all repos — gemini-redirect @ 772f5df37f7bd727dd575ea042b6d87b9b2e2529

Actually generate site
Lonami Exo totufals@hotmail.com
Sat, 03 Oct 2020 13:08:31 +0200
commit

772f5df37f7bd727dd575ea042b6d87b9b2e2529

parent

0b267f51260b59f9c40f193d688f4c01f696328f

M blog/asyncio/index.htmlblog/asyncio/index.html

@@ -10,15 +10,15 @@ <body>

<main> <h1 class="title" id="an_introduction_to_asyncio"><a class="anchor" href="#an_introduction_to_asyncio">¶</a>An Introduction to Asyncio</h1> <div class="date-created-modified">Created 2018-06-13<br> -Modified 2018-06-15</div> +Modified 2020-10-03</div> <h2 id="index"><a class="anchor" href="#index">¶</a>Index</h2> <ul> <li><a href="#background">Background</a></li> -<li><a href="#inputoutput">Input / Output</a></li> -<li><a href="#divingin">Diving In</a></li> -<li><a href="#toyexample">A Toy Example</a></li> -<li><a href="#example">A Real Example</a></li> -<li><a href="#extra">Extra Material</a></li> +<li><a href="#input_output">Input / Output</a></li> +<li><a href="#diving_in">Diving In</a></li> +<li><a href="#a_toy_example">A Toy Example</a></li> +<li><a href="#a_real_example">A Real Example</a></li> +<li><a href="#extra_material">Extra Material</a></li> </ul> <h2 id="background"><a class="anchor" href="#background">¶</a>Background</h2> <p>After seeing some friends struggle with <code>asyncio</code> I decided that it could be a good idea to write a blog post using my own words to explain how I understand the world of asynchronous IO. I will focus on Python's <code>asyncio</code> module but this post should apply to any other language easily.</p>

@@ -33,32 +33,46 @@ line 5

</code></pre> <p>And you start two threads to run the method at the same time. What is the order in which the lines of code get executed? The answer is that you can't know! The first thread can run the entire method before the second thread even starts. Or it could be the first thread that runs after the second thread. Perhaps both run the &quot;line 1&quot;, and then the line 2. Maybe the first thread runs lines 1 and 2, and then the second thread only runs the line 1 before the first thread finishes.</p> <p>As you can see, any combination of the order in which the lines run is possible. If the lines modify some global shared state, that will get messy quickly.</p> -<p>Second, in Python, threads <em>won't</em> make your code faster. It will only increase the concurrency of your program, allowing you to run several things at the same time, so using threads for speed isn't a real advantage. Indeed, your code will probably run slower under the most common Python implementation, CPython, which makes use of a Global Interpreter Lock (GIL) that only lets a thread run at once.</p> +<p>Second, in Python, threads <em>won't</em> make your code faster most of the time. It will only increase the concurrency of your program (which is okay if it makes many blocking calls), allowing you to run several things at the same time.</p> +<p>If you have a lot of CPU work to do though, threads aren't a real advantage. Indeed, your code will probably run slower under the most common Python implementation, CPython, which makes use of a Global Interpreter Lock (GIL) that only lets a thread run at once. The operations won't run in parallel!</p> <h2 id="input_output"><a class="anchor" href="#input_output">¶</a>Input / Output</h2> <p>Before we go any further, let's first stop to talk about input and output, commonly known as &quot;IO&quot;. There are two main ways to perform IO operations, such as reading or writing from a file or a network socket.</p> <p>The first one is known as &quot;blocking IO&quot;. What this means is that, when you try performing IO, the current application thread is going to <em>block</em> until the Operative System can tell you it's done. Normally, this is not a problem, since disks are pretty fast anyway, but it can soon become a performance bottleneck. And network IO will be much slower than disk IO!</p> -<pre><code class="language-python"># &quot;open&quot; will block until the OS creates a new file in the disk. -# this can be really slow if the disk is under heavy load! -with open('hello.txt', 'w') as fd: - fd.write('hello!\n') +<pre><code class="language-python">import socket - # &quot;flush&quot; will block until the OS has written all data to disk* - fd.flush() +# Setup a network socket and a very simple HTTP request. +# By default, sockets are open in blocking mode. +sock = socket.socket() +request = b'''HEAD / HTTP/1.0\r +Host: example.com\r +\r +''' + +# &quot;connect&quot; will block until a successful TCP connection +# is made to the host &quot;example.com&quot; on port 80. +sock.connect(('example.com', 80)) + +# &quot;sendall&quot; will repeatedly call &quot;send&quot; until all the data in &quot;request&quot; is +# sent to the host we just connected, which blocks until the data is sent. +sock.sendall(request) + +# &quot;recv&quot; will try to receive up to 1024 bytes from the host, and block until +# there is any data to receive (or empty if the host closes the connection). +response = sock.recv(1024) -# * the reality is a bit more complicated, since writes to disk are -# quite expensive, the OS will normally keep the data in RAM until -# it has more stuff to write to disk, and then it will `sync` -# everything after a few seconds +# After all those blocking calls, we got out data! These are the headers from +# making a HTTP request to example.com. +print(response.decode()) </code></pre> <p>Blocking IO offers timeouts, so that you can get control back in your code if the operation doesn't finish. Imagine that the remote host doesn't want to reply, your code would be stuck for as long as the connection remains alive!</p> <p>But wait, what if we make the timeout small? Very, very small? If we do that, we will never block waiting for an answer. That's how asynchronous IO works, and it's the opposite of blocking IO (you can also call it non-blocking IO if you want to).</p> <p>How does non-blocking IO work if the IO device needs a while to answer with the data? In that case, the operative system responds with &quot;not ready&quot;, and your application gets control back so it can do other stuff while the IO device completes your request. It works a bit like this:</p> -<pre><code class="language-python">&amp;lt;app&amp;gt; Hey, I would like to read 16 bytes from this file -&amp;lt;OS&amp;gt; Okay, but the disk hasn't sent me the data yet -&amp;lt;app&amp;gt; Alright, I will do something else then +<pre><code>&lt;app&gt; Hey, I would like to read 16 bytes from this file +&lt;OS&gt; Okay, but the disk hasn't sent me the data yet +&lt;app&gt; Alright, I will do something else then (a lot of computer time passes) -&amp;lt;app&amp;gt; Do you have my 16 bytes now? -&amp;lt;OS&amp;gt; Yes, here they are! &quot;Hello, world !!\n&quot; +&lt;app&gt; Do you have my 16 bytes now? +&lt;OS&gt; Yes, here they are! &quot;Hello, world !!\n&quot; </code></pre> <p>In reality, you can tell the OS to notify you when the data is ready, as opposed to polling (constantly asking the OS whether the data is ready yet or not), which is more efficient.</p> <p>But either way, that's the difference between blocking and non-blocking IO, and what matters is that your application gets to run more without ever needing to wait for data to arrive, because the data will be there immediately when you ask, and if it's not yet, your app can do more things meanwhile.</p>

@@ -87,8 +101,53 @@ </div>

