Hacker Newsnew | past | comments | ask | show | jobs | submit | more BiteCode_dev's commentslogin

A twitter account RT with emoji, people block it because it has no value, and it's called news?

Don't get me wrong, I find it funny. The current trend of humble brag is a good topic to laugh about.

But do you want an entire article about this? Do you want that to be on HN front page?

There are thousands of such joke accounts. Are we going to post about them all?


A HN comment that adds nothing to the discussion, people post it because they need to pat themselves on the back, and it's upvoted?

Don't get me wrong, I find your comment OK. The current trend of garbage comments with no content on HN is a good topic to laugh about.

But do you want an entire comment about this? Do you want that to be in an HN thread?

There are thousands of such joke accounts. Are you going to comment about them all?


[clap emoji] [clap emoji] [clap emoji]


> There are thousands of such joke accounts. Are we going to post about them all?

How about we deal with them on a case by case basis? Why this rush to post about them all or flag them all?


Yes, we're going to post about them all.


Did... This hit a nerve?


I get that this guide tries to ease you in into low level concurrency concepts.

However, if you try to just get work done in Python, this is not what you want.

Don't do threads/processes yourself, use pools:

    import random
    import time
    from concurrent.futures import ProcessPoolExecutor, as_completed

    def hello():
        seconds = random.randint(0, 5)
        print(f"Start blocking for {seconds}s")
        time.sleep(seconds)
        print(f"Stopped blocking after {seconds}s")
        return seconds

    if __name__ == "__main__":

        with ProcessPoolExecutor(max_workers=2) as exec:

            a = exec.submit(hello)
            b = exec.submit(hello)

            for future in as_completed((a, b)):
                print(future.result())
And don't manage the loop yourself. Use Python 3.7, and replace:

    loop = asyncio.get_event_loop()
    loop.run_until_complete(loop.create_task(foo()))
    loop.close()
With: asyncio.run(foo())

The code is not just shorter, it is way, wayyyyyyyyyyyy, more correct.

Also don't program asyncio by hand. Use a lib. E.G: wanna do http, use aiohttp.

This is Python, don't suffer more than you need to.


I agree with you. We should use a reliable library, as you said. The primary purpose of this article is to help people understand what a coroutine and an event loop are. Therefore, programmers can use asyncio API fluently without misuse.

However, I don't think use threads/processes is a bad idea. A pool gives you a constrain to utilize threads/processes, but sometime we may want to adjust the number of threads/processes based on system load. Under this circumstance, using a pool is not the best choice.


You’re sending the poor newbie on a journey of self-discovering of picklable-non-picklable, passing of arguments back and forth, working with Queues (which have well-known yet undocumented race conditions), missing exception stack traces due to dead processes and all sorts of useless garbage they don’t need to know about.

Also what exactly would that newbie be building that starts and stops threads depending on the system load? What kind of a contraption is that? What are you doing?

Finallizing all of the above: under the circumstance you mentioned, you should check whether you have just seriously over-architected the solution.


I understand you are worried about newbies misuse APIs. You remind me that I should add a warning to inform the sample code in this article should not use in programs. Thanks.

Also, I did not advocate a newbie should start and stop threads by themselves. I want to say I agree that we should use high-level APIs in most cases, but, in some cases, we may need to use low-level APIs to achieve our missions. I am unwilling to limit what kind of APIs should use. In my opinion, like you said: "you have just seriously over-architected the solution," we should be careful to use APIs. Even though high-level APIs are safer, programmers may misuse them.


Just create a new pool and close the previous one, depending of the system load.


I think this is not an excellent solution. You have to wait for all threads finish. I agree that we should use high-level API in most of the time, but, in some cases, we still need low-level APIs to support us to reach some goals.


+1 for this, Aio libs make all of this so effortless - aiohttp, aiopg, aiomysql, aiobotocore, I’m about to try aiokafka next.

Just an effortless programming experience.


Python always could use multiprocessing to do parallel processing leveraging several CPU.

However, it became especially easy with Python 3.2 (10 years ago) which introduced the ProcessPoolExecutor (https://docs.python.org/dev/library/concurrent.futures.html#...):

    import random
    import time
    from concurrent.futures import ProcessPoolExecutor, as_completed


    def hello():
        seconds = random.randint(0, 5)
        print(f"Start blocking for {seconds}s")
        time.sleep(seconds)
        print(f"Stopped blocking after {seconds}s")
        return seconds

    if __name__ == "__main__":

        with ProcessPoolExecutor(max_workers=2) as exec:

            a = exec.submit(hello)
            b = exec.submit(hello)

            for future in as_completed((a, b)):
                print(future.result())
The same exact same API exist for thread BTW. I don't think a tutorial should introduce you to concurrency using manual process/thread management any more. I makes no sense to me.

You may note that multiprocessing still eats more RAM than with typical Go/Rust code since max_workers=n means n+1 Python VM spawing but on modern servers you don't really feel it. That's what most WSGI setup do anyway.

Now, before 2019, there was one more use case that wasn't served well: how do you share some computation between isolated processes that need to communicate to make their work ? Typical use case was people using numpy or pandas crunching numbers that depended on each others. Indeed, communicating between processing using piping is expensive given the cost of message passing serialization.

However, in the previous Python release (3.8), we introduced a mechanism to share memory for almost free (https://docs.python.org/3/library/multiprocessing.shared_mem...):

    from multiprocessing.managers import SharedMemoryManager

    with SharedMemoryManager() as smm:
        sl = smm.ShareableList(name="unique_name", range(2000))
The sl object can then contain int, float, bool, str, bytes and None and its reference can be shared among processes. Each item can be deleted and replaced. You an also get an hold on sl by using the "unique_name" if you don't have the reference at hand.

There is a raw ShareableMemory object for stuff like numpy/pandas array buffers if this is your main concern.


Thank you for this. I did not know of this change in implementation in Python 3.8.

Are you a core dev btw? I have a complaint about single threads and processes and how they have absolutely no way to return values back to the main thread except through some shared memory object. Am I too ignorant to understand how big of a challenge it is to do this?

  from threading import Thread

  def func1(*args):
     #something

  def main():
     new_thread, return_val = Thread(target=func1, args=(1, 2))
     new_thread.start()
     new_thread.join()
     print(return_val)
Instead to implement this, I keep having to use like single process pools that already have return mechanisms encoded. All I need is for a way of starting off a thread (or process) and joining it once my main thread / process is done and retrieving its return value for my use (assuming there is one).


Not a core dev.

The clean way to return a value is to pass it to a Queue (https://docs.python.org/fr/3/library/queue.html), and this is what the executor does, but for your use case, it's overkill.

For very simple use cases, you can inherit from Thread and force join() to return the value:

    class SimpleReturningThread(Thread):
        result = None
        def run(self):
            try:
                if self._target:
                    self.result = self._target(*self._args, **self._kwargs)
            finally:
                del self._target, self._args, self._kwargs
        def join(self, *args, **kwargs):
            super().join(*args, **kwargs)
            return self.result

Personally, I'd stick to using a pool with only one worker in it. It's not worth the trouble of doing all this work. Wrap it in a few functions if you do the same thing repeatedly and call it a day, it's unlikely going to be what most your code is about anyway.


Thanks for the detailed answer.

Correct me if I'm wrong, but from what you've said I take it that the GIL issue has not been resolved (i.e. the Python interpreter is not thread-safe, Python still can't have a single process, with a single Python interpreter, running multiple CPU-bound threads all doing useful compute in Python, running against a single unified local memory space containing all of the objects, as you would in say C or C++). The only option is to resort to more elaborate schemes involving multiple processes, multiple interpreters, and explicitly managed shared memory windows -- but all of these options are in place now, so there is at least a solution to most common use cases, even if it's not as simple as in other languages with proper support for threads and shared local memory.


There are been many attempt to create a different design without the GIL. None of them made it to cPython.

The whole language assume it's safe to mutate things around. E.G: list.append() is assumed to be thread safe.


Yes, but doing so, they will lose the ability to be indexed, searched, archived and linked to. Like during the flash era.

Which in turn will start a new trend of website that are "open".

It's a cycle.


> they will lose the ability to be indexed, searched, archived and linked to

Sounds like an API that will be implemented.


If it's not standard, it will be useless. If it is, the browser will eventually put it in the users hand.


Crawler bots are already doing site rendering and OCR. This isn't that big of a step for them.


TIL. Wow. I guess I missed the web is not HTML anymore.


Plenty of sites already give Google something different from what they show everyone else, right?


No, that's actually a great way to make Google penalize your site. It's explicitly against their Webmaster Guidelines: https://support.google.com/webmasters/answer/66355


Tell that to linkedin, pinterest, and dozens of news sites.


Linkedin used to trick people into thinking you have to pay to see someones profile when you can see it just fine by logging out. That is not against Googles policy. Not sure if they still do that, but I used the logout trick a lot a few years ago.


Google does document a way to mark paywalled content and have it indexed without it being considered cloaking: https://developers.google.com/search/docs/data-types/paywall...


Big properties do that and Google doesn't care.


You sure about that? How big qualifies as big in your eyes? Medium implemented homepage cloaking in November of 2019 and within a month they lost 40% of their overall search visibility:

https://www.onely.com/blog/medium-lost-half-visibility/


Pinterest? Google is somehow able to crawl images on their site, but I certainly can't view these images without creating an account and logging in. Their site ranks highly enough that I gave up on google image search last year.

Additionally, off the top of my head Bloomberg and NYT both won't allow me to view more than a few articles but let the Google crawler index their articles.


Yes Pinterest is awful. Certain categories of images are totally borked on Google and other search engines because of them.


I thought that was an offense that would get one either severely de-ranked or delisted from search outright?


What do paywalled sites do, then? They don't seem to have a problem ranking just fine.


They show the abstract or the same bit of the headline and maybe a paragraph you see when hitting the page. Googlebot doesn't get the full text.


I've definitely seen article text on Google that was not presented to me when I clicked the link, and not because the article was updated or something, but because I was blocked from seeing the article.


It could be in a hidden element or something.. I find that pages that do this fall in the face of things like safari reader mode.


Many "paywalled" sites lose their paywall if you disable JS.


There are many cases where what you need is instant soup powder, not home made velouté.

And this will save me from writing tests for those lines. With all major browsers. And documentation. And maintain all that, of course, for the next 5 years.

And when new devs will arrive in the team to provide the training for the custom code. I may even not be here anymore

So yes, it can be overkill, or just what you need.

E.G: some server side dev need a quick fix for his personal web site.

Besides, even a lib with zero tests like this one will have enough users and tickets open that it will be better tested that the server side dev code that don't know JS much.


Startup idea: use machine learning to scan social networks and detect PR campaigns, submarine pieces, fake reviews, etc.


This should be a state provided service. Or provided by the UN. Essential stuff like this or root DNS should be a planetary responsibility.


In a lot of countries, giving the government the ability to issue SSL certificates would be a catastrophe in terms of surveillance and censorship.


Didn't think of that.

It doesn't have to be just the state or the UN though. It's not about removing all the other actors on the market.

But if I make a website on Python programming in french, I'm quite ok using the french gov as a CA provider.

I mean, I trust mozilla because it's mozilla. But I wouldn't trust most companies.


There was an incident just last year with Kazakhstan:

https://bugzilla.mozilla.org/show_bug.cgi?id=1567114

Not exactly the same as for-website certificates but in the same realm of government certificate issuance.


The problem is, there’s no way to enforce this. If you are a CA, there is nothing technically stopping you from issuing a certificate for google.com. There’s no infrastructure for the ability to say “this CA is valid only for sites that agree with the risks involved in using it”.


Actually, I believe there are. IIRC it's possible for a CA's root cert to be limited to only a certain TLD. There's an extension called "Name Constraints" that limits a Root SSL Cert, and I believe it is honored by chrome.

https://security.stackexchange.com/questions/31376/can-i-res...


It's an optional extension, so a client may ignore it without failing the connection. It needs a lot more adoption. I could, for example, instead of getting a wildcard cert, get LE to sign a CA valid for my domain. That way I can issue certs for my domain myself and put load off of LE.


Actually Firefox for example carries around code to arbitrarily set any restrictions on any of the root CAs in Mozilla's trust store.

These are documented, on a best effort basis, at:

https://wiki.mozilla.org/CA/Additional_Trust_Changes

It is true, however, that no equivalent rules are enforced in most generic TLS clients (e.g. using OpenSSL directly or something like Python).


Protocols allow for namespace restrictions on CA certificates. There could, in concept, be something stopping you from spoofing google.

https://www.ietf.org/rfc/rfc2459.txt - section 4.2.1.11, Name Constraints

Given that I don't think you can actually buy that kind of cert, and the term "CA" is accepted to imply "universal CA", you're correct.


I'm by no means an expert, but I believe Certificate Transparency provides a way to catch that rogue CA after the fact.


Only if the certificate authority doesn't implement a way of not submitting their cert to the CT log servers. Of course, eventually someone might notice (if the certificate is used widely enough - if it's used to attack specific known people, maybe not) and realise that a certificate is being served that doesn't have corresponding CT info, but browsers don't check that.


Browser can check that a cert has an equivalent CT Log entry. Chrome does since 2018. https://tools.ietf.org/html/rfc6962#section-3.3 https://groups.google.com/a/chromium.org/forum/#!msg/ct-poli...


The ct-policy link you gave and that section of RFC 6962 are about SCTs. The existence of the Signed Certificate Timestamp does not prove the certificate was actually logged, it just proves that the Log promises to log this certificate within the Maximum Merge Delay (24 hours in the case of the Web PKI). A log might in fact be lying or have suffered a grave technical problem.

Figuring out how best to have browsers check the logs are truly accurate while preserving user privacy (e.g. obviously if you call a log to ask "Did you log this certificate for clown-porn.example ?" it gives them a good idea about your taste in circus-related adult content which you probably don't want them to have) is an ongoing topic of research.

With SCT checks you're in very good shape already today - bad guys would need to compromise several distinct entities to successfully pull this off. It's just not quite "Fire and forget" safe yet.


If the certificate wasn't submitted to an otherwise trustworthy CT log server then there's no way to provide an SCT ("Signed Certificate Timestamp") for a qualified CT log server. Some browsers (including Chrome and Safari) expect to be shown qualified SCTs for certificates issued after a certain date.

The SCT is signed by the log, so if you want them to lie you'd need to control enough logs to get enough qualified SCTs. Bad news, for Chrome that means it must include a Google log, which means now you're asking Google to conspire against themselves.

For now you could sidestep this by issuing bogus certificates with back-dated issuance dates. But that will stop working once those dates are too long ago for a certificate to still be valid. I think that happens some point later this year or in 2021 maybe? If you show Chrome (perhaps other browsers but I've read the code in Chrome) a certificate in which the lifespan (between NotBefore and NotAfter) exceeds the maximum permissible lifespan at that issuance date, it treats the certificate as invalid anyway.


This Mozilla isn’t the Mozilla from back in day.

It’s hard to imagine the old Mozilla enabling DNS over HTTPS by default to Cloudflare, with DoH’s tracking issues: https://labs.ripe.net/Members/bert_hubert/centralised-doh-is...


In all countries, giving the government the ability to issue SSL certificates would be a catastrophe in terms of surveillance and censorship.

FTFY


By the way, there have been a number of openly government-operated root CAs in numerous countries for decades. Before I got involved with Let's Encrypt, I was very nervous about government influence in PKI and thought this was quite concerning. (That was also before Certificate Transparency.)

A quick look at a root store turns up

subject=C = CN, O = China Financial Certification Authority, CN = CFCA EV ROOT

subject=C = HK, O = Hongkong Post, CN = Hongkong Post Root CA 1

subject=C = NL, O = Staat der Nederlanden, CN = Staat der Nederlanden EV Root CA [and other roots with the same organization]

subject=C = TW, O = Government Root Certification Authority

I think there are several others, probably especially at the intermediate level.


Just what we need is to get politicians involved in this.

One benefit thought would be they could more easily block access to sites they don't want folks visiting by just denying a CA cert (which would then generate warnings / blocking in many browsers).


One benefit? Did you mean to say "the most obvious downside" instead?


Ok, the more I read answers to my comment, the less I think it's a good idea.


Looks like your browser didn't render the <sarcasm> tags.


> planetary responsibility.

I would like to hear from the planetary president to see what he has to say about that.

Seriously this is all great but unfortunately with all the mess going on with "the big powers" I'm not sure you want to give them that. I wished we lived in a world where we could tho.


Oh, you mean like the state provided service that is trying to sell off the .org domain registry right now?


Cloud flare is American and we know since the PRISM scandal that US based tech companies are directly plugged into the NSA, and everybody in the chain will deny it under the threat of prison.

So, if this rolls out 'as-is' in any other country than the US, we will go from "all DNS requests are clear text, but dispatched among many entities" to "DNS requests are encrypted, but all read and controlled by american agencies".

We (may) have gain (some) privacy (maybe). But we also (certainly) gained a serious dependency.


NSA don’t factor into my personal threat model _at all_ where random ISPs snooping and selling do. I would gladly give the NSA all of my traffic unencrypted in exchange for decent commercial privacy


I supposed not having a dictatorship regime in your country history book helps to see things that way.

Given the way my country went from freedom to "regime de Vichy" in a few years, during my grandpa time, I don't want a state level entity having that kind of power.

Since the US state level entities decided they could now ignore Habeas Corpus and legitimated torture, secret courts and declared impunity for them-self, I especially don't want them to have that kind of power.


If a malicious power takes over your country they’ll hit you with a rubber hose until you give up your secrets much before they give a shit about your internet history, I suspect.


Quite the contrary, as shown by as most dictatorships across the world trying to control their piece of the internet. The biggest example being the Big Firewall of China.

This let them control how people think, communicate, consume and inform them-self. But also detects anyone that could oppose the regime. Or make a graph of all allies, suspects, etc.

Then you hit them with a rubber hose :)


That is the case if they are targeting you, what you should likely worry about is if they take interest in you.


They only enabled it by default for US users, so at this time it doesn't really matter. shrugs

When they roll out in the EU, I will pay close attention to how they are doing it, what partners they use under what jurisdictions etc.


Same.

Gotta also make sure I don't get a US Firefox build somehow.


You can always disable DNS-over-HTTPS in the network preferences, or set or own resolver, e.g. https://news.ycombinator.com/item?id=22412656

But good point, now I am curious how they detect US-ness. Probably a combination of using the en-US and some geo lookup?


The page, which you didn't read, specifically makes the point that they have no plans to roll this out (by default) anywhere except for the US.


Nowhere it says they have no plan of doing it. They just release it only for the US __build__, __by default__, __now__.

But to make things more honest, I'll edit my comment.


I don't think it is. If JS had any sane competition, I think it would have lost. By some weird conjunction of events, it landed a monopoly on the most amazing plateform in the world.

PHP is a good example of Worse is Better, because it won over the competition, despite its flaws.

HTML vs xHTML as well. Bash, maybe?

But JS didn't win. It was the only one there.


What? JS had loads of competition back then. VBScript, Flash, and Java applets, just to name a few ways to get interactivity on a browser.


"sane" is the keyword here.

The alternative all depended on non technical users with slow connections to install the runtime.

Js code was guaranteed to work anywhere, and with no requirements, giving it practical monopoly.


Most server side code is Java, quickly followed by PHP.

And of course next to JS, you have C#, Asp.Net, Ruby, Python, and Go.

I'd say that given that:

- a lot of people only know JS (like designers)

- JS has a monopoly on the front end and is the only language that can be used on the front and back

- JS has existed for as long as Java (C#, Ruby and Go are way younger)

- there are JS materials everywhere given the web popularity

- the web is the most popular plateform in the world

The fact, as a freelancer going from company to company, I see so little JS on the server compared to other languages tells a lot.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: