<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kimberly McCarty on Medium]]></title>
        <description><![CDATA[Stories by Kimberly McCarty on Medium]]></description>
        <link>https://medium.com/@kimberly_mc?source=rss-cf0050b63bbc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o_86rOHo3BgY7h4tp4cmoA.jpeg</url>
            <title>Stories by Kimberly McCarty on Medium</title>
            <link>https://medium.com/@kimberly_mc?source=rss-cf0050b63bbc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:00:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kimberly_mc/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bitmaps (TGA format): Let’s Take a Good Look: Multitudes Entry 2]]></title>
            <link>https://medium.com/@kimberly_mc/bitmaps-tga-format-lets-take-a-good-look-multitudes-entry-2-d206c63ce4e0?source=rss-cf0050b63bbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d206c63ce4e0</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[file-format]]></category>
            <dc:creator><![CDATA[Kimberly McCarty]]></dc:creator>
            <pubDate>Wed, 22 Nov 2017 00:50:48 GMT</pubDate>
            <atom:updated>2017-11-22T00:51:15.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*9RXoL74BhoWdmka5." /><figcaption>this man’s face is worth three bytes per pixel</figcaption></figure><p>This is the next entry in my posts about file encodings. Which I named Multitudes because I’m that big a dork re: Walt Whitman references.</p><p>Learn a bit about how the TGA format turns an image into a list of bytes that are easy to encode and decode!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bc66c1869bf0de3877e44d767eb362f/href">https://medium.com/media/2bc66c1869bf0de3877e44d767eb362f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d206c63ce4e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WAV files: Make some noise: Multitudes, Entry 1]]></title>
            <link>https://medium.com/@kimberly_mc/wav-files-make-some-noise-multitudes-entry-1-2e3ff5a17536?source=rss-cf0050b63bbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e3ff5a17536</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[wav-file]]></category>
            <dc:creator><![CDATA[Kimberly McCarty]]></dc:creator>
            <pubDate>Tue, 14 Nov 2017 03:32:51 GMT</pubDate>
            <atom:updated>2017-11-14T03:32:51.893Z</atom:updated>
            <content:encoded><![CDATA[<p>Part of a series that started with <a href="https://medium.com/@kimberly_mc/whats-inside-files-what-even-are-files-multitudes-entry-0-5f79bad6cf6a">Entry 0: What’s Inside Files? What Even are Files?</a></p><p>Yet again, Jupyter Notebooks seem to be an issue for me on this platform.</p><p><a href="https://github.com/mccartykim/multitudes/blob/master/1_wav_lets_make_some_noise/entry_1.ipynb">mccartykim/multitudes</a></p><p>^ There’s a link to the notebook rendered on GitHub, and below is a quick-and-dirty GitHub Gist rendering:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/662d87f81dd79a110d0af410bb7a11a5/href">https://medium.com/media/662d87f81dd79a110d0af410bb7a11a5/href</a></iframe><p>Below is the WAV metadata bytes diagram I wish I could have included.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*7q8VbkIObAadWCFLKALSbg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e3ff5a17536" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s inside files? What even are files? Multitudes Entry 0]]></title>
            <link>https://medium.com/@kimberly_mc/whats-inside-files-what-even-are-files-multitudes-entry-0-5f79bad6cf6a?source=rss-cf0050b63bbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f79bad6cf6a</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[files]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kimberly McCarty]]></dc:creator>
            <pubDate>Tue, 14 Nov 2017 03:11:40 GMT</pubDate>
            <atom:updated>2017-11-14T18:48:36.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zu41cArrWbgLaN4bzQkC4A.jpeg" /><figcaption>files can contain tapirs ❤</figcaption></figure><p>I’m working on a series of articles about file encoding. I’m hoping I can share them through this blog, but I’m starting to see the limitations of Medium when it comes to sharing things like IPython notebooks. Especially once I add images. It’s a shame, as I like Medium so much for writing and sharing text, but I’ve fallen in love with IPython Notebooks for describing code. If anybody has tips, let me know!</p><p><a href="https://github.com/mccartykim/multitudes">Here’s the GitHub repo</a></p><p>And here is the nicely rendered notebook on NBViewer.</p><p><a href="http://nbviewer.jupyter.org/github/mccartykim/multitudes/blob/master/0_what_is_a_file/what_is_a_file.ipynb">Notebook on nbviewer</a></p><p>But if you want to read it inside Medium (understandable), here’s an embedded Github Gist of my first entry in the series.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6d6823c32901e430c190e050ad49bb9/href">https://medium.com/media/a6d6823c32901e430c190e050ad49bb9/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f79bad6cf6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Arithmetic Parser in Python 3]]></title>
            <link>https://medium.com/@kimberly_mc/an-arithmetic-parser-in-python-3-f4458cfb5cbd?source=rss-cf0050b63bbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4458cfb5cbd</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[parser]]></category>
            <category><![CDATA[formal-grammar]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kimberly McCarty]]></dc:creator>
            <pubDate>Thu, 09 Nov 2017 19:19:40 GMT</pubDate>
            <atom:updated>2017-11-09T19:19:40.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/448/0*RGeCTh2m-gB6eRkC." /></figure><p>Back in college, I bought a really cute calculator that can’t run programs or anything so I could take exams. I felt bad I wasn’t using it as much now that I’m in an environment I can use my laptop and phone for math, and thought it could be lonely.</p><p>So I made it a friend using a formal grammar, and a recursive descent parser.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e436486ad7cd2ef91a483adc7d37474/href">https://medium.com/media/9e436486ad7cd2ef91a483adc7d37474/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4458cfb5cbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving Into List Comprehensions in Python3: an IPy Notebook]]></title>
            <link>https://medium.com/@kimberly_mc/diving-into-list-comprehensions-in-python3-an-ipy-notebook-1cee890fab06?source=rss-cf0050b63bbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cee890fab06</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bytecode]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kimberly McCarty]]></dc:creator>
            <pubDate>Tue, 31 Oct 2017 18:55:40 GMT</pubDate>
            <atom:updated>2017-10-31T18:56:08.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*Px5qATNSAyPmCGL-.png" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:Chrysopoea_of_Cleopatra_1.png">wikimedia</a>, text probably translates to “drat i failed to consider what i am actually doing”</figcaption></figure><p>Today, I wrote a solution to a “simple” problem that started timing out. I realized I missed a simple error because I failed to consider what Python’s abstractions were doing. I used this as an excuse to finally check out dis, and learn more about what’s happening inside my favorite language.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb35aadca99aed763876b6517f9f2d45/href">https://medium.com/media/fb35aadca99aed763876b6517f9f2d45/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cee890fab06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding Experiment: Asynchronous Event Loop]]></title>
            <link>https://medium.com/@kimberly_mc/coding-experiment-asynchronous-event-loop-584b4f596a2?source=rss-cf0050b63bbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/584b4f596a2</guid>
            <category><![CDATA[coding-experiment]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kimberly McCarty]]></dc:creator>
            <pubDate>Sat, 21 Oct 2017 00:30:55 GMT</pubDate>
            <atom:updated>2017-10-21T00:35:43.021Z</atom:updated>
            <content:encoded><![CDATA[<p>Last night, at the RC Job Fair, a python engineer suggested a good way to better understand event loops is to write one yourself. It sounded interesting, and I felt like I understood the gist of the idea.</p><p>I once heard that to really understand something in programming, you need a grasp on what’s happening one level of abstraction deeper. So if you want to understand the HTTP protocol, it helps to learn a bit about TCP sockets, and I guess if you want to learn about asyncio or some other single-threaded coroutine-centric library, you want to learn about event loops.</p><p>So I went and made one myself today, and got a little more familiar with python generators and what presumably goes on under the hood for Python libs like asyncio and twisted.</p><p><a href="http://nbviewer.jupyter.org/github/mccartykim/my_async/blob/fcefb142d49b80d8db1876e683e2e27626678161/my_async.ipynb">Here it is</a>. Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=584b4f596a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modeling Crochet as a Programmer]]></title>
            <link>https://medium.com/@kimberly_mc/modeling-crochet-as-a-programmer-64e9a79b8061?source=rss-cf0050b63bbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/64e9a79b8061</guid>
            <category><![CDATA[crochet]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kimberly McCarty]]></dc:creator>
            <pubDate>Thu, 19 Oct 2017 16:47:18 GMT</pubDate>
            <atom:updated>2017-10-19T16:47:20.423Z</atom:updated>
            <content:encoded><![CDATA[<p>During my batch at the Recurse Center, I’ve worked on both larger projects (like my BitTorrent client) and smaller projects (like my Moniac JS simulation and twitterbot). One source of small projects I’ve gone back to over and over is crochet. Lately, I’m working on a tool that attempts to make lace patterns from images, with scaling and dithering. It’s nowhere near finished. This is essentially my notes on the process of representing crochet with a program in general.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_yVw7DKuplWvDCHTqa-_g.jpeg" /><figcaption><a href="https://www.flickr.com/photos/moonrat/5809243391">source</a></figcaption></figure><p>Crochet is an interesting craft to me, as it is relatively easy and forgiving. You can drop a crochet project and probably not lose any stitches, unlike with a knitting project. And you can make a mistake and often improvise around it later. I also like the aesthetic of crocheted objects, and like how it works well with cheap cotton yarn.</p><p>A crochet pattern describes a series of steps to create an object made of stitches. Patterns sometimes use repetition and custom stitch notations for more complicated patterns. In that way, they remind me of loops and macros in programs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*y3QfL36QQ3HS3Dyw.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Spring_system">From Wikipedia</a></figcaption></figure><p>A crocheted object gets its shape from the connection between stitches. To model it mathematically, I’ve found a spring-mass network or force-directed graph (itself a kind of spring network) works well for objects that are either flat or three dimensional, but a simple mesh is good enough for flat crochet objects.</p><p>Further, crochet can be worked either flat or in the round. Flat crochet is easy to describe in rectangular coordinates. Polar coordinates come in handy for crochet done in the round, as you’re describing either a series of circular rows or one spiral. If it’s not done with a constant amount of increases (which creates a flat circle like a doily), it can create a cylinder, or a tube, or all kinds of variations on 3d forms.</p><p>If you’re unfamiliar with polar coordinates, it’s an alternative to rectangular coordinates where you have <em>r</em>, a unit describing the distance from the origin (radius), and <em>theta</em>, a unit describing the rotation from the origin. It’s very easy to convert points to rectangular coordinates (x = r cos(theta), y = r sin(theta)), and back. (r = sqrt(x*x + y*y), theta = atan2(y, x))</p><p>With either a static mesh or spring network, you model each stitch as a vertex, and add edges to connect those vertices. Edges can be stored in an “adjacency list,” a list of pairs of vertices for each edge.</p><p>Fabrics in general model well with a spring-mass network, where each stitch is a mass, and each thread between those stitches is a spring. After all, most cloth can stretch a little, or be crumpled up, and then return back to its “normal” shape. According to Hooke’s law, a spring has a relaxed length where its displacement, <em>X</em>, is zero, and a “spring constant,” <em>k</em>, which models how much force a spring will apply if deformed from its relaxed length. The equation is <em>F = kX. </em>It makes sense to apply damping or friction to this force, as otherwise the system is prone to oscillation.</p><p>In the spring-mass network model, each point (or stitch) is a movable object with mass, and three vectors (position, velocity, and acceleration). Each iteration of the game loop, any forces are added to acceleration, acceleration is added to velocity, velocity is added to position, and acceleration is set to 0. Or a different integration is used to transfer force to acceleration to velocity to position, but that’s outside the scope here. Here’s the pseudocode of a phsyics object in 2d.</p><pre>Class Mover {<br>Mover(x,y,m){<br>float this.mass = m;<br>Vector this.position = Vector(x,y);<br>Vector this.velocity = Vector(0,0);<br>Vector this.acceleration = Vector(0,0);<br>}</pre><pre>//add force vector from the game world<br>void addForce(f){<br>this.acceleration.add(f.div(m));<br>}<br>void update(){<br>this.velocity.add(this.acceleration);<br>this.position.add(this.velocity);<br>this.acceleration.mult(0);<br>}<br>}</pre><p>So, write a function that determines how far apart two points are, and subtract it from the “correct” distance, and multiply that difference by K. Then apply that force to each object, rotated at the other object.</p><pre>const DAMPING = 0.9;<br>Vector spring(pos1, pos2, rel_len, K){<br>float x= rel_len - pos1.dist(pos2);<br>float mag = K*x;<br>//get unit vector towards position 2, and scale it to magnitude<br>return pos1.dir(pos2).mult(mag).mult(damping);<br>}</pre><p>Of course, not every edge will find its relaxed length, but with a good K value and a little damping, the network will find a relatively relaxed position.</p><p>All of this assumes the network will be made of one type of stitch. I tend to model single crochet as it’s easy, but other stitches could probably be modeled with some variant of chains between the top and bottom of the stitch.</p><p>I’m also curious how crochet could be modeled in Box2d or another “serious” physics library, but I have yet to try that. I imagine it could cut back on some of my repeated code and less-than-ideal integration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64e9a79b8061" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leaving the Nest: Let your Twitter Bot fly among the clouds]]></title>
            <link>https://medium.com/@kimberly_mc/leaving-the-nest-let-your-twitter-bot-fly-among-the-clouds-f0b469bde495?source=rss-cf0050b63bbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0b469bde495</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[twitterbots]]></category>
            <dc:creator><![CDATA[Kimberly McCarty]]></dc:creator>
            <pubDate>Wed, 11 Oct 2017 18:29:31 GMT</pubDate>
            <atom:updated>2017-10-11T18:29:31.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*mb9fKXsZY4kJxP5u.jpg" /><figcaption>Enrich your life by adding a robot child to your legacy</figcaption></figure><p>Writing a Twitter Bot is a fun programming exercise for programmers of any skill level. There’s lots of API wrappers for every language, and in the end, all you need to worry about is producing a script that makes some text or maybe an image. This goes double for Mastodon, the scrappy new federated microblogging network you’ll probably love if Twitter’s moderation has let you down.</p><p>I personally like Python and the Tweepy, but this guide should work for any language that runs on Heroku. I’m going to assume you’ve composed your bot of scripts that can be called from the command line, and already have the bot working on your local machine.</p><p>You’ll also need your own twitter API keys from <a href="https://apps.twitter.com/">apps.twitter.com</a>. Twitter requires four cryptographic strings (Consumer key, consumer secret, Access token and Access token secret), which you can generate for your own account through the Twitter developer page, or you can request the access token and access token secret from Tweepy in the python repl following the guide in <a href="http://docs.tweepy.org/en/v3.5.0/auth_tutorial.html">Tweepy’s docs</a>.</p><p>Periodically running a script is a decent option if you don’t need your twitter bot to reply immediately to somebody. On the free tier, your script will run every 10 minutes or every hour, or daily, which I think are perfectly decent frequencies for the sort of bots I would like to make.</p><p>And if your bot needs to change or save data, you need to make sure it’s working with an interface that stores it on one of the DBs Heroku provides. I like PostgreSQL because it works with ORMs like SQLAlchemy and Pony, and I’m comfortable writing some raw SQL in a pinch. But you can definitely use other databases/datastores. Sadly, you can’t write to file, because Heroku resets your app’s filesystem between programs.</p><p>The thing to understand about Heroku is that most of the documentation assumes you’re going to host a program that will be accessible via HTTP requests. So either a web app or a REST-ful API. This isn’t our case, though. So don’t worry about webservers or workers or anything like that. We’re going to summon just one worker for when we run our script.</p><p>Create an empty file named Procfile, which will tell Heroku explicitly to not try to start a server or map your app to any URLs.</p><p>I’m assuming you have Python 3.6 installed along with <a href="https://github.com/kennethreitz/pipenv">Pipenv</a>. If not, Pipenv is a great tool that makes Python’s pip package management and virtual environments a lot more comfortable. Install all your libraries with pipenv install and then run pipenv lock so that Heroku will see your Pipfile. And if your project isn’t a git repo, make it one with</p><p>git init</p><p>git add .</p><p>git rm ANYTHING_WITH_YOUR_CREDENTIALS</p><p>git commit -m &quot;Initial commit&quot;</p><p>Using the Heroku CLI, login to Heroku and then runheroku create, and now your git repo will have a remote repo on Heroku’s servers, and your project will have a randomly generated name you can reach from your dashboard on Heroku.com. You can type in git push heroku master to upload or update your code, just like on Github.</p><p>You do not want to share your twitter API keys on a public Github (anybody could tweet as you or abuse twitter’s services in your name). I strongly encourage you to not store those in files, and if you have those files, list them in .gitignore.</p><p>The best practice on Heroku is to use “config variables” to hold your keys. These keys are accessible to your program as environmental variables. In Python, these are exposed with the os.environ object (import OS for it to work). So where you’d load your keys from a file, instead put those in this page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*YMPXMWnyiRzFMwvQtyOEOQ.png" /></figure><p>And call them by their keys in python like os.environ[“TWITTER_OAUTH_SECRET”]. You can set them locally, too. Every operating system has its own flavor of environmental variables.</p><p>While you’re in Heroku’s dashboard for your app, click the “Resources” tab, and then the purple “Find more add-ons” button. Install an add-on called Heroku scheduler. You can see I also installed the free tier of the PostgreSQL service. Make sure you have whatever database you’d like set up, and read about <a href="https://devcenter.heroku.com/articles/heroku-postgresql">how to connect to it safely</a> from your app. Again, you don’t want to accidentally leak your keys on github!</p><p>Make sure everything is working locally and you’ve committed and pushed all your changes on the master branch to Heroku (git push heroku master ). Now, let’s try it out. Run the command heroku run bash, and you’re now inside a shell with python set up to match your Pipfile specifications. Try running your script here. Does it work? Great! If it doesn’t, now’s the time to start debugging. Heroku’s docs are pretty well written, and it’s popular enough to have lots of answers from other users online. If you have a database, initialize it now.</p><p>Now that it works, let’s got into the resources tab on the Heroku dashboard. Under add-ons, click on Heroku Scheduler. You’ll see a page like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*uJ8wRbWDozXkvAsgt1zkDg.png" /></figure><p>Type in whatever command starts your script. In my case, I have the python interpreter start my main script. This is the same as anything you could run from your bash command line.</p><p>And, congratulations! Your bot has left the nest, and is out on its own making friends and getting the followers you yourself wish you could have attracted in life. You may find yourself living vicariously through its success, and perhaps you’ll git clone it home for a chat sometimes, where you then offer it new suggestions and features and bask in a warm contentment at a job well done.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0b469bde495" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a Bit Torrent Client: Step 1]]></title>
            <link>https://medium.com/@kimberly_mc/writing-a-bit-torrent-client-step-1-6cefb256fe87?source=rss-cf0050b63bbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cefb256fe87</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[parser]]></category>
            <dc:creator><![CDATA[Kimberly McCarty]]></dc:creator>
            <pubDate>Tue, 03 Oct 2017 21:35:15 GMT</pubDate>
            <atom:updated>2017-10-09T19:54:58.916Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m not sure I’ve been explicit about this, but I’m participating at the Recurse Center and I’m about halfway through, and figured I’d spend batch part 2 writing a BitTorrent client. At the very least, I’ll have some interesting components made if not the whole thing.</p><p>I’m working from <a href="http://www.bittorrent.org/beps/bep_0003.html">Bram Cohen’s BEP 0003 spec,</a> and the first item after a broad overview of how BitTorrent works from the application level is Bencoding. Bencoding is BitTorrent’s own message encoding system, and it’s meant to be terse and easy to parse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*bQizynriiLQHwds7-y0qSQ.png" /></figure><p>For me, my mind went straight to grammars and Noam Chomsky and all the other cool folks who have profound thoughts on language and computer science. I knew writing a parser was in my future, and that got me excited. Parsers were things smart people write!</p><p>But first, I focused on encoding, translating the obvious Python equivalent types to bencoding’s types. Python’s bytestrings (‘bytes’), integers (‘int’), lists (‘[]’), and dictionaries (‘{}’) can all operate just great under these rules with small restrictions. For example, a Python dict’s key can be many types, but here that key must be a string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d454dcb48526eff53a73d6a926981cea/href">https://medium.com/media/d454dcb48526eff53a73d6a926981cea/href</a></iframe><p>encode_integer and encode_string are both fairly simple, just following the rules to turn their types into strings wrapped with the right flags. And encode_list and encode_dict recurse back to encode for the objects they can hold.</p><p>Doing it in reverse was more confusing. While I knew of grammars and how to make a parse tree, I’d never written a parser. My Theory of Language Design professor was old fashioned and believed that theory was best diagrammed/discussed on paper. But that’s good, because it gave me a great first step towards building a recursive descent parser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ad7DnDBA8tgwa_v7DucBeg.jpeg" /><figcaption><a href="https://www.youtube.com/watch?v=nRYswTXDYog">I’m sorry?</a></figcaption></figure><p>Here’s my sketch of Bencoding grammar, following the rules that should apply to a recursive descent parser, the big one being no left recursion. That means I shouldn’t have B -&gt; B or anything like that.</p><p>Terminals are symbols that can’t be replaced, so i, e, integer digits, and so on are terminals. Nonterminals are the symbols we can break own in our parse trees, to the point we have a string of terminals.</p><p>Each non-terminal becomes a function, and that function manages each of the options the terminal can become. And then it calls the function for whatever non-terminals it contains and returns those results, or parses and returns whatever terminal it found.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66c979e87fb26990e8e10146cdbc4a11/href">https://medium.com/media/66c979e87fb26990e8e10146cdbc4a11/href</a></iframe><p>Here we have pieces of my Parser class, which has two fields to keep track of state, cursor and s. s is the string buffer, and cursor is the current spot the client is looking at. And a function that makes sure those variables are set properly for an unread, well-formed bencode bytestring.</p><p>And we have B, our most broad Bencode statement rule, which envelops all the other nonterminals, and which is always our root. It lacks terminals of its own, and just dispatches the appropriate nonterminal function for whatever character it finds. Luckily, there’s no ambiguity in bencoding, a digit means a string, an l means a list, a d means a dict, and a i means an int.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d522ebf69f63504c4681b9389e679eb1/href">https://medium.com/media/d522ebf69f63504c4681b9389e679eb1/href</a></iframe><p>These two functions are relatively simple, and just translate the bytestring to their respective types with regexes and built-in python parsing functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0537af44a6a769f8a34b0e6047803dd8/href">https://medium.com/media/0537af44a6a769f8a34b0e6047803dd8/href</a></iframe><p>And here we have the functions that put the recursion into this problem. I got a bit excited in the comments, because even after earning a degree and working at a place literally called the Recurse Center, divide and conquer recursion solutions are still exciting. It took me a bit of thinking for some reason to get how a kleene star (*) would work in logic, and I even wondered if it was legal. Then I realized a while loop would do a fine job, especially since the functions deeper in the call-stack would move the cursor to the next token of interest. While next token is not e, keep parsing. What to parse? I don’t know, it’s some flavor of B, let B() deal with it. And then it just works, whether we have an empty list, a list of dicts, a dict of lists, a list of ints, or some other wild structure.</p><p>And that’s my first parser.</p><p>See the whole mess at <a href="https://github.com/mccartykim/bittorrent/">https://github.com/mccartykim/bittorrent/</a> in the file bencode.py</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cefb256fe87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Bestiary of Python’s Asyncio]]></title>
            <link>https://medium.com/@kimberly_mc/a-bestiary-of-pythons-asyncio-9fe4d93fa145?source=rss-cf0050b63bbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fe4d93fa145</guid>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[short-post]]></category>
            <dc:creator><![CDATA[Kimberly McCarty]]></dc:creator>
            <pubDate>Tue, 26 Sep 2017 17:03:29 GMT</pubDate>
            <atom:updated>2017-09-26T17:03:29.870Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post is sort of meant to be my thoughts/notes on <strong>Asyncio</strong>, a library I’d like to understand in Python 3.5 and later. I’m writing this at a pretty novice level, because it helps to understand what abstractions asynchronous programming takes advantage of. I encourage you to read more about operating systems or syscalls if you haven’t considered their relation to the python interpreter, even if you never end up using them in practice.</p><p>In my rough understanding, asyncio is a library built in to Python that adds asynchronous concurrency, so that one thread can better juggle several tasks.</p><p>In any modern operating system, a network request or IO request is abstracted away by parts of the OS. So if you tell Python, “Hey, I want to get this data from this address at this port using this protocol,” Python calls some wrapper around your operating system’s system call (if you don’t know system calls, they’re like functions programs can ask the OS to do, and it includes stuff like reading from the filesystem, getting the time, or generating a secure random number). This is why Python’s socket API and file API look extremely similar to the APIs in C. Python is not in charge of turning your URL requests into ethernet protocol frames, or figuring out how to turn a file modification in a certain directory into a bunch of writes on a magnetic disk.</p><p>The idea behind asynchronous programming is to teach a single thread, which reads one line of code at a time, to go ahead and do something else when a slow operation starts. Just waiting is called blocking, and while it can be fine in some contexts (like if you want to download a few web pages once and parse their text), if your application is IO heavy, you leave your interpreter, and thus CPU, sitting around bored. It would be better if your function could generously say, “Hey, I’m going to be a while, let somebody else take a turn.” Then, the interpretter can look at what else needs attention and keep your application quick and responsive.</p><p>That’s what <strong>coroutines</strong> allow. A coroutine function is declared like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a7b86055e9d958eff28316db87939a0/href">https://medium.com/media/4a7b86055e9d958eff28316db87939a0/href</a></iframe><p>To a computer, a minute is a lifetime. If this was a function in a chatbot, imagine how many requests would have been lost if we used time.sleep().</p><p>But because we used await, the event loop knows to put this function down and come back to it until 60 seconds have passed. During that time, the event loop can look for something else to do.</p><p>Coroutines are pretty similar to generators, as they’re functions that do something, and then yield control and sometimes a partial or current result. The older syntax for coroutines actually was “yield from” before they decided await was more intuitive.</p><p><strong>Futures </strong>left me a big confused, since the future is a term that has a lot of meanings in social usage. But it helps a bit to know futures are called “promises” in other languages. And that futures are more or less a way to keep track of some task you put on the event loop. They keep track of the task so you can call functions on it or cancel it, and hold the result when it’s done.</p><p>For a “real world” example, if you take a silk shirt to the dry cleaner’s, they will give you a paper receipt with a number to keep track of the order. That slip is a future. You’ll use it to get the result of your dry cleaning (clean shirt!), and you can call the dry cleaner with that number if you have instructions (“Cancel it!” Or, “I’m allergic to that chemical!” Or, “I’ll be out of town, how long will you hold on to it?”).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37c6dcca495b41885a375abbc73ea6bd/href">https://medium.com/media/37c6dcca495b41885a375abbc73ea6bd/href</a></iframe><p>But what if you don’t want to explicitly communicate with a feature, and just let your function/coroutine work like a regular function, where you have input, output, and take a couple breaks in the middle? Enter tasks.</p><p>A<strong> task</strong> is a type of future with a coroutine attached, so that the event loop can tell you the status of the task and give you a place to talk to your coroutine. In practice, a task is the future the event loop hands back when you run a task. To me, a task feels even more like that dry cleaning receipt, in that it’s an object with references to something I’m trusting to the event loop! And while above, I explicitly made the future, here, the Asyncio library made it for me.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a7b86055e9d958eff28316db87939a0/href">https://medium.com/media/4a7b86055e9d958eff28316db87939a0/href</a></iframe><p>Above, we see that our coroutine explicitly becomes a future when we call loop.create_task, and when we pass that task to print_future by a callback, print_future sees a future with our coroutine’s output in it.</p><p>So there’s a lot of somewhat confusing language to asyncio, but it’s not really that alien once you get the metaphors the developers were going for.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fe4d93fa145" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>