<p> <p>Start reading the code of the event loop and follow the arrows. You can see that, in the beginning, there are no events yet, so the loop calls one of your functions. The code runs until it has to <code>await</code> for some IO operation to complete, such as sending a request over the network. The method is &quot;paused&quot; until an event occurs (for example, an &quot;event&quot; occurs when the request has been sent completely).</p> <p>While the first method is busy, the event loop can enter the second method, and run its code until the first <code>await</code>. But it can happen that the event of the second query occurs before the request on the first method, so the event loop can re-enter the second method because it has already sent the query, but the first method isn't done sending the request yet.</p> -<p>Then, the second method <code>await</code>'s for an answer, and an event occurs telling the event loop that the request from the first method was sent. The code can be resumed again, until it has to <code>await</code> for a response, and so on.</p> -<p>There are some important things to note here. The first is that we only need one thread to be running! The event loop decides when and which methods should run. The second is that we know when it may run other methods. Those are the <code>await</code> keywords! Whenever there is one of those, we know that the loop is able to run other things until the resource (again, like network) becomes ready.</p> +<p>Then, the second method <code>await</code>'s for an answer, and an event occurs telling the event loop that the request from the first method was sent. The code can be resumed again, until it has to <code>await</code> for a response, and so on. Here's an explanation with pseudo-code for this process if you prefer:</p> +<pre><code class="language-python">async def method(request): + prepare request + await send request + + await receive request + + process request + return result + +run in parallel ( + method with request 1, + method with request 2, +) +</code></pre> +<p>This is what the event loop will do on the above pseudo-code:</p> +<pre><code>no events pending, can advance + +enter method with request 1 + prepare request + await sending request +pause method with request 1 + +no events ready, can advance + +enter method with request 2 + prepare request + await sending request +pause method with request 2 + +both requests are paused, cannot advance +wait for events +event for request 2 arrives (sending request completed) + +enter method with request 2 + await receiving response +pause method with request 2 + +event for request 1 arrives (sending request completed) + +enter method with request 1 + await receiving response +pause method with request 1 + +...and so on +</code></pre> +<p>You may be wondering &quot;okay, but threads work for me, so why should I change?&quot;. There are some important things to note here. The first is that we only need one thread to be running! The event loop decides when and which methods should run. This results in less pressure for the operating system. The second is that we know when it may run other methods. Those are the <code>await</code> keywords! Whenever there is one of those, we know that the loop is able to run other things until the resource (again, like network) becomes ready (when a event occurs telling us it's ready to be used without blocking or it has completed).</p> <p>So far, we already have two advantages. We are only using a single thread so the cost for switching between methods is low, and we can easily reason about where our program may interleave operations.</p> <p>Another advantage is that, with the event loop, you can easily schedule when a piece of code should run, such as using the method <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_at"><code>loop.call_at</code></a>, without the need for spawning another thread at all.</p> <p>To tell the <code>asyncio</code> to run the two methods shown above, we can use <a href="https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future"><code>asyncio.ensure_future</code></a>, which is a way of saying &quot;I want the future of my method to be ensured&quot;. That is, you want to run your method in the future, whenever the loop is free to do so. This method returns a <code>Future</code> object, so if your method returns a value, you can <code>await</code> this future to retrieve its result.</p>
M blog/atom.xmlblog/atom.xml

@@ -1,29 +1,4 @@

-<feed xmlns="http://www.w3.org/2005/Atom"><title>pagong</title><id>pagong</id><updated>2020-08-23T22:00:00+00:00</updated><entry><title>Making a Difference</title><id>dist/making-a-difference/index.html</id><updated>2020-08-23T22:00:00+00:00</updated><published>2020-08-23T22:00:00+00:00</published><summary>When I've thought about what "making a difference" means, I've always seen it as having to do something at very large scales. Something that changes everyone's lives. But I've realized that it doesn't need the case.</summary><content type="html" src="dist/making-a-difference/index.html">&lt;!DOCTYPE html&gt; -&lt;html&gt; -&lt;head&gt; -&lt;meta charset=&quot;utf-8&quot; /&gt; -&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt; -&lt;title&gt;Making a Difference&lt;/title&gt; -&lt;link rel=&quot;stylesheet&quot; href=&quot;../css/style.css&quot;&gt; -&lt;/head&gt; -&lt;body&gt; -&lt;main&gt; -&lt;h1 class=&quot;title&quot; id=&quot;making_a_difference&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#making_a_difference&quot;&gt;¶&lt;/a&gt;Making a Difference&lt;/h1&gt; -&lt;div class=&quot;date-created-modified&quot;&gt;2020-08-24&lt;/div&gt; -&lt;p&gt;When I've thought about what &amp;quot;making a difference&amp;quot; means, I've always seen it as having to do something at very large scales. Something that changes everyone's lives. But I've realized that it doesn't need the case.&lt;/p&gt; -&lt;p&gt;I'm thinking about certain people. I'm thinking about middle-school.&lt;/p&gt; -&lt;p&gt;I'm thinking about my math teacher, who I remember saying that if he made a student fail with a grade very close to passing, then he would be a bad teacher because he could just &amp;quot;let them pass&amp;quot;. But if he just passed that one student, he would fail as a teacher, because it's his job to get people to actually &lt;em&gt;learn&lt;/em&gt; his subject. He didn't want to be mean, he was just trying to have everybody properly learn the subject. That made a difference on me, but I never got the chance to thank him.&lt;/p&gt; -&lt;p&gt;I'm thinking about my English teacher, who has had to put up with a lot of stupidity from the rest of students, making the class not enjoyable. But I thought she was nice, and she thought I was nice. I remember of a day when she was grading my assignement and debating what grade I should get. I thought to myself, she should just grade whatever she considered fair. But she went something along the lines of &amp;quot;what the heck, you deserve it&amp;quot;, and graded in my favour. I think of her as an honest person who also just wants to make other people learn, despite the other students not liking her much. I never got a chance to thank her.&lt;/p&gt; -&lt;p&gt;I'm thinking about my philosophy teacher, who was a nice chap. He tried to make the lectures fun and had some really interesting ways of thinking. He was nice to talk to overall, but I never got to thank him for what he taught us.&lt;/p&gt; -&lt;p&gt;I'm thinking about one of my lecturers at university who has let me express my feelings to her and helped me make the last push I needed to finish my university degree (I was really dreading some subjects and considering dropping out, but those days are finally over).&lt;/p&gt; -&lt;p&gt;I'm thinking about all the people who has been in a long-distance relationship with me. None of the three I've had have worked out in the long-term so far, and I'm in a need of a break from those. But they were really invaluable to help me grow and learn a lot about how things actually work. I'm okay with the first two people now, maybe the third one can be my friend once more in the future as well. I'm sure I've told them how important they have been to me and my life.&lt;/p&gt; -&lt;p&gt;I'm thinking about all the people who I've met online and have had overall a healthy relation, sharing interesting things between each other, playtime, thoughts, and other various lessons.&lt;/p&gt; -&lt;p&gt;What I'm trying to get across is that you may be more impactful than you think you really are. And even if people don't say it, some are extremely thankful of your interactions with them. You can see this post as a sort of a &amp;quot;call for action&amp;quot; to be more thankful to the people that have affected you in important ways. If people take things for granted because they Just Work, the person who made those things should be proud of this achievement.&lt;/p&gt; -&lt;p&gt;Thanks to all of them, to everyone who has shared good moments with me, and to all the people who enjoy the things I make.&lt;/p&gt; -&lt;/main&gt; -&lt;/body&gt; -&lt;/html&gt; - </content></entry><entry><title>Atemporal Blog Posts</title><id>dist/posts/index.html</id><updated>2020-08-23T22:00:00+00:00</updated><published>2020-08-23T22:00:00+00:00</published><summary>These are some interesting posts and links I've found around the web. I believe they are quite interesting and nice reads, so if you have the time, I encourage you to check some out.</summary><content type="html" src="dist/posts/index.html">&lt;!DOCTYPE html&gt; +<feed xmlns="http://www.w3.org/2005/Atom"><title>pagong</title><id>pagong</id><updated>2020-10-02T22:00:00+00:00</updated><entry><title>Atemporal Blog Posts</title><id>dist/posts/index.html</id><updated>2020-10-02T22:00:00+00:00</updated><published>2020-10-02T22:00:00+00:00</published><summary>These are some interesting posts and links I've found around the web. I believe they are quite interesting and nice reads, so if you have the time, I encourage you to check some out.</summary><content type="html" src="dist/posts/index.html">&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot; /&gt;

@@ -34,7 +9,7 @@ &lt;/head&gt;

&lt;body&gt; &lt;main&gt; &lt;h1 class=&quot;title&quot; id=&quot;atemporal_blog_posts&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#atemporal_blog_posts&quot;&gt;¶&lt;/a&gt;Atemporal Blog Posts&lt;/h1&gt; -&lt;div class=&quot;date-created-modified&quot;&gt;2020-08-24&lt;/div&gt; +&lt;div class=&quot;date-created-modified&quot;&gt;2020-10-03&lt;/div&gt; &lt;p&gt;These are some interesting posts and links I've found around the web. I believe they are quite interesting and nice reads, so if you have the time, I encourage you to check some out.&lt;/p&gt; &lt;h2 id=&quot;algorithms&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#algorithms&quot;&gt;¶&lt;/a&gt;Algorithms&lt;/h2&gt; &lt;ul&gt;

@@ -124,7 +99,33 @@ &lt;/ul&gt;

&lt;/main&gt; &lt;/body&gt; &lt;/html&gt; - </content></entry><entry><title>University posts</title><id>dist/university/index.html</id><updated>2020-08-23T22:00:00+00:00</updated><published>2020-07-02T22:00:00+00:00</published><summary>During university, there were a few subjects where I had to write blog posts for (either as</summary><content type="html" src="dist/university/index.html">&lt;!DOCTYPE html&gt; + </content></entry><entry><title>Making a Difference</title><id>dist/making-a-difference/index.html</id><updated>2020-10-02T22:00:00+00:00</updated><published>2020-08-23T22:00:00+00:00</published><summary>When I've thought about what "making a difference" means, I've always seen it as having to do something at very large scales. Something that changes everyone's lives. But I've realized that it doesn't need the case.</summary><content type="html" src="dist/making-a-difference/index.html">&lt;!DOCTYPE html&gt; +&lt;html&gt; +&lt;head&gt; +&lt;meta charset=&quot;utf-8&quot; /&gt; +&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt; +&lt;title&gt;Making a Difference&lt;/title&gt; +&lt;link rel=&quot;stylesheet&quot; href=&quot;../css/style.css&quot;&gt; +&lt;/head&gt; +&lt;body&gt; +&lt;main&gt; +&lt;h1 class=&quot;title&quot; id=&quot;making_a_difference&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#making_a_difference&quot;&gt;¶&lt;/a&gt;Making a Difference&lt;/h1&gt; +&lt;div class=&quot;date-created-modified&quot;&gt;Created 2020-08-24&lt;br&gt; +Modified 2020-10-03&lt;/div&gt; +&lt;p&gt;When I've thought about what &amp;quot;making a difference&amp;quot; means, I've always seen it as having to do something at very large scales. Something that changes everyone's lives. But I've realized that it doesn't need the case.&lt;/p&gt; +&lt;p&gt;I'm thinking about certain people. I'm thinking about middle-school.&lt;/p&gt; +&lt;p&gt;I'm thinking about my math teacher, who I remember saying that if he made a student fail with a grade very close to passing, then he would be a bad teacher because he could just &amp;quot;let them pass&amp;quot;. But if he just passed that one student, he would fail as a teacher, because it's his job to get people to actually &lt;em&gt;learn&lt;/em&gt; his subject. He didn't want to be mean, he was just trying to have everybody properly learn the subject. That made a difference on me, but I never got the chance to thank him.&lt;/p&gt; +&lt;p&gt;I'm thinking about my English teacher, who has had to put up with a lot of stupidity from the rest of students, making the class not enjoyable. But I thought she was nice, and she thought I was nice. I remember of a day when she was grading my assignement and debating what grade I should get. I thought to myself, she should just grade whatever she considered fair. But she went something along the lines of &amp;quot;what the heck, you deserve it&amp;quot;, and graded in my favour. I think of her as an honest person who also just wants to make other people learn, despite the other students not liking her much. I never got a chance to thank her.&lt;/p&gt; +&lt;p&gt;I'm thinking about my philosophy teacher, who was a nice chap. He tried to make the lectures fun and had some really interesting ways of thinking. He was nice to talk to overall, but I never got to thank him for what he taught us.&lt;/p&gt; +&lt;p&gt;I'm thinking about one of my lecturers at university who has let me express my feelings to her and helped me make the last push I needed to finish my university degree (I was really dreading some subjects and considering dropping out, but those days are finally over).&lt;/p&gt; +&lt;p&gt;I'm thinking about all the people who has been in a long-distance relationship with me. None of the three I've had have worked out in the long-term so far, and I'm in a need of a break from those. But they were really invaluable to help me grow and learn a lot about how things actually work. I'm okay with the first two people now, maybe the third one can be my friend once more in the future as well. I'm sure I've told them how important they have been to me and my life.&lt;/p&gt; +&lt;p&gt;I'm thinking about all the people who I've met online and have had overall a healthy relation, sharing interesting things between each other, playtime, thoughts, and other various lessons.&lt;/p&gt; +&lt;p&gt;What I'm trying to get across is that you may be more impactful than you think you really are. And even if people don't say it, some are extremely thankful of your interactions with them. You can see this post as a sort of a &amp;quot;call for action&amp;quot; to be more thankful to the people that have affected you in important ways. If people take things for granted because they Just Work, the person who made those things should be proud of this achievement.&lt;/p&gt; +&lt;p&gt;Thanks to all of them, to everyone who has shared good moments with me, and to all the people who enjoy the things I make.&lt;/p&gt; +&lt;/main&gt; +&lt;/body&gt; +&lt;/html&gt; + </content></entry><entry><title>University posts</title><id>dist/university/index.html</id><updated>2020-10-02T22:00:00+00:00</updated><published>2020-07-02T22:00:00+00:00</published><summary>During university, there were a few subjects where I had to write blog posts for (either as</summary><content type="html" src="dist/university/index.html">&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot; /&gt;

@@ -136,7 +137,7 @@ &lt;body&gt;

&lt;main&gt; &lt;h1 class=&quot;title&quot; id=&quot;university_posts&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#university_posts&quot;&gt;¶&lt;/a&gt;University posts&lt;/h1&gt; &lt;div class=&quot;date-created-modified&quot;&gt;Created 2020-07-03&lt;br&gt; -Modified 2020-08-24&lt;/div&gt; +Modified 2020-10-03&lt;/div&gt; &lt;p&gt;During university, there were a few subjects where I had to write blog posts for (either as evaluable tasks or just for fun). Currently, these are:&lt;/p&gt; &lt;ul&gt;

@@ -146,7 +147,7 @@ &lt;/ul&gt;

&lt;/main&gt; &lt;/body&gt; &lt;/html&gt; - </content></entry><entry><title>Python ctypes and Windows</title><id>dist/ctypes-and-windows/index.html</id><updated>2020-08-23T22:00:00+00:00</updated><published>2019-06-18T22:00:00+00:00</published><summary>Python</summary><content type="html" src="dist/ctypes-and-windows/index.html">&lt;!DOCTYPE html&gt; + </content></entry><entry><title>Python ctypes and Windows</title><id>dist/ctypes-and-windows/index.html</id><updated>2020-10-02T22:00:00+00:00</updated><published>2019-06-18T22:00:00+00:00</published><summary>Python</summary><content type="html" src="dist/ctypes-and-windows/index.html">&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot; /&gt;

@@ -158,7 +159,7 @@ &lt;body&gt;

&lt;main&gt; &lt;h1 class=&quot;title&quot; id=&quot;python_ctypes_and_windows&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#python_ctypes_and_windows&quot;&gt;¶&lt;/a&gt;Python ctypes and Windows&lt;/h1&gt; &lt;div class=&quot;date-created-modified&quot;&gt;Created 2019-06-19&lt;br&gt; -Modified 2020-08-24&lt;/div&gt; +Modified 2020-10-03&lt;/div&gt; &lt;p&gt;&lt;a href=&quot;https://www.python.org/&quot;&gt;Python&lt;/a&gt;'s &lt;a href=&quot;https://docs.python.org/3/library/ctypes.html&quot;&gt;&lt;code&gt;ctypes&lt;/code&gt;&lt;/a&gt; is quite a nice library to easily load and invoke C methods available in already-compiled &lt;a href=&quot;https://en.wikipedia.org/wiki/Dynamic-link_library&quot;&gt;&lt;code&gt;.dll&lt;/code&gt; files&lt;/a&gt; without any additional dependencies. And I &lt;em&gt;love&lt;/em&gt; depending on as little as possible.&lt;/p&gt; &lt;p&gt;In this blog post, we will walk through my endeavors to use &lt;code&gt;ctypes&lt;/code&gt; with the &lt;a href=&quot;https://docs.microsoft.com/en-us/windows/desktop/api/&quot;&gt;Windows API&lt;/a&gt;, and do some cool stuff with it.&lt;/p&gt; &lt;p&gt;We will assume some knowledge of C/++ and Python, since we will need to read and write a bit of both. Please note that this post is only an introduction to &lt;code&gt;ctypes&lt;/code&gt;, and if you need more information you should consult the &lt;a href=&quot;https://docs.python.org/3/library/ctypes.html&quot;&gt;Python's documentation for &lt;code&gt;ctypes&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

@@ -428,7 +429,7 @@ &lt;p&gt;Have fun hacking!&lt;/p&gt;

&lt;/main&gt; &lt;/body&gt; &lt;/html&gt; - </content></entry><entry><title>Shattered Pixel Dungeon</title><id>dist/pixel-dungeon/index.html</id><updated>2020-08-23T22:00:00+00:00</updated><published>2019-06-02T22:00:00+00:00</published><summary>Shattered Pixel Dungeon</summary><content type="html" src="dist/pixel-dungeon/index.html">&lt;!DOCTYPE html&gt; + </content></entry><entry><title>Shattered Pixel Dungeon</title><id>dist/pixel-dungeon/index.html</id><updated>2020-10-02T22:00:00+00:00</updated><published>2019-06-02T22:00:00+00:00</published><summary>Shattered Pixel Dungeon</summary><content type="html" src="dist/pixel-dungeon/index.html">&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot; /&gt;

@@ -440,7 +441,7 @@ &lt;body&gt;

&lt;main&gt; &lt;h1 class=&quot;title&quot; id=&quot;shattered_pixel_dungeon&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#shattered_pixel_dungeon&quot;&gt;¶&lt;/a&gt;Shattered Pixel Dungeon&lt;/h1&gt; &lt;div class=&quot;date-created-modified&quot;&gt;Created 2019-06-03&lt;br&gt; -Modified 2020-08-24&lt;/div&gt; +Modified 2020-10-03&lt;/div&gt; &lt;p&gt;&lt;a href=&quot;https://shatteredpixel.com/shatteredpd/&quot;&gt;Shattered Pixel Dungeon&lt;/a&gt; is the classic roguelike RPG game with randomly-generated dungeons. As a new player, it was a bit frustrating to be constantly killed on the first levels of the dungeon, but with some practice it's easy to reach high levels if you can kill the first boss.&lt;/p&gt; &lt;h2 id=&quot;basic_tips&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#basic_tips&quot;&gt;¶&lt;/a&gt;Basic Tips&lt;/h2&gt; &lt;p&gt;The game comes with its own tips, but here's a short and straight-forward summary:&lt;/p&gt;

@@ -471,7 +472,7 @@ &lt;p&gt;This game is all about luck and patience! Some runs will be better than others, and you should thank and pray the RNG gods for them. If you don't, they will only give you cursed items and not a single scroll to clean them. So, good luck and enjoy playing!&lt;/p&gt;

&lt;/main&gt; &lt;/body&gt; &lt;/html&gt; - </content></entry><entry><title>Breaking Risk of Rain</title><id>dist/breaking-ror/index.html</id><updated>2020-08-23T22:00:00+00:00</updated><published>2019-01-11T23:00:00+00:00</published><summary>Risk of Rain</summary><content type="html" src="dist/breaking-ror/index.html">&lt;!DOCTYPE html&gt; + </content></entry><entry><title>Breaking Risk of Rain</title><id>dist/breaking-ror/index.html</id><updated>2020-10-02T22:00:00+00:00</updated><published>2019-01-11T23:00:00+00:00</published><summary>Risk of Rain</summary><content type="html" src="dist/breaking-ror/index.html">&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot; /&gt;

@@ -483,7 +484,7 @@ &lt;body&gt;

&lt;main&gt; &lt;h1 class=&quot;title&quot; id=&quot;breaking_risk_of_rain&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#breaking_risk_of_rain&quot;&gt;¶&lt;/a&gt;Breaking Risk of Rain&lt;/h1&gt; &lt;div class=&quot;date-created-modified&quot;&gt;Created 2019-01-12&lt;br&gt; -Modified 2020-08-24&lt;/div&gt; +Modified 2020-10-03&lt;/div&gt; &lt;p&gt;&lt;a href=&quot;https://riskofraingame.com/&quot;&gt;Risk of Rain&lt;/a&gt; is a fun little game you can spend a lot of hours on. It's incredibly challenging for new players, and fun once you have learnt the basics. This blog will go through what I've learnt and how to play the game correctly.&lt;/p&gt; &lt;h2 id=&quot;getting_started&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#getting_started&quot;&gt;¶&lt;/a&gt;Getting Started&lt;/h2&gt; &lt;p&gt;If you're new to the game, you may find it frustrating. You must learn very well to dodge.&lt;/p&gt;

@@ -548,6 +549,370 @@ &lt;p&gt;You can now beat the game in Monsoon solo with any character. Have fun! And be careful with the sadly common crashes.&lt;/p&gt;

&lt;/main&gt; &lt;/body&gt; &lt;/html&gt; + </content></entry><entry><title>An Introduction to Asyncio</title><id>dist/asyncio/index.html</id><updated>2020-10-02T22:00:00+00:00</updated><published>2018-06-12T22:00:00+00:00</published><summary>After seeing some friends struggle with </summary><content type="html" src="dist/asyncio/index.html">&lt;!DOCTYPE html&gt; +&lt;html&gt; +&lt;head&gt; +&lt;meta charset=&quot;utf-8&quot; /&gt; +&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt; +&lt;title&gt;An Introduction to Asyncio&lt;/title&gt; +&lt;link rel=&quot;stylesheet&quot; href=&quot;../css/style.css&quot;&gt; +&lt;/head&gt; +&lt;body&gt; +&lt;main&gt; +&lt;h1 class=&quot;title&quot; id=&quot;an_introduction_to_asyncio&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#an_introduction_to_asyncio&quot;&gt;¶&lt;/a&gt;An Introduction to Asyncio&lt;/h1&gt; +&lt;div class=&quot;date-created-modified&quot;&gt;Created 2018-06-13&lt;br&gt; +Modified 2020-10-03&lt;/div&gt; +&lt;h2 id=&quot;index&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#index&quot;&gt;¶&lt;/a&gt;Index&lt;/h2&gt; +&lt;ul&gt; +&lt;li&gt;&lt;a href=&quot;#background&quot;&gt;Background&lt;/a&gt;&lt;/li&gt; +&lt;li&gt;&lt;a href=&quot;#input_output&quot;&gt;Input / Output&lt;/a&gt;&lt;/li&gt; +&lt;li&gt;&lt;a href=&quot;#diving_in&quot;&gt;Diving In&lt;/a&gt;&lt;/li&gt; +&lt;li&gt;&lt;a href=&quot;#a_toy_example&quot;&gt;A Toy Example&lt;/a&gt;&lt;/li&gt; +&lt;li&gt;&lt;a href=&quot;#a_real_example&quot;&gt;A Real Example&lt;/a&gt;&lt;/li&gt; +&lt;li&gt;&lt;a href=&quot;#extra_material&quot;&gt;Extra Material&lt;/a&gt;&lt;/li&gt; +&lt;/ul&gt; +&lt;h2 id=&quot;background&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#background&quot;&gt;¶&lt;/a&gt;Background&lt;/h2&gt; +&lt;p&gt;After seeing some friends struggle with &lt;code&gt;asyncio&lt;/code&gt; I decided that it could be a good idea to write a blog post using my own words to explain how I understand the world of asynchronous IO. I will focus on Python's &lt;code&gt;asyncio&lt;/code&gt; module but this post should apply to any other language easily.&lt;/p&gt; +&lt;p&gt;So what is &lt;code&gt;asyncio&lt;/code&gt; and what makes it good? Why don't we just use the old and known threads to run several parts of the code concurrently, at the same time?&lt;/p&gt; +&lt;p&gt;The first reason is that &lt;code&gt;asyncio&lt;/code&gt; makes your code easier to reason about, as opposed to using threads, because the amount of ways in which your code can run grows exponentially. Let's see that with an example. Imagine you have this code:&lt;/p&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def method(): + line 1 + line 2 + line 3 + line 4 + line 5 +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;And you start two threads to run the method at the same time. What is the order in which the lines of code get executed? The answer is that you can't know! The first thread can run the entire method before the second thread even starts. Or it could be the first thread that runs after the second thread. Perhaps both run the &amp;quot;line 1&amp;quot;, and then the line 2. Maybe the first thread runs lines 1 and 2, and then the second thread only runs the line 1 before the first thread finishes.&lt;/p&gt; +&lt;p&gt;As you can see, any combination of the order in which the lines run is possible. If the lines modify some global shared state, that will get messy quickly.&lt;/p&gt; +&lt;p&gt;Second, in Python, threads &lt;em&gt;won't&lt;/em&gt; make your code faster most of the time. It will only increase the concurrency of your program (which is okay if it makes many blocking calls), allowing you to run several things at the same time.&lt;/p&gt; +&lt;p&gt;If you have a lot of CPU work to do though, threads aren't a real advantage. Indeed, your code will probably run slower under the most common Python implementation, CPython, which makes use of a Global Interpreter Lock (GIL) that only lets a thread run at once. The operations won't run in parallel!&lt;/p&gt; +&lt;h2 id=&quot;input_output&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#input_output&quot;&gt;¶&lt;/a&gt;Input / Output&lt;/h2&gt; +&lt;p&gt;Before we go any further, let's first stop to talk about input and output, commonly known as &amp;quot;IO&amp;quot;. There are two main ways to perform IO operations, such as reading or writing from a file or a network socket.&lt;/p&gt; +&lt;p&gt;The first one is known as &amp;quot;blocking IO&amp;quot;. What this means is that, when you try performing IO, the current application thread is going to &lt;em&gt;block&lt;/em&gt; until the Operative System can tell you it's done. Normally, this is not a problem, since disks are pretty fast anyway, but it can soon become a performance bottleneck. And network IO will be much slower than disk IO!&lt;/p&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import socket + +# Setup a network socket and a very simple HTTP request. +# By default, sockets are open in blocking mode. +sock = socket.socket() +request = b'''HEAD / HTTP/1.0\r +Host: example.com\r +\r +''' + +# &amp;quot;connect&amp;quot; will block until a successful TCP connection +# is made to the host &amp;quot;example.com&amp;quot; on port 80. +sock.connect(('example.com', 80)) + +# &amp;quot;sendall&amp;quot; will repeatedly call &amp;quot;send&amp;quot; until all the data in &amp;quot;request&amp;quot; is +# sent to the host we just connected, which blocks until the data is sent. +sock.sendall(request) + +# &amp;quot;recv&amp;quot; will try to receive up to 1024 bytes from the host, and block until +# there is any data to receive (or empty if the host closes the connection). +response = sock.recv(1024) + +# After all those blocking calls, we got out data! These are the headers from +# making a HTTP request to example.com. +print(response.decode()) +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;Blocking IO offers timeouts, so that you can get control back in your code if the operation doesn't finish. Imagine that the remote host doesn't want to reply, your code would be stuck for as long as the connection remains alive!&lt;/p&gt; +&lt;p&gt;But wait, what if we make the timeout small? Very, very small? If we do that, we will never block waiting for an answer. That's how asynchronous IO works, and it's the opposite of blocking IO (you can also call it non-blocking IO if you want to).&lt;/p&gt; +&lt;p&gt;How does non-blocking IO work if the IO device needs a while to answer with the data? In that case, the operative system responds with &amp;quot;not ready&amp;quot;, and your application gets control back so it can do other stuff while the IO device completes your request. It works a bit like this:&lt;/p&gt; +&lt;pre&gt;&lt;code&gt;&amp;lt;app&amp;gt; Hey, I would like to read 16 bytes from this file +&amp;lt;OS&amp;gt; Okay, but the disk hasn't sent me the data yet +&amp;lt;app&amp;gt; Alright, I will do something else then +(a lot of computer time passes) +&amp;lt;app&amp;gt; Do you have my 16 bytes now? +&amp;lt;OS&amp;gt; Yes, here they are! &amp;quot;Hello, world !!\n&amp;quot; +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;In reality, you can tell the OS to notify you when the data is ready, as opposed to polling (constantly asking the OS whether the data is ready yet or not), which is more efficient.&lt;/p&gt; +&lt;p&gt;But either way, that's the difference between blocking and non-blocking IO, and what matters is that your application gets to run more without ever needing to wait for data to arrive, because the data will be there immediately when you ask, and if it's not yet, your app can do more things meanwhile.&lt;/p&gt; +&lt;h2 id=&quot;diving_in&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#diving_in&quot;&gt;¶&lt;/a&gt;Diving In&lt;/h2&gt; +&lt;p&gt;Now we've seen what blocking and non-blocking IO is, and how threads make your code harder to reason about, but they give concurrency (yet not more speed). Is there any other way to achieve this concurrency that doesn't involve threads? Yes! The answer is &lt;code&gt;asyncio&lt;/code&gt;.&lt;/p&gt; +&lt;p&gt;So how does &lt;code&gt;asyncio&lt;/code&gt; help? First we need to understand a very crucial concept before we can dive any deeper, and I'm talking about the &lt;em&gt;event loop&lt;/em&gt;. What is it and why do we need it?&lt;/p&gt; +&lt;p&gt;You can think of the event loop as a &lt;em&gt;loop&lt;/em&gt; that will be responsible for calling your &lt;code&gt;async&lt;/code&gt; functions:&lt;/p&gt; +&lt;div class=&quot;image-container&quot;&gt; +&lt;img src=&quot;eventloop.svg&quot; alt=&quot;The Event Loop&quot; /&gt; +&lt;div class=&quot;image-caption&quot;&gt;&lt;/div&gt; +&lt;/div&gt; +&lt;p&gt; +&lt;p&gt;That's silly you may think. Now not only we run our code but we also have to run some &amp;quot;event loop&amp;quot;. It doesn't sound beneficial at all. What are these events? Well, they are the IO events we talked about before!&lt;/p&gt; +&lt;p&gt;&lt;code&gt;asyncio&lt;/code&gt;'s event loop is responsible for handling those IO events, such as file is ready, data arrived, flushing is done, and so on. As we saw before, we can make these events non-blocking by setting their timeout to 0.&lt;/p&gt; +&lt;p&gt;Let's say you want to read from 10 files at the same time. You will ask the OS to read data from 10 files, and at first none of the reads will be ready. But the event loop will be constantly asking the OS to know which are done, and when they are done, you will get your data.&lt;/p&gt; +&lt;p&gt;This has some nice advantages. It means that, instead of waiting for a network request to send you a response or some file, instead of blocking there, the event loop can decide to run other code meanwhile. Whenever the contents are ready, they can be read, and your code can continue. Waiting for the contents to be received is done with the &lt;code&gt;await&lt;/code&gt; keyword, and it tells the loop that it can run other code meanwhile:&lt;/p&gt; +&lt;div class=&quot;image-container&quot;&gt; +&lt;img src=&quot;awaitkwd1.svg&quot; alt=&quot;Step 1, await keyword&quot; /&gt; +&lt;div class=&quot;image-caption&quot;&gt;&lt;/div&gt; +&lt;/div&gt; +&lt;p&gt; +&lt;div class=&quot;image-container&quot;&gt; +&lt;img src=&quot;awaitkwd2.svg&quot; alt=&quot;Step 2, await keyword&quot; /&gt; +&lt;div class=&quot;image-caption&quot;&gt;&lt;/div&gt; +&lt;/div&gt; +&lt;p&gt; +&lt;p&gt;Start reading the code of the event loop and follow the arrows. You can see that, in the beginning, there are no events yet, so the loop calls one of your functions. The code runs until it has to &lt;code&gt;await&lt;/code&gt; for some IO operation to complete, such as sending a request over the network. The method is &amp;quot;paused&amp;quot; until an event occurs (for example, an &amp;quot;event&amp;quot; occurs when the request has been sent completely).&lt;/p&gt; +&lt;p&gt;While the first method is busy, the event loop can enter the second method, and run its code until the first &lt;code&gt;await&lt;/code&gt;. But it can happen that the event of the second query occurs before the request on the first method, so the event loop can re-enter the second method because it has already sent the query, but the first method isn't done sending the request yet.&lt;/p&gt; +&lt;p&gt;Then, the second method &lt;code&gt;await&lt;/code&gt;'s for an answer, and an event occurs telling the event loop that the request from the first method was sent. The code can be resumed again, until it has to &lt;code&gt;await&lt;/code&gt; for a response, and so on. Here's an explanation with pseudo-code for this process if you prefer:&lt;/p&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;async def method(request): + prepare request + await send request + + await receive request + + process request + return result + +run in parallel ( + method with request 1, + method with request 2, +) +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;This is what the event loop will do on the above pseudo-code:&lt;/p&gt; +&lt;pre&gt;&lt;code&gt;no events pending, can advance + +enter method with request 1 + prepare request + await sending request +pause method with request 1 + +no events ready, can advance + +enter method with request 2 + prepare request + await sending request +pause method with request 2 + +both requests are paused, cannot advance +wait for events +event for request 2 arrives (sending request completed) + +enter method with request 2 + await receiving response +pause method with request 2 + +event for request 1 arrives (sending request completed) + +enter method with request 1 + await receiving response +pause method with request 1 + +...and so on +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;You may be wondering &amp;quot;okay, but threads work for me, so why should I change?&amp;quot;. There are some important things to note here. The first is that we only need one thread to be running! The event loop decides when and which methods should run. This results in less pressure for the operating system. The second is that we know when it may run other methods. Those are the &lt;code&gt;await&lt;/code&gt; keywords! Whenever there is one of those, we know that the loop is able to run other things until the resource (again, like network) becomes ready (when a event occurs telling us it's ready to be used without blocking or it has completed).&lt;/p&gt; +&lt;p&gt;So far, we already have two advantages. We are only using a single thread so the cost for switching between methods is low, and we can easily reason about where our program may interleave operations.&lt;/p&gt; +&lt;p&gt;Another advantage is that, with the event loop, you can easily schedule when a piece of code should run, such as using the method &lt;a href=&quot;https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_at&quot;&gt;&lt;code&gt;loop.call_at&lt;/code&gt;&lt;/a&gt;, without the need for spawning another thread at all.&lt;/p&gt; +&lt;p&gt;To tell the &lt;code&gt;asyncio&lt;/code&gt; to run the two methods shown above, we can use &lt;a href=&quot;https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future&quot;&gt;&lt;code&gt;asyncio.ensure_future&lt;/code&gt;&lt;/a&gt;, which is a way of saying &amp;quot;I want the future of my method to be ensured&amp;quot;. That is, you want to run your method in the future, whenever the loop is free to do so. This method returns a &lt;code&gt;Future&lt;/code&gt; object, so if your method returns a value, you can &lt;code&gt;await&lt;/code&gt; this future to retrieve its result.&lt;/p&gt; +&lt;p&gt;What is a &lt;code&gt;Future&lt;/code&gt;? This object represents the value of something that will be there in the future, but might not be there yet. Just like you can &lt;code&gt;await&lt;/code&gt; your own &lt;code&gt;async def&lt;/code&gt; functions, you can &lt;code&gt;await&lt;/code&gt; these &lt;code&gt;Future&lt;/code&gt;'s.&lt;/p&gt; +&lt;p&gt;The &lt;code&gt;async def&lt;/code&gt; functions are also called &amp;quot;coroutines&amp;quot;, and Python does some magic behind the scenes to turn them into such. The coroutines can be &lt;code&gt;await&lt;/code&gt;'ed, and this is what you normally do.&lt;/p&gt; +&lt;h2 id=&quot;a_toy_example&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#a_toy_example&quot;&gt;¶&lt;/a&gt;A Toy Example&lt;/h2&gt; +&lt;p&gt;That's all about &lt;code&gt;asyncio&lt;/code&gt;! Let's wrap up with some example code. We will create a server that replies with the text a client sends, but reversed. First, we will show what you could write with normal synchronous code, and then we will port it.&lt;/p&gt; +&lt;p&gt;Here is the &lt;strong&gt;synchronous version&lt;/strong&gt;:&lt;/p&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# server.py +import socket + + +def server_method(): + # create a new server socket to listen for connections + server = socket.socket() + + # bind to localhost:6789 for new connections + server.bind(('localhost', 6789)) + + # we will listen for one client at most + server.listen(1) + + # *block* waiting for a new client + client, _ = server.accept() + + # *block* waiting for some data + data = client.recv(1024) + + # reverse the data + data = data[::-1] + + # *block* sending the data + client.sendall(data) + + # close client and server + server.close() + client.close() + + +if __name__ == '__main__': + # block running the server + server_method() +&lt;/code&gt;&lt;/pre&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# client.py +import socket + + +def client_method(): + message = b'Hello Server!\n' + client = socket.socket() + + # *block* trying to stabilish a connection + client.connect(('localhost', 6789)) + + # *block* trying to send the message + print('Sending', message) + client.sendall(message) + + # *block* until we receive a response + response = client.recv(1024) + print('Server replied', response) + + client.close() + + +if __name__ == '__main__': + client_method() +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;From what we've seen, this code will block on all the lines with a comment above them saying that they will block. This means that for running more than one client or server, or both in the same file, you will need threads. But we can do better, we can rewrite it into &lt;code&gt;asyncio&lt;/code&gt;!&lt;/p&gt; +&lt;p&gt;The first step is to mark all your &lt;code&gt;def&lt;/code&gt;initions that may block with &lt;code&gt;async&lt;/code&gt;. This marks them as coroutines, which can be &lt;code&gt;await&lt;/code&gt;ed on.&lt;/p&gt; +&lt;p&gt;Second, since we're using low-level sockets, we need to make use of the methods that &lt;code&gt;asyncio&lt;/code&gt; provides directly. If this was a third-party library, this would be just like using their &lt;code&gt;async def&lt;/code&gt;initions.&lt;/p&gt; +&lt;p&gt;Here is the &lt;strong&gt;asynchronous version&lt;/strong&gt;:&lt;/p&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# server.py +import asyncio +import socket + +# get the default &amp;quot;event loop&amp;quot; that we will run +loop = asyncio.get_event_loop() + + +# notice our new &amp;quot;async&amp;quot; before the definition +async def server_method(): + server = socket.socket() + server.bind(('localhost', 6789)) + server.listen(1) + + # await for a new client + # the event loop can run other code while we wait here! + client, _ = await loop.sock_accept(server) + + # await for some data + data = await loop.sock_recv(client, 1024) + data = data[::-1] + + # await for sending the data + await loop.sock_sendall(client, data) + + server.close() + client.close() + + +if __name__ == '__main__': + # run the loop until &amp;quot;server method&amp;quot; is complete + loop.run_until_complete(server_method()) +&lt;/code&gt;&lt;/pre&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# client.py +import asyncio +import socket + +loop = asyncio.get_event_loop() + + +async def client_method(): + message = b'Hello Server!\n' + client = socket.socket() + + # await to stabilish a connection + await loop.sock_connect(client, ('localhost', 6789)) + + # await to send the message + print('Sending', message) + await loop.sock_sendall(client, message) + + # await to receive a response + response = await loop.sock_recv(client, 1024) + print('Server replied', response) + + client.close() + + +if __name__ == '__main__': + loop.run_until_complete(client_method()) +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;That's it! You can place these two files separately and run, first the server, then the client. You should see output in the client.&lt;/p&gt; +&lt;p&gt;The big difference here is that you can easily modify the code to run more than one server or clients at the same time. Whenever you &lt;code&gt;await&lt;/code&gt; the event loop will run other of your code. It seems to &amp;quot;block&amp;quot; on the &lt;code&gt;await&lt;/code&gt; parts, but remember it's actually jumping to run more code, and the event loop will get back to you whenever it can.&lt;/p&gt; +&lt;p&gt;In short, you need an &lt;code&gt;async def&lt;/code&gt; to &lt;code&gt;await&lt;/code&gt; things, and you run them with the event loop instead of calling them directly. So this…&lt;/p&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def main(): + ... # some code + + +if __name__ == '__main__': + main() +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;…becomes this:&lt;/p&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import asyncio + + +async def main(): + ... # some code + + +if __name__ == '__main__': + asyncio.get_event_loop().run_until_complete(main) +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;This is pretty much how most of your &lt;code&gt;async&lt;/code&gt; scripts will start, running the main method until its completion.&lt;/p&gt; +&lt;h2 id=&quot;a_real_example&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#a_real_example&quot;&gt;¶&lt;/a&gt;A Real Example&lt;/h2&gt; +&lt;p&gt;Let's have some fun with a real library. We'll be using &lt;a href=&quot;https://github.com/LonamiWebs/Telethon&quot;&gt;Telethon&lt;/a&gt; to broadcast a message to our three best friends, all at the same time, thanks to the magic of &lt;code&gt;asyncio&lt;/code&gt;. We'll dive right into the code, and then I'll explain our new friend &lt;code&gt;asyncio.wait(...)&lt;/code&gt;:&lt;/p&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# broadcast.py +import asyncio +import sys + +from telethon import TelegramClient + +# (you need your own values here, check Telethon's documentation) +api_id = 123 +api_hash = '123abc' +friends = [ + '@friend1__username', + '@friend2__username', + '@bestie__username' +] + +# we will have to await things, so we need an async def +async def main(message): + # start is a coroutine, so we need to await it to run it + client = await TelegramClient('me', api_id, api_hash).start() + + # wait for all three client.send_message to complete + await asyncio.wait([ + client.send_message(friend, message) + for friend in friends + ]) + + # and close our client + await client.disconnect() + + +if __name__ == '__main__': + if len(sys.argv) != 2: + print('You must pass the message to broadcast!') + quit() + + message = sys.argv[1] + asyncio.get_event_loop().run_until_complete(main(message)) +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;Wait… how did that send a message to all three of +my friends? The magic is done here:&lt;/p&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;[ + client.send_message(friend, message) + for friend in friends +] +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;This list comprehension creates another list with three +coroutines, the three &lt;code&gt;client.send_message(...)&lt;/code&gt;. +Then we just pass that list to &lt;code&gt;asyncio.wait&lt;/code&gt;:&lt;/p&gt; +&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;await asyncio.wait([...]) +&lt;/code&gt;&lt;/pre&gt; +&lt;p&gt;This method, by default, waits for the list of coroutines to run until they've all finished. You can read more on the Python &lt;a href=&quot;https://docs.python.org/3/library/asyncio-task.html#asyncio.wait&quot;&gt;documentation&lt;/a&gt;. Truly a good function to know about!&lt;/p&gt; +&lt;p&gt;Now whenever you have some important news for your friends, you can simply &lt;code&gt;python3 broadcast.py 'I bought a car!'&lt;/code&gt; to tell all your friends about your new car! All you need to remember is that you need to &lt;code&gt;await&lt;/code&gt; on coroutines, and you will be good. &lt;code&gt;asyncio&lt;/code&gt; will warn you when you forget to do so.&lt;/p&gt; +&lt;h2 id=&quot;extra_material&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#extra_material&quot;&gt;¶&lt;/a&gt;Extra Material&lt;/h2&gt; +&lt;p&gt;If you want to understand how &lt;code&gt;asyncio&lt;/code&gt; works under the hood, I recommend you to watch this hour-long talk &lt;a href=&quot;https://youtu.be/M-UcUs7IMIM&quot;&gt;Get to grips with asyncio in Python 3&lt;/a&gt; by Robert Smallshire. In the video, they will explain the differences between concurrency and parallelism, along with others concepts, and how to implement your own &lt;code&gt;asyncio&lt;/code&gt; &amp;quot;scheduler&amp;quot; from scratch.&lt;/p&gt; +&lt;/main&gt; +&lt;/body&gt; +&lt;/html&gt; </content></entry><entry><title>My new computer</title><id>dist/new-computer/index.html</id><updated>2020-07-02T22:00:00+00:00</updated><published>2020-06-18T22:00:00+00:00</published><summary>This post will be mostly me ranting about setting up a new laptop, but I also just want to share my upgrade. If you're considering installing Arch Linux with dual-boot for Windows, maybe this post will help. Or perhaps you will learn something new to troubleshoot systems in the future. Let's begin!</summary><content type="html" src="dist/new-computer/index.html">&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt;

@@ -1198,311 +1563,6 @@ &lt;h2 id=&quot;clipboard&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#clipboard&quot;&gt;¶&lt;/a&gt;Clipboard&lt;/h2&gt;

&lt;p&gt;Finally, you can copy and cut things around like you would do with normal text with &lt;code&gt;//copy&lt;/code&gt; and &lt;code&gt;//cut&lt;/code&gt;. The copy is issued from wherever you issue the command, so when you use &lt;code&gt;//paste&lt;/code&gt;, remember that if you were 4 blocks apart when copying, it will be 4 blocks apart when pasting.&lt;/p&gt; &lt;p&gt;The contents of the clipboard can be flipped to wherever you are looking via &lt;code&gt;//flip&lt;/code&gt;, and can be rotated via the &lt;code&gt;//rotate 90&lt;/code&gt; command (in degrees).&lt;/p&gt; &lt;p&gt;To remove the copy use &lt;code&gt;//clearclipboard&lt;/code&gt;.&lt;/p&gt; -&lt;/main&gt; -&lt;/body&gt; -&lt;/html&gt; - </content></entry><entry><title>An Introduction to Asyncio</title><id>dist/asyncio/index.html</id><updated>2018-06-14T22:00:00+00:00</updated><published>2018-06-12T22:00:00+00:00</published><summary>After seeing some friends struggle with </summary><content type="html" src="dist/asyncio/index.html">&lt;!DOCTYPE html&gt; -&lt;html&gt; -&lt;head&gt; -&lt;meta charset=&quot;utf-8&quot; /&gt; -&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt; -&lt;title&gt;An Introduction to Asyncio&lt;/title&gt; -&lt;link rel=&quot;stylesheet&quot; href=&quot;../css/style.css&quot;&gt; -&lt;/head&gt; -&lt;body&gt; -&lt;main&gt; -&lt;h1 class=&quot;title&quot; id=&quot;an_introduction_to_asyncio&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#an_introduction_to_asyncio&quot;&gt;¶&lt;/a&gt;An Introduction to Asyncio&lt;/h1&gt; -&lt;div class=&quot;date-created-modified&quot;&gt;Created 2018-06-13&lt;br&gt; -Modified 2018-06-15&lt;/div&gt; -&lt;h2 id=&quot;index&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#index&quot;&gt;¶&lt;/a&gt;Index&lt;/h2&gt; -&lt;ul&gt; -&lt;li&gt;&lt;a href=&quot;#background&quot;&gt;Background&lt;/a&gt;&lt;/li&gt; -&lt;li&gt;&lt;a href=&quot;#inputoutput&quot;&gt;Input / Output&lt;/a&gt;&lt;/li&gt; -&lt;li&gt;&lt;a href=&quot;#divingin&quot;&gt;Diving In&lt;/a&gt;&lt;/li&gt; -&lt;li&gt;&lt;a href=&quot;#toyexample&quot;&gt;A Toy Example&lt;/a&gt;&lt;/li&gt; -&lt;li&gt;&lt;a href=&quot;#example&quot;&gt;A Real Example&lt;/a&gt;&lt;/li&gt; -&lt;li&gt;&lt;a href=&quot;#extra&quot;&gt;Extra Material&lt;/a&gt;&lt;/li&gt; -&lt;/ul&gt; -&lt;h2 id=&quot;background&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#background&quot;&gt;¶&lt;/a&gt;Background&lt;/h2&gt; -&lt;p&gt;After seeing some friends struggle with &lt;code&gt;asyncio&lt;/code&gt; I decided that it could be a good idea to write a blog post using my own words to explain how I understand the world of asynchronous IO. I will focus on Python's &lt;code&gt;asyncio&lt;/code&gt; module but this post should apply to any other language easily.&lt;/p&gt; -&lt;p&gt;So what is &lt;code&gt;asyncio&lt;/code&gt; and what makes it good? Why don't we just use the old and known threads to run several parts of the code concurrently, at the same time?&lt;/p&gt; -&lt;p&gt;The first reason is that &lt;code&gt;asyncio&lt;/code&gt; makes your code easier to reason about, as opposed to using threads, because the amount of ways in which your code can run grows exponentially. Let's see that with an example. Imagine you have this code:&lt;/p&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def method(): - line 1 - line 2 - line 3 - line 4 - line 5 -&lt;/code&gt;&lt;/pre&gt; -&lt;p&gt;And you start two threads to run the method at the same time. What is the order in which the lines of code get executed? The answer is that you can't know! The first thread can run the entire method before the second thread even starts. Or it could be the first thread that runs after the second thread. Perhaps both run the &amp;quot;line 1&amp;quot;, and then the line 2. Maybe the first thread runs lines 1 and 2, and then the second thread only runs the line 1 before the first thread finishes.&lt;/p&gt; -&lt;p&gt;As you can see, any combination of the order in which the lines run is possible. If the lines modify some global shared state, that will get messy quickly.&lt;/p&gt; -&lt;p&gt;Second, in Python, threads &lt;em&gt;won't&lt;/em&gt; make your code faster. It will only increase the concurrency of your program, allowing you to run several things at the same time, so using threads for speed isn't a real advantage. Indeed, your code will probably run slower under the most common Python implementation, CPython, which makes use of a Global Interpreter Lock (GIL) that only lets a thread run at once.&lt;/p&gt; -&lt;h2 id=&quot;input_output&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#input_output&quot;&gt;¶&lt;/a&gt;Input / Output&lt;/h2&gt; -&lt;p&gt;Before we go any further, let's first stop to talk about input and output, commonly known as &amp;quot;IO&amp;quot;. There are two main ways to perform IO operations, such as reading or writing from a file or a network socket.&lt;/p&gt; -&lt;p&gt;The first one is known as &amp;quot;blocking IO&amp;quot;. What this means is that, when you try performing IO, the current application thread is going to &lt;em&gt;block&lt;/em&gt; until the Operative System can tell you it's done. Normally, this is not a problem, since disks are pretty fast anyway, but it can soon become a performance bottleneck. And network IO will be much slower than disk IO!&lt;/p&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# &amp;quot;open&amp;quot; will block until the OS creates a new file in the disk. -# this can be really slow if the disk is under heavy load! -with open('hello.txt', 'w') as fd: - fd.write('hello!\n') - - # &amp;quot;flush&amp;quot; will block until the OS has written all data to disk* - fd.flush() - -# * the reality is a bit more complicated, since writes to disk are -# quite expensive, the OS will normally keep the data in RAM until -# it has more stuff to write to disk, and then it will `sync` -# everything after a few seconds -&lt;/code&gt;&lt;/pre&gt; -&lt;p&gt;Blocking IO offers timeouts, so that you can get control back in your code if the operation doesn't finish. Imagine that the remote host doesn't want to reply, your code would be stuck for as long as the connection remains alive!&lt;/p&gt; -&lt;p&gt;But wait, what if we make the timeout small? Very, very small? If we do that, we will never block waiting for an answer. That's how asynchronous IO works, and it's the opposite of blocking IO (you can also call it non-blocking IO if you want to).&lt;/p&gt; -&lt;p&gt;How does non-blocking IO work if the IO device needs a while to answer with the data? In that case, the operative system responds with &amp;quot;not ready&amp;quot;, and your application gets control back so it can do other stuff while the IO device completes your request. It works a bit like this:&lt;/p&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;amp;lt;app&amp;amp;gt; Hey, I would like to read 16 bytes from this file -&amp;amp;lt;OS&amp;amp;gt; Okay, but the disk hasn't sent me the data yet -&amp;amp;lt;app&amp;amp;gt; Alright, I will do something else then -(a lot of computer time passes) -&amp;amp;lt;app&amp;amp;gt; Do you have my 16 bytes now? -&amp;amp;lt;OS&amp;amp;gt; Yes, here they are! &amp;quot;Hello, world !!\n&amp;quot; -&lt;/code&gt;&lt;/pre&gt; -&lt;p&gt;In reality, you can tell the OS to notify you when the data is ready, as opposed to polling (constantly asking the OS whether the data is ready yet or not), which is more efficient.&lt;/p&gt; -&lt;p&gt;But either way, that's the difference between blocking and non-blocking IO, and what matters is that your application gets to run more without ever needing to wait for data to arrive, because the data will be there immediately when you ask, and if it's not yet, your app can do more things meanwhile.&lt;/p&gt; -&lt;h2 id=&quot;diving_in&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#diving_in&quot;&gt;¶&lt;/a&gt;Diving In&lt;/h2&gt; -&lt;p&gt;Now we've seen what blocking and non-blocking IO is, and how threads make your code harder to reason about, but they give concurrency (yet not more speed). Is there any other way to achieve this concurrency that doesn't involve threads? Yes! The answer is &lt;code&gt;asyncio&lt;/code&gt;.&lt;/p&gt; -&lt;p&gt;So how does &lt;code&gt;asyncio&lt;/code&gt; help? First we need to understand a very crucial concept before we can dive any deeper, and I'm talking about the &lt;em&gt;event loop&lt;/em&gt;. What is it and why do we need it?&lt;/p&gt; -&lt;p&gt;You can think of the event loop as a &lt;em&gt;loop&lt;/em&gt; that will be responsible for calling your &lt;code&gt;async&lt;/code&gt; functions:&lt;/p&gt; -&lt;div class=&quot;image-container&quot;&gt; -&lt;img src=&quot;eventloop.svg&quot; alt=&quot;The Event Loop&quot; /&gt; -&lt;div class=&quot;image-caption&quot;&gt;&lt;/div&gt; -&lt;/div&gt; -&lt;p&gt; -&lt;p&gt;That's silly you may think. Now not only we run our code but we also have to run some &amp;quot;event loop&amp;quot;. It doesn't sound beneficial at all. What are these events? Well, they are the IO events we talked about before!&lt;/p&gt; -&lt;p&gt;&lt;code&gt;asyncio&lt;/code&gt;'s event loop is responsible for handling those IO events, such as file is ready, data arrived, flushing is done, and so on. As we saw before, we can make these events non-blocking by setting their timeout to 0.&lt;/p&gt; -&lt;p&gt;Let's say you want to read from 10 files at the same time. You will ask the OS to read data from 10 files, and at first none of the reads will be ready. But the event loop will be constantly asking the OS to know which are done, and when they are done, you will get your data.&lt;/p&gt; -&lt;p&gt;This has some nice advantages. It means that, instead of waiting for a network request to send you a response or some file, instead of blocking there, the event loop can decide to run other code meanwhile. Whenever the contents are ready, they can be read, and your code can continue. Waiting for the contents to be received is done with the &lt;code&gt;await&lt;/code&gt; keyword, and it tells the loop that it can run other code meanwhile:&lt;/p&gt; -&lt;div class=&quot;image-container&quot;&gt; -&lt;img src=&quot;awaitkwd1.svg&quot; alt=&quot;Step 1, await keyword&quot; /&gt; -&lt;div class=&quot;image-caption&quot;&gt;&lt;/div&gt; -&lt;/div&gt; -&lt;p&gt; -&lt;div class=&quot;image-container&quot;&gt; -&lt;img src=&quot;awaitkwd2.svg&quot; alt=&quot;Step 2, await keyword&quot; /&gt; -&lt;div class=&quot;image-caption&quot;&gt;&lt;/div&gt; -&lt;/div&gt; -&lt;p&gt; -&lt;p&gt;Start reading the code of the event loop and follow the arrows. You can see that, in the beginning, there are no events yet, so the loop calls one of your functions. The code runs until it has to &lt;code&gt;await&lt;/code&gt; for some IO operation to complete, such as sending a request over the network. The method is &amp;quot;paused&amp;quot; until an event occurs (for example, an &amp;quot;event&amp;quot; occurs when the request has been sent completely).&lt;/p&gt; -&lt;p&gt;While the first method is busy, the event loop can enter the second method, and run its code until the first &lt;code&gt;await&lt;/code&gt;. But it can happen that the event of the second query occurs before the request on the first method, so the event loop can re-enter the second method because it has already sent the query, but the first method isn't done sending the request yet.&lt;/p&gt; -&lt;p&gt;Then, the second method &lt;code&gt;await&lt;/code&gt;'s for an answer, and an event occurs telling the event loop that the request from the first method was sent. The code can be resumed again, until it has to &lt;code&gt;await&lt;/code&gt; for a response, and so on.&lt;/p&gt; -&lt;p&gt;There are some important things to note here. The first is that we only need one thread to be running! The event loop decides when and which methods should run. The second is that we know when it may run other methods. Those are the &lt;code&gt;await&lt;/code&gt; keywords! Whenever there is one of those, we know that the loop is able to run other things until the resource (again, like network) becomes ready.&lt;/p&gt; -&lt;p&gt;So far, we already have two advantages. We are only using a single thread so the cost for switching between methods is low, and we can easily reason about where our program may interleave operations.&lt;/p&gt; -&lt;p&gt;Another advantage is that, with the event loop, you can easily schedule when a piece of code should run, such as using the method &lt;a href=&quot;https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_at&quot;&gt;&lt;code&gt;loop.call_at&lt;/code&gt;&lt;/a&gt;, without the need for spawning another thread at all.&lt;/p&gt; -&lt;p&gt;To tell the &lt;code&gt;asyncio&lt;/code&gt; to run the two methods shown above, we can use &lt;a href=&quot;https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future&quot;&gt;&lt;code&gt;asyncio.ensure_future&lt;/code&gt;&lt;/a&gt;, which is a way of saying &amp;quot;I want the future of my method to be ensured&amp;quot;. That is, you want to run your method in the future, whenever the loop is free to do so. This method returns a &lt;code&gt;Future&lt;/code&gt; object, so if your method returns a value, you can &lt;code&gt;await&lt;/code&gt; this future to retrieve its result.&lt;/p&gt; -&lt;p&gt;What is a &lt;code&gt;Future&lt;/code&gt;? This object represents the value of something that will be there in the future, but might not be there yet. Just like you can &lt;code&gt;await&lt;/code&gt; your own &lt;code&gt;async def&lt;/code&gt; functions, you can &lt;code&gt;await&lt;/code&gt; these &lt;code&gt;Future&lt;/code&gt;'s.&lt;/p&gt; -&lt;p&gt;The &lt;code&gt;async def&lt;/code&gt; functions are also called &amp;quot;coroutines&amp;quot;, and Python does some magic behind the scenes to turn them into such. The coroutines can be &lt;code&gt;await&lt;/code&gt;'ed, and this is what you normally do.&lt;/p&gt; -&lt;h2 id=&quot;a_toy_example&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#a_toy_example&quot;&gt;¶&lt;/a&gt;A Toy Example&lt;/h2&gt; -&lt;p&gt;That's all about &lt;code&gt;asyncio&lt;/code&gt;! Let's wrap up with some example code. We will create a server that replies with the text a client sends, but reversed. First, we will show what you could write with normal synchronous code, and then we will port it.&lt;/p&gt; -&lt;p&gt;Here is the &lt;strong&gt;synchronous version&lt;/strong&gt;:&lt;/p&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# server.py -import socket - - -def server_method(): - # create a new server socket to listen for connections - server = socket.socket() - - # bind to localhost:6789 for new connections - server.bind(('localhost', 6789)) - - # we will listen for one client at most - server.listen(1) - - # *block* waiting for a new client - client, _ = server.accept() - - # *block* waiting for some data - data = client.recv(1024) - - # reverse the data - data = data[::-1] - - # *block* sending the data - client.sendall(data) - - # close client and server - server.close() - client.close() - - -if __name__ == '__main__': - # block running the server - server_method() -&lt;/code&gt;&lt;/pre&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# client.py -import socket - - -def client_method(): - message = b'Hello Server!\n' - client = socket.socket() - - # *block* trying to stabilish a connection - client.connect(('localhost', 6789)) - - # *block* trying to send the message - print('Sending', message) - client.sendall(message) - - # *block* until we receive a response - response = client.recv(1024) - print('Server replied', response) - - client.close() - - -if __name__ == '__main__': - client_method() -&lt;/code&gt;&lt;/pre&gt; -&lt;p&gt;From what we've seen, this code will block on all the lines with a comment above them saying that they will block. This means that for running more than one client or server, or both in the same file, you will need threads. But we can do better, we can rewrite it into &lt;code&gt;asyncio&lt;/code&gt;!&lt;/p&gt; -&lt;p&gt;The first step is to mark all your &lt;code&gt;def&lt;/code&gt;initions that may block with &lt;code&gt;async&lt;/code&gt;. This marks them as coroutines, which can be &lt;code&gt;await&lt;/code&gt;ed on.&lt;/p&gt; -&lt;p&gt;Second, since we're using low-level sockets, we need to make use of the methods that &lt;code&gt;asyncio&lt;/code&gt; provides directly. If this was a third-party library, this would be just like using their &lt;code&gt;async def&lt;/code&gt;initions.&lt;/p&gt; -&lt;p&gt;Here is the &lt;strong&gt;asynchronous version&lt;/strong&gt;:&lt;/p&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# server.py -import asyncio -import socket - -# get the default &amp;quot;event loop&amp;quot; that we will run -loop = asyncio.get_event_loop() - - -# notice our new &amp;quot;async&amp;quot; before the definition -async def server_method(): - server = socket.socket() - server.bind(('localhost', 6789)) - server.listen(1) - - # await for a new client - # the event loop can run other code while we wait here! - client, _ = await loop.sock_accept(server) - - # await for some data - data = await loop.sock_recv(client, 1024) - data = data[::-1] - - # await for sending the data - await loop.sock_sendall(client, data) - - server.close() - client.close() - - -if __name__ == '__main__': - # run the loop until &amp;quot;server method&amp;quot; is complete - loop.run_until_complete(server_method()) -&lt;/code&gt;&lt;/pre&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# client.py -import asyncio -import socket - -loop = asyncio.get_event_loop() - - -async def client_method(): - message = b'Hello Server!\n' - client = socket.socket() - - # await to stabilish a connection - await loop.sock_connect(client, ('localhost', 6789)) - - # await to send the message - print('Sending', message) - await loop.sock_sendall(client, message) - - # await to receive a response - response = await loop.sock_recv(client, 1024) - print('Server replied', response) - - client.close() - - -if __name__ == '__main__': - loop.run_until_complete(client_method()) -&lt;/code&gt;&lt;/pre&gt; -&lt;p&gt;That's it! You can place these two files separately and run, first the server, then the client. You should see output in the client.&lt;/p&gt; -&lt;p&gt;The big difference here is that you can easily modify the code to run more than one server or clients at the same time. Whenever you &lt;code&gt;await&lt;/code&gt; the event loop will run other of your code. It seems to &amp;quot;block&amp;quot; on the &lt;code&gt;await&lt;/code&gt; parts, but remember it's actually jumping to run more code, and the event loop will get back to you whenever it can.&lt;/p&gt; -&lt;p&gt;In short, you need an &lt;code&gt;async def&lt;/code&gt; to &lt;code&gt;await&lt;/code&gt; things, and you run them with the event loop instead of calling them directly. So this…&lt;/p&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def main(): - ... # some code - - -if __name__ == '__main__': - main() -&lt;/code&gt;&lt;/pre&gt; -&lt;p&gt;…becomes this:&lt;/p&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import asyncio - - -async def main(): - ... # some code - - -if __name__ == '__main__': - asyncio.get_event_loop().run_until_complete(main) -&lt;/code&gt;&lt;/pre&gt; -&lt;p&gt;This is pretty much how most of your &lt;code&gt;async&lt;/code&gt; scripts will start, running the main method until its completion.&lt;/p&gt; -&lt;h2 id=&quot;a_real_example&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#a_real_example&quot;&gt;¶&lt;/a&gt;A Real Example&lt;/h2&gt; -&lt;p&gt;Let's have some fun with a real library. We'll be using &lt;a href=&quot;https://github.com/LonamiWebs/Telethon&quot;&gt;Telethon&lt;/a&gt; to broadcast a message to our three best friends, all at the same time, thanks to the magic of &lt;code&gt;asyncio&lt;/code&gt;. We'll dive right into the code, and then I'll explain our new friend &lt;code&gt;asyncio.wait(...)&lt;/code&gt;:&lt;/p&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# broadcast.py -import asyncio -import sys - -from telethon import TelegramClient - -# (you need your own values here, check Telethon's documentation) -api_id = 123 -api_hash = '123abc' -friends = [ - '@friend1__username', - '@friend2__username', - '@bestie__username' -] - -# we will have to await things, so we need an async def -async def main(message): - # start is a coroutine, so we need to await it to run it - client = await TelegramClient('me', api_id, api_hash).start() - - # wait for all three client.send_message to complete - await asyncio.wait([ - client.send_message(friend, message) - for friend in friends - ]) - - # and close our client - await client.disconnect() - - -if __name__ == '__main__': - if len(sys.argv) != 2: - print('You must pass the message to broadcast!') - quit() - - message = sys.argv[1] - asyncio.get_event_loop().run_until_complete(main(message)) -&lt;/code&gt;&lt;/pre&gt; -&lt;p&gt;Wait… how did that send a message to all three of -my friends? The magic is done here:&lt;/p&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;[ - client.send_message(friend, message) - for friend in friends -] -&lt;/code&gt;&lt;/pre&gt; -&lt;p&gt;This list comprehension creates another list with three -coroutines, the three &lt;code&gt;client.send_message(...)&lt;/code&gt;. -Then we just pass that list to &lt;code&gt;asyncio.wait&lt;/code&gt;:&lt;/p&gt; -&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;await asyncio.wait([...]) -&lt;/code&gt;&lt;/pre&gt; -&lt;p&gt;This method, by default, waits for the list of coroutines to run until they've all finished. You can read more on the Python &lt;a href=&quot;https://docs.python.org/3/library/asyncio-task.html#asyncio.wait&quot;&gt;documentation&lt;/a&gt;. Truly a good function to know about!&lt;/p&gt; -&lt;p&gt;Now whenever you have some important news for your friends, you can simply &lt;code&gt;python3 broadcast.py 'I bought a car!'&lt;/code&gt; to tell all your friends about your new car! All you need to remember is that you need to &lt;code&gt;await&lt;/code&gt; on coroutines, and you will be good. &lt;code&gt;asyncio&lt;/code&gt; will warn you when you forget to do so.&lt;/p&gt; -&lt;h2 id=&quot;extra_material&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#extra_material&quot;&gt;¶&lt;/a&gt;Extra Material&lt;/h2&gt; -&lt;p&gt;If you want to understand how &lt;code&gt;asyncio&lt;/code&gt; works under the hood, I recommend you to watch this hour-long talk &lt;a href=&quot;https://youtu.be/M-UcUs7IMIM&quot;&gt;Get to grips with asyncio in Python 3&lt;/a&gt; by Robert Smallshire. In the video, they will explain the differences between concurrency and parallelism, along with others concepts, and how to implement your own &lt;code&gt;asyncio&lt;/code&gt; &amp;quot;scheduler&amp;quot; from scratch.&lt;/p&gt; &lt;/main&gt; &lt;/body&gt; &lt;/html&gt;
M blog/breaking-ror/index.htmlblog/breaking-ror/index.html

@@ -10,7 +10,7 @@ <body>

<main> <h1 class="title" id="breaking_risk_of_rain"><a class="anchor" href="#breaking_risk_of_rain">¶</a>Breaking Risk of Rain</h1> <div class="date-created-modified">Created 2019-01-12<br> -Modified 2020-08-24</div> +Modified 2020-10-03</div> <p><a href="https://riskofraingame.com/">Risk of Rain</a> is a fun little game you can spend a lot of hours on. It's incredibly challenging for new players, and fun once you have learnt the basics. This blog will go through what I've learnt and how to play the game correctly.</p> <h2 id="getting_started"><a class="anchor" href="#getting_started">¶</a>Getting Started</h2> <p>If you're new to the game, you may find it frustrating. You must learn very well to dodge.</p>
M blog/ctypes-and-windows/index.htmlblog/ctypes-and-windows/index.html

@@ -10,7 +10,7 @@ <body>

<main> <h1 class="title" id="python_ctypes_and_windows"><a class="anchor" href="#python_ctypes_and_windows">¶</a>Python ctypes and Windows</h1> <div class="date-created-modified">Created 2019-06-19<br> -Modified 2020-08-24</div> +Modified 2020-10-03</div> <p><a href="https://www.python.org/">Python</a>'s <a href="https://docs.python.org/3/library/ctypes.html"><code>ctypes</code></a> is quite a nice library to easily load and invoke C methods available in already-compiled <a href="https://en.wikipedia.org/wiki/Dynamic-link_library"><code>.dll</code> files</a> without any additional dependencies. And I <em>love</em> depending on as little as possible.</p> <p>In this blog post, we will walk through my endeavors to use <code>ctypes</code> with the <a href="https://docs.microsoft.com/en-us/windows/desktop/api/">Windows API</a>, and do some cool stuff with it.</p> <p>We will assume some knowledge of C/++ and Python, since we will need to read and write a bit of both. Please note that this post is only an introduction to <code>ctypes</code>, and if you need more information you should consult the <a href="https://docs.python.org/3/library/ctypes.html">Python's documentation for <code>ctypes</code></a>.</p>
M blog/index.htmlblog/index.html

@@ -8,7 +8,7 @@ <link rel="stylesheet" href="css/style.css">

</head> <body> <main> -<ul><li><a href="making-a-difference/index.html">Making a Difference</a></li><li><a href="posts/index.html">Atemporal Blog Posts</a></li><li><a href="university/index.html">University posts</a></li><li><a href="ctypes-and-windows/index.html">Python ctypes and Windows</a></li><li><a href="pixel-dungeon/index.html">Shattered Pixel Dungeon</a></li><li><a href="breaking-ror/index.html">Breaking Risk of Rain</a></li><li><a href="new-computer/index.html">My new computer</a></li><li><a href="tips-outpost/index.html">Tips for Outpost</a></li><li><a href="installing_nixos_2/index.html">Installing NixOS, Take 2</a></li><li><a href="installing_nixos/index.html">Installing NixOS</a></li><li><a href="world_edit/index.html">WorldEdit Commands</a></li><li><a href="asyncio/index.html">An Introduction to Asyncio</a></li><li><a href="sentences/index.html">Sentences</a></li><li><a href="index/index.html">Blog de Lonami</a></li><li><a href="graphs/index.html">Graphs</a></li><li><a href="filosofia/index.html">Apuntes de bachillerato de Filosofía</a></li><li><a href="reflexion_ia/index.html">Reflexión sobre la Inteligencia artificial</a></li><li><a href="inteligencia_artificial/index.html">Inteligencia artificial</a></li></ul></main> +<ul><li><a href="posts/index.html">Atemporal Blog Posts</a></li><li><a href="making-a-difference/index.html">Making a Difference</a></li><li><a href="university/index.html">University posts</a></li><li><a href="ctypes-and-windows/index.html">Python ctypes and Windows</a></li><li><a href="pixel-dungeon/index.html">Shattered Pixel Dungeon</a></li><li><a href="breaking-ror/index.html">Breaking Risk of Rain</a></li><li><a href="asyncio/index.html">An Introduction to Asyncio</a></li><li><a href="new-computer/index.html">My new computer</a></li><li><a href="tips-outpost/index.html">Tips for Outpost</a></li><li><a href="installing_nixos_2/index.html">Installing NixOS, Take 2</a></li><li><a href="installing_nixos/index.html">Installing NixOS</a></li><li><a href="world_edit/index.html">WorldEdit Commands</a></li><li><a href="sentences/index.html">Sentences</a></li><li><a href="index/index.html">Blog de Lonami</a></li><li><a href="graphs/index.html">Graphs</a></li><li><a href="filosofia/index.html">Apuntes de bachillerato de Filosofía</a></li><li><a href="reflexion_ia/index.html">Reflexión sobre la Inteligencia artificial</a></li><li><a href="inteligencia_artificial/index.html">Inteligencia artificial</a></li></ul></main> </body> </html>
M blog/making-a-difference/index.htmlblog/making-a-difference/index.html

@@ -9,7 +9,8 @@ </head>

<body> <main> <h1 class="title" id="making_a_difference"><a class="anchor" href="#making_a_difference">¶</a>Making a Difference</h1> -<div class="date-created-modified">2020-08-24</div> +<div class="date-created-modified">Created 2020-08-24<br> +Modified 2020-10-03</div> <p>When I've thought about what &quot;making a difference&quot; means, I've always seen it as having to do something at very large scales. Something that changes everyone's lives. But I've realized that it doesn't need the case.</p> <p>I'm thinking about certain people. I'm thinking about middle-school.</p> <p>I'm thinking about my math teacher, who I remember saying that if he made a student fail with a grade very close to passing, then he would be a bad teacher because he could just &quot;let them pass&quot;. But if he just passed that one student, he would fail as a teacher, because it's his job to get people to actually <em>learn</em> his subject. He didn't want to be mean, he was just trying to have everybody properly learn the subject. That made a difference on me, but I never got the chance to thank him.</p>
M blog/mdad/atom.xmlblog/mdad/atom.xml

@@ -1,4 +1,4 @@

-<feed xmlns="http://www.w3.org/2005/Atom"><title>pagong</title><id>pagong</id><updated>2020-08-23T22:00:00+00:00</updated><entry><title>Data Mining and Data Warehousing</title><id>dist/index/index.html</id><updated>2020-08-23T22:00:00+00:00</updated><published>2020-08-23T22:00:00+00:00</published><summary>During 2020 at university, this subject ("Minería de Datos y Almacenes de Datos") had us write</summary><content type="html" src="dist/index/index.html">&lt;!DOCTYPE html&gt; +<feed xmlns="http://www.w3.org/2005/Atom"><title>pagong</title><id>pagong</id><updated>2020-10-02T22:00:00+00:00</updated><entry><title>Data Mining and Data Warehousing</title><id>dist/index/index.html</id><updated>2020-10-02T22:00:00+00:00</updated><published>2020-10-02T22:00:00+00:00</published><summary>During 2020 at university, this subject ("Minería de Datos y Almacenes de Datos") had us write</summary><content type="html" src="dist/index/index.html">&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot; /&gt;

@@ -9,7 +9,7 @@ &lt;/head&gt;

&lt;body&gt; &lt;main&gt; &lt;h1 class=&quot;title&quot; id=&quot;data_mining_and_data_warehousing&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#data_mining_and_data_warehousing&quot;&gt;¶&lt;/a&gt;Data Mining and Data Warehousing&lt;/h1&gt; -&lt;div class=&quot;date-created-modified&quot;&gt;2020-08-24&lt;/div&gt; +&lt;div class=&quot;date-created-modified&quot;&gt;2020-10-03&lt;/div&gt; &lt;p&gt;During 2020 at university, this subject (&amp;quot;Minería de Datos y Almacenes de Datos&amp;quot;) had us write blog posts as assignments. I think it would be really fun and I wanted to preserve that work here, with the hopes it's interesting to someone.&lt;/p&gt;
M blog/mdad/index/index.htmlblog/mdad/index/index.html

@@ -9,7 +9,7 @@ </head>

<body> <main> <h1 class="title" id="data_mining_and_data_warehousing"><a class="anchor" href="#data_mining_and_data_warehousing">¶</a>Data Mining and Data Warehousing</h1> -<div class="date-created-modified">2020-08-24</div> +<div class="date-created-modified">2020-10-03</div> <p>During 2020 at university, this subject (&quot;Minería de Datos y Almacenes de Datos&quot;) had us write blog posts as assignments. I think it would be really fun and I wanted to preserve that work here, with the hopes it's interesting to someone.</p>
M blog/pixel-dungeon/index.htmlblog/pixel-dungeon/index.html

@@ -10,7 +10,7 @@ <body>

<main> <h1 class="title" id="shattered_pixel_dungeon"><a class="anchor" href="#shattered_pixel_dungeon">¶</a>Shattered Pixel Dungeon</h1> <div class="date-created-modified">Created 2019-06-03<br> -Modified 2020-08-24</div> +Modified 2020-10-03</div> <p><a href="https://shatteredpixel.com/shatteredpd/">Shattered Pixel Dungeon</a> is the classic roguelike RPG game with randomly-generated dungeons. As a new player, it was a bit frustrating to be constantly killed on the first levels of the dungeon, but with some practice it's easy to reach high levels if you can kill the first boss.</p> <h2 id="basic_tips"><a class="anchor" href="#basic_tips">¶</a>Basic Tips</h2> <p>The game comes with its own tips, but here's a short and straight-forward summary:</p>
M blog/posts/index.htmlblog/posts/index.html

@@ -9,7 +9,7 @@ </head>

<body> <main> <h1 class="title" id="atemporal_blog_posts"><a class="anchor" href="#atemporal_blog_posts">¶</a>Atemporal Blog Posts</h1> -<div class="date-created-modified">2020-08-24</div> +<div class="date-created-modified">2020-10-03</div> <p>These are some interesting posts and links I've found around the web. I believe they are quite interesting and nice reads, so if you have the time, I encourage you to check some out.</p> <h2 id="algorithms"><a class="anchor" href="#algorithms">¶</a>Algorithms</h2> <ul>
M blog/ribw/atom.xmlblog/ribw/atom.xml

@@ -1,4 +1,4 @@

-<feed xmlns="http://www.w3.org/2005/Atom"><title>pagong</title><id>pagong</id><updated>2020-08-23T22:00:00+00:00</updated><entry><title>Information Retrieval and Web Search</title><id>dist/index/index.html</id><updated>2020-08-23T22:00:00+00:00</updated><published>2020-08-23T22:00:00+00:00</published><summary>During 2020 at university, this subject ("Recuperación de la Información y Búsqueda en la Web")</summary><content type="html" src="dist/index/index.html">&lt;!DOCTYPE html&gt; +<feed xmlns="http://www.w3.org/2005/Atom"><title>pagong</title><id>pagong</id><updated>2020-10-02T22:00:00+00:00</updated><entry><title>Information Retrieval and Web Search</title><id>dist/index/index.html</id><updated>2020-10-02T22:00:00+00:00</updated><published>2020-10-02T22:00:00+00:00</published><summary>During 2020 at university, this subject ("Recuperación de la Información y Búsqueda en la Web")</summary><content type="html" src="dist/index/index.html">&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot; /&gt;

@@ -9,7 +9,7 @@ &lt;/head&gt;

&lt;body&gt; &lt;main&gt; &lt;h1 class=&quot;title&quot; id=&quot;information_retrieval_and_web_search&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#information_retrieval_and_web_search&quot;&gt;¶&lt;/a&gt;Information Retrieval and Web Search&lt;/h1&gt; -&lt;div class=&quot;date-created-modified&quot;&gt;2020-08-24&lt;/div&gt; +&lt;div class=&quot;date-created-modified&quot;&gt;2020-10-03&lt;/div&gt; &lt;p&gt;During 2020 at university, this subject (&amp;quot;Recuperación de la Información y Búsqueda en la Web&amp;quot;) had us write blog posts as assignments. I think it would be really fun and I wanted to preserve that work here, with the hopes it's interesting to someone.&lt;/p&gt;
M blog/ribw/index/index.htmlblog/ribw/index/index.html

@@ -9,7 +9,7 @@ </head>

<body> <main> <h1 class="title" id="information_retrieval_and_web_search"><a class="anchor" href="#information_retrieval_and_web_search">¶</a>Information Retrieval and Web Search</h1> -<div class="date-created-modified">2020-08-24</div> +<div class="date-created-modified">2020-10-03</div> <p>During 2020 at university, this subject (&quot;Recuperación de la Información y Búsqueda en la Web&quot;) had us write blog posts as assignments. I think it would be really fun and I wanted to preserve that work here, with the hopes it's interesting to someone.</p>
M blog/university/index.htmlblog/university/index.html

@@ -10,7 +10,7 @@ <body>

<main> <h1 class="title" id="university_posts"><a class="anchor" href="#university_posts">¶</a>University posts</h1> <div class="date-created-modified">Created 2020-07-03<br> -Modified 2020-08-24</div> +Modified 2020-10-03</div> <p>During university, there were a few subjects where I had to write blog posts for (either as evaluable tasks or just for fun). Currently, these are:</p> <ul>