Goodness that’s a lot of stuff! I still remember when even the Host header was optional (in HTTP/0.91). And my knowledge taps out around HTTP/1.1, the Connection: keep-alive and the Accept headers.. Anyway, what else is there?
The sec-ch-ua stuff is a modern replacement for User-Agent
DNT, sec-gpc, and permissions-policy are various requests to preserve my privacy. I just installed OptMeOwt, it is adding some of these. I think permissions-policy is a Google thing.
The Sec-Fetchstuff is about the intent of the request and is apparently used to make decisions related to CSRF, CORS, etc.
Upgrade-Insecure-Requests is telling the webserver to redirect me to https if it can.
In general sec- is a “forbidden request header”: only the browser is allowed to set these headers, not Javascript on the page. (Extensions can set them though.)
One other trivia I learned about: HTTP Trailers. This lets you set more headers at the end of an HTTP request instead of the start. Say data you only know about after a long POST or something. These date all the way back to 1997 and HTTP/1.1 apparently but I’ve never encountered them. They don’t work with the simplest request format since there’s no way to identify the end of the HTTP body. Chunked encoding allows for them and I imagine later encodings have something similar.
I’m tinkering with my postcards project. It’s a thread unroller: it takes Mastodon threads and reformats them in a way that makes sense for my “travel postcard” format I post in when I’m on a trip. This whole thing was vibe coded from the start, but I like the result enough I’m trying to turn it into a real tool and maybe a hosted product at some point.
Anyway, today’s task was to convert the images from JPG to WebP to save space. It’s not a general image tool: this is taking tourist snaps from my pixel camera and displaying them in web box nominally 800 pixels wide. The images themselves are 1600 px and I’m mostly testing visually on a HighDPI display.
The end result was the old 800px JPGs took 10M, simple 1600px JPGs took 36M, and 1600px WebP at quality=50 took 16M. The WebP looks as good as the JPG to me, even at the low quality setting. (The JPGs were at quality 85, I think, whatever the default is.)
Encoding parameters
The end result I landed on is quality=50, method=6. This is a remarkably low quality! Last time I looked at this I ended up with quality 90. But for this application with the 2x images I’d rather have a smaller file.
FWIW I tested with an input file that’s 388k as a JPEG quality 85. Output sizes in webp from quality 10 to 90:
60 76 96 116 132 148 168 216 364
I also briefly tested method 4 vs method 6. Method 6 just makes slightly smaller files but using more CPU. It’s not a big difference either way.
q=10q=50q=90
Code details
WebP is good for smaller files that every browser can display, but WebP is staunchly an 8 bit format. I’m bummed, my Pixel is now outputting weirdo HDR JPGs that look nice. But it’s still a challenge to work with those, so I’m giving up on HDR for now. (I think the right answer is to resize to AVIF files but the open source tools for that are still difficult in HDR.
I’m using PIL to create the webp files. Saving it is as easy as img.save(fn, 'WEBP', quality=50, method=6). The trick was getting a version of PIL with webp support. uv is compiling my own wheel, I think, which may be part of my problem. Anyway adding config-setting = { pillow = ["webp=enable"] } to pyproject.toml fixed it.
AI programming notes
I feel increasingly weird writing these work notes to myself. Everything done up above was done with coding agents, I’m not sure I learned much myself. But I spent a bunch of time tinkering to get there. Jules/Gemini had the wrong idea how to fix PIL the first time. I didn’t trust its own judgement about what quality level to use, I had to determine for myself.
I did a lot of work 4 years ago writing my linkblog generator and then haven’t had to touch the code. I did a good job! Unfortunately it is now time to migrate off of Pinboard to Linkding, so I needed to update the code that fetches my bookmarks to use the new site.
Dev Environment
My code uses shot-scraper and Playwright to generate screenshots and that explicitly does not support Fedora, has various Debian dependencies on it. (I didn’t like this hack-around). So I set up distrobox as a dev environment. Now when I want to develop I have to do this
distrobox enter linkblog-dev
cd ~/src/linkblog/pinboard-to-static/
source venv/bin/activate
./update.sh
It also helps to run a web server in the site-generated/ directory to see the output.
I don’t have VS.Code set up on the Fedora machine. Right now I’m using Kate, which is capable enough as a text editor. Note it has to run in the host OS, not inside the distrobox. (Files are bind mounted so there’s no container boundary problem.)
AI programming
Four years ago I wrote all my code by hand, of course. Now I want to use agent tools like Jules. This turned out to be pretty easy and I could just tell the agent to rewrite the Pinboard code for a new API. It read the Linkding docs and figured out most of it itself.
The problem is I didn’t structure this code for anyone else, even an agent, to run it. It depends on some secrets (not checked in) and access to a Tailscale server. Worse, it has no tests. Yes, I hang my head in shame, this project was done very sloppily. And without tests or the ability to even run it a key part of the agent development loop doesn’t work.
I yoloed this one change anyway and reviewed it carefully and it was fine. But I probably should adapt this code to be agent-friendly for further development. Test suites are a good idea for people too! But they are essential for an agent.
Going forward
I’m a little nervous about these code changes, particularly without testing. I’ll run it by hand for a few days and see how I feel.
I love swimming in the Yuba near Grass Valley. Local wisdom is it’s not safe to swim until July 4, that’s when it’s warm and slow enough to be safe. PG&E controls the flow with a dam but seems to follow a sort of schedule. My notes are that 200 CFS is “calm” flow. I was just there at 450 CFS and it was still pretty sporty. I could have swum across but it wasn’t yet a good idea.
There’s flow data at Dreamflows and USGS. Also historical data at USGS. So I fired up Claude Code and 30 minutes and $2 later I have a serviceable graph. It’s online here.
End result: yeah, July 4 is about right.
Update
For $0.50 I added a histogram of the flow on July 4. I also added a deploy script for 10 cents. Then I spent another 20 cents making sure it was treating no data differently from zero. There’s 61 years with flow under two hundred: 20 years with flow over that.
Vibe coding notes
Another project I could have done myself but didn’t want to spend the time: Claude makes it kind of fun. This went OK at first but got in the weeds.
Claude’s first instinct was to use Python and matplotlib. Yuck. I asked it to do Javascript and it chose Chart.js. Which was fine for small data but choking on more points, so it suggested switching to uPlot. That seems to get the job done. d3.js would be nice too but is overkill for a static one-off.
I am very impressed with how Claude understands high level directives like “draw a bunch of individual thin lines for each year to show distribution”. OTOH I don’t quite trust it: I’m afraid to publish this more widely for fear something about its calculations is incorrect. I tried reviewing the code but just can’t bring myself to care enough to bother. It looks right!
Claude is great when starting de novo but gets slower and buggier with iteration. For instance it mostly converted the code from Chart.js to uPlot just fine. But one thing I wanted was to clamp the Y axis at 2000 CFS. It insisted on keeping the Chart.JS code to do that and wouldn’t update to the uPlot API until I read the docs and told it myself what it needed to do. It also made a bunch of other changes that just didn’t work. I never could get it to make the graph fill the whole width. I know some folks doing agentic coding are also building test suites and telling the agent to not commit until the tests pass, that would have been really helpful here.
I sure wish I had more confidence that this visualization is actually correct and doesn’t do something stupid like averaging missing data in as if they were zeros. That’d be the same problem with a person doing the coding but I’d trust them more.
I usually develop on local disk, just git init and start programming. No push or pull, no remote repos. But sometimes I want to get fancy and have a remote repo. I don’t use GitHub or GitLab to host these projects, I just host them myself. But things have changed a bit in the intervening 12 years, here’s the new process.
### Clone existing code into a new bare repo
cd ~/gitrepos
git clone --bare ~/src/blog/static/flourish/ flourish
### Set up origin in the old existing code
cd ~/src/blog/static/flourish
git remote add origin example.com:~/gitrepos/flourish
git push --set-upstream origin main
### Verify things are working as expected
git remote -v
git branch -avv
One subtle thing there... The bare repo is created by cloning from local disk. But then I set the origin back in my working code via an SSH URL. Not strictly necessary in the case where both the bare repo and the working copy are on the same computer but the whole point here is to enable working copies on multiple machines from the same bare repo.
And an extra complication: I have Syncthing synchronizing my ~/src to my various Linux development environments. All behind the scenes, transparently. This can be a little spooky sometimes; if I git commit in one working copy there’s no need to git pull in another working copy because syncthing will sync for me. It’s harmless to git pull and git push in this configuration though, at least as long as I’m not making changes in two places at once.
I’m working on my blog engine. I want to package it nicely as a Python package. I also want to be able to run my code from a command line using the click library, and write and run tests using pytest, and be able to do all this with the debugger in VS.Code. I’ve never made my peace with Python packaging, for many many years now I’ve avoided it. Because it’s a mess.
Anyway I just tried again here in April 2024 and more or less succeeded in just an hour or so. This is where I would write clear docs with a github repo with the code but.. nah. I’m not confident it’s right and I don’t understand it well enough to present coherently. But I’ll write up what I learned.
I mostly followed the Packaging Python Projects tutorial which explains the creation of this sample project. Following that gets you a basic Python project which you can install with pip install -e. The key thing here is everything’s driven by the pyproject.toml file. If you are reading any docs that talk about setup.py they are old and outdated; the TOML is the new way.
Some subtleties in the pyproject.toml:
My project has dependencies that I specified in the TOML. It depends on pytest and click.
I had to pick a build backend; I’m using setuptools as the old non-fancy default.
My project has console scripts. You can specify these in entry points or in a scripts section.
Getting click working was not hard. There’s docs for click + setuptools. Note these are in terms of the old setup.py style but translating to pyproject.toml isn’t too hard.
Here’s my source tree for a toy package called “whir”
pyproject.toml in the root directory
Python code in sys/whir/.
src/whir/__init__.py that imports all the public functions, particularly the click commands.
src/whir/lib.py is simple library code that other stuff imports.
src/whir/main.py contains a main_cli() function that’s a click command. __init__.py imports it so it can be used as a script in pyproject.toml. It also imports the lib code via import whir.lib, not a relative import.
tests/test_lib is a pytest function that tests the lib code. It imports it with from whir import lib.
Getting pytest working was not hard either. The default setup worked just fine from a shell. Getting it to work inside VS.Code’s extension for it required adding something to pyproject.toml to get pytest to use importlib, as described here. But now I can just press a button the IDE GUI and all my tests run with a nice display. Yay!
Getting the VS.Code debugger to work with click was tricky. AFAICT there’s no easy way to get VS.Code to invoke a click command. But there’s a hack where you call the click command with string command line arguments inside a if __name__ == '__main__'; then VS.Code can be used to just debug the file and it will work.
Edit: thanks to Claude I’ve now found two more ways to invoke a click command from a function. The intended way to just invoke it is to use main_cli().callback(args): the click decorator adds a callback function to the command function you can use. There’s also a whole library for testing invocation of Click commands, CliRunner, that will mimic a command line call. It sets up a special environment that captures stdout and stderr, can mock up a filesystem, etc. It’s for using in a unit test framework.
Ranting reflection
It all worked pretty straightforwardly! But I have no idea at all how it works. If something goes wrong I won’t understand what is happening or how to fi x it. And the tools are creating little files and shims that get between me and my code. It’s always like this with packaging and build systems and I hate it.
About a week ago I took over the service Feditrends, a link aggregator that shows trending stories on the Fediverse and Bluesky. The project creator (Jackson Palmer) had gotten tired of running it and shut it down a couple of times. I visit it every day so I took it over.
I have no immediate plans to change anything, I want to get some familiarity with what it’s doing and how it’s used first. Personally I use it partly to find interesting links and partly to keep tabs on what the Fediverse is talking about. The current dataset tends towards US news stories. I mostly avoid the mainstream news cycle but I like seeing what folks are talking about.
Taking it over
Taking it over was quite simple. Jackson did a great job releasing the code as open source. I got it running in about 15 minutes of work. It’s very simple, just a few hundred lines of Python code to fetch feeds and generate static HTML. It stores some stuff in a sqlite database. I haven’t looked closely.
Once I had it running locally and pushing to a web server of my own, Jackson just transferred the Namecheap domain name to me. I changed the DNS record and that was that. He also transferred the GitHub organization and the Mastodon account.
Observations
It all seems to run fine on its own. It does not have a lot of users. Feedly reports 22 subscribers, but of course that’s only a small fraction. The whole server is getting only a few thousand requests a day. About 30% of that is for the RSS feed for the main site, another 22% accessing the main HTML page. Maybe 1% of the requests are for the second experimental Bluesky product. I may remove that since I don’t use it and it’s completely separate code.
Feditrends now is pretty much entirely news links. That’s because its data source is Mastodon’s trending links (for example) on about 10 of the biggest English language Mastodon services. Mastodon.social is quite clear these are “News”. I’m not certain but I’ve been told these links are hand-curated, that a moderator has to approve a link to be valid for showing up there. Update: a friend says that the publishers have to be approved but not the links themselves. Also points to the Mastodon code for links.
Earlier versions of Feditrends used to have three tabs: News, Posts, and Hashtags. I’m not quite sure why Jackson narrowed down to just News but I can think of several reasons the other views could be harder to make work well. The code for posts is on GitHub.
Plans
The site could use an About page. With a last updated slug in it.
I never used the RSS feed before. It’s quite noisy, Feedly says it’s like 500 articles per week. I’ve gotten a suggestion to have a feed with fewer links, the Top 10 instead of all trending or something.
I really miss belong.io, Andy Baio’s old trending links service. That worked by watching Twitter accounts of a carefully selected list of 1000+ people for trending links. It’s possible a similar idea would work for the Fediverse but there’s various cultural forces at work that make me wonder if it really would. I should look at the “Trending Posts” data at Mastodon instances again to see if it’s interesting. Or consider my own curated set of accounts to track.
There’s some tinkering I could do to make the production a bit better. All my Proxmox work has paid off though, I got it up and running in an Ubuntu container on my server with simple backups, etc. I’m not sure what’s in the sqlite database and if it’s growing without bound. The static site publisher logs need some attention.
I should consolidate GitHub, right now I’m working in a fork.
I’d like to move the web serving off my own datacenter server and into some hosted solution. It’s so little traffic it’d be cheap or free on Github Pages or Netlify or just some sort of S3-like host or Cloudflare or something. Static sites are so easy to work with! The hard part is I’d like some basic access log info; I don’t want to add tracking Javascript just to get a rough count of visitors. I’m using GoAccess on the Apache logs for now.
Following up on a post 7 years ago, there now seems to be a consensus for a hash / checksum algorithm that’s not cryptographic. xxhash. Some variants are literally faster than memcpy, which is quite a trick. (I assume it’s the SIMD instructions).
xxhash has a bunch of implementations, I’m using the Ubuntu version. It comes in four flavors: 32, 64, 128 bit, and an alternative 64 bit (H3) that’s the fastest. Oddly the 128 version is the fastest of the first three, then the 64 bit.
This reimplementation blog post has some details on the algorithm. The speed comes from a parallel design meant for SIMD calculation. The actual checksumming boils down to rotate(state + (data * prime2)) * prime1. I’m a little surprised it’s a multiply and not a shift and xor or something but I know nothing about modern CPU speed.
I did a very simplistic benchmark: time dd if=/dev/zero bs=1024k count=1024 | xxhsum -H3 and took the best time of several runs.
no hash (send to /dev/null): 30ms
H0: 245ms
H1: 222ms
H2: 224ms
H3: 224ms
md5sum: 1250ms
Safe to say xxhash in any of its forms is so fast that I/O speeds and overhead dominate the CPU for the calculation. No wonder people embed this thing in filesystems, etc. It has very little cost.
I put my own Twitter archive online, hosted here with individual tweet URLs like here. The “server” is all static HTML but the list of tweets is an infinite scroll thing. Oct 2006 to Nov 2022.
I made this with Julia Evans setup, itself based on Darius Kazemi’s tool. Darius’ program generates its own HTML view but it’s got an idiosyncratic presentation. Julia’s code takes the tweet data (from searchDocuments.js) and the media files and constructs a new HTML archive borrowed broadly from Nitter’s UI. The Vue-based infinite scrolling wouldn’t be my first choice for an archive but it works fine and only took a half hour to set up. The main thing I miss is thread nesting.
I mostly just followed Julia’s instructions, getting something basically working is very easy. The scripts aren’t a polished product but if you are comfortable hacking a little code it’s not hard to get working. I’m glad she shared them! Some details:
Here are the specific edits to the code to customize my archive:
app.js: Replace two instances of b0rk with nelson
index.html: Replace four instances of “julia” or her full name with mine. Replace two instances of “b0rk” with “nelson”.
build.py: 5 instances of “b0rk” for “nelson”. 4 instances of “julia” for “Nelson”. (this page includes HTML similar to index.html).
profile.jpg: replaced with my own image
Deployed by rsyncing the entire github package, Julia’s scripts write stuff in that directory. Then on the web server I deleted things that weren’t necessary for the static HTML: .git, scripts,
The other thing I did was write a script to filter my tweets by date. I decided to cut off the archive at Nov 3 2022, the stuff I posted afterwards is all not something I care to preserve, just bearing witness to Elon Musk’s destruction of the company and product.
#!/usr/bin/python
import json, pytz
from datetime import datetime
cutoff_dt = datetime(2022, 11, 4, tzinfo=pytz.UTC)
def cutoff(item):
created_at = item["created_at"]
dt = datetime.strptime(created_at, "%a %b %d %H:%M:%S %z %Y")
# print(dt, dt >= cutoff_dt, cutoff_dt)
if dt >= cutoff_dt:
return True
else:
return False
jsonp_header = 'const searchDocuments = '
data = open("searchDocuments.orig").read()
data = data[len(jsonp_header):]
tweets = json.loads(data)
filtered = tuple(t for t in tweets if not cutoff(t))
print(f'{len(tweets)} tweets in archive, {len(filtered)} passed filter')
with open('searchDocuments.js', 'w') as fp:
fp.write(jsonp_header)
json.dump(filtered, fp, separators=(',', ':'))
Working on my new blog engine. I want to have “typographical quotes”, ie: “smart quotes”. Nice curly things that look like typesetting, not straight ’ or ” from some old typewriter. I am most interested in American English’s use of double quotes (open and close) and the apostrophe character we use in the middle of a word for contractions and plurals.
Annoyed I have to do this in my HTML; browsers could do a better job here, applying English curly quote rules to text input that looks like straight quotes.
Side note: testing all this was hard because something in Windows, PowerToys, or Windows Terminal is converting stuff I copy and paste. I can have a U+2019 in my terminal window from cat or from a web page and then when I paste it it turns into a U+0022. It was doing this with HTML entities I copied too. So I’m doing cut -c x..y | od -t x1 and dealing with cut not supporting UTF-8.
Side note 2: blogging about all this is impossible. The Wordpress editor is rewriting stuff I type, replacing various crafted markup examples with literal quote glyphs.
Unicode
Unicode double quotes are easy. U+201C and U+201D. Right name, right character category, done. Single quotes used for quoting are also easy: U+2018 and U+2019.
Unicode apostrophe is a mess. The ASCII U+0027 APOSTROPHE is what I type, and has the right name and categorization (“Other Punctuation”). But it looks wrong in most renderings, straight up and down and not curly. It’s kept that way for historical reasons.
U+2019 RIGHT SINGLE QUOTATION MARK is what most people use to get a curly apostrophe-looking thing. It works most places and is labelled in Unicode as “FINAL PUNCTUATION”. Which is half correct; it is punctuation. But also half wrong: apostrophe is not final. Also the Unicode character is actually a quote mark, not an apostrophe at all.
Some folks argue U+02BC MODIFIER LETTER APOSTROPHE is the right thing. But that’s the obscure choice. Also it has category “Modifier Letter” because it’s usually used as a letter, not punctuation.
I think U+2019 is the practical choice, ’, because that’s what most people do already. I assume it’s too late for Unicode to fix this by adding a proper apostrophe. The pedants probably think U+0027 is sufficient.
HTML
The most straightforward thing is just to embed the Unicode in UTF-8. That should be fine in 2023.
The older thing most people do is use Unicode entities so the output is ASCII with HTML encoding. For some reason those tend to be decimal, so you get ’ for apostrophe and “ and ” for double quotes. (Hilarious; I’d typed the entities for 8220, 8221, and 8217 in my Wordpress editor. When I came back what I typed was replaced by the actual glyphs.)
The W3C has a page from 2015 with different advice. It suggests named entities, using “ and ” for double quotes, and ’ for apostrophe. There are also ' and " entities which presumably are to be avoided.
Automatic conversion and Markdown
I’m lazy and want to type ASCII straight ’ or ” and have software convert them to proper quotes. “Smart Quotes”. It’s important to do this in a way that’s aware of HTML markup; you don’t want to be replacing ” in URLs, code fragments, etc.
The CommonMark spec doesn’t seem to say anything about typographer’s quotes. All their test cases replace ASCII ” with HTML entity " but I’m not clear why, or if the spec demands it. Some sort of escaping safety thing I guess? It’s awkward IMHO. This discussion says the reference implementation does some smart quotes but it’s not part of the spec.
In the ancient days we used “SmartyPants” to do a typographic conversion for us. There’s a modernish Python implementation that seems to work. It uses 8217, 8220, and 8221. Good enough for me! But it’s awkward to plug in to other markdown frameworks, in particular smartypants is re-parsing the input and it’d be nice to skip that.
Despite that mistletoe + smartypants works fine.
mistune and marko do not work with smartypants. Both seem to be converting ” into " like CommonMark’s demo tool does and smartypants won’t pick that up and replace them with 8220/8221.
The old pre-CommonMark Python markdown library has an extension called “SmartyPants”. It seems to be emitting named entities like “. It doesn’t do apostrophes?
The Markdown-it-py extension has typographic components for quotes and apostrophes. This seems to work well and as a bonus emits actual UTF-8 for the Unicode themselves, not ASCII escapes. I’m not afraid of UTF-8. That may be enough to get me to use Markdown-it-py!
cut is a very simple shell util; it will take a few characters or fields out of its input. cut -c 10-20 for instance should output characters 10-20 on every line.
Except hahahaha joke’s on you, despite being called --characters and there being a separate --bytes flag, they both actually operate on bytes. No matter what your locale is. This completely breaks UTF-8 input; it does not treat them as characters.
This behavior is not disclosed in the cut --help docs, nor in man cut on my Ubuntu system. It is documented in info cut, the obsolete doc tool rms failed to foist on the world 25+ years ago. There it says:
Select for printing only the characters in positions listed in CHARACTER-LIST. The same as ‘-b’ for now, but internationalization will change that.
There’s a good Stack answer from 2014 explaining all this. I even understand why the GNU tool does this, it’s as much POSIX’ fault as GNU’s. But you’d think in the intervening 9 years they could at least improve the docs.
Here’s a 2006 bug report documenting the same problem. I would not be surprised if the bug goes back to the 90s, predating the adoption of UTF-8 everywhere.
Pressing reload in a browser while developing a web page is for chumps! A very popular trick is to serve the site under development with a special server and put a little Javascript in the page to get a reload signal when it should reload. Saves a lot of time, I love live previews.
five-server is the most mature tool for this I could find. It’s written in Node but you can run it as a standalone server unconnected to the code you’re developing. This is a fork of an older live-server that was abandoned. There’s a VS.Code version too that has some integration that looks useful if you’re editing HTML files.
LiveReload is a Python server to do the same thing. It has a Python API so you can integrate it with your own Python code to help while developing a webapp. I hit a confusing problem because of less-than-robust error handling related to my malformed HTML input (the script injection failed) but it seems to work well.
There must be a zillion other tools that do the same thing.
I’m mad enough about Hugo I spent an hour writing a very minimal blog engine. Lots to go to make it usable, but as a piece of it I had to look for a Markdown processor for Python. Here’s what I’ve found, there are probably more. I want something that supports CommonMark and has a decent extension story. (A lot of folks support GitHub flavored markdown, perhaps that’s coherent enough to also be reasonable.)
mistletoe. 652 GitHub stars. I’ve used this already and it works but haven’t gotten in deep. Docs and PyPI niceties are not great. Says it’s the fastest implementation but all of these are pretty close (except Mistune which is way faster). Supports rendering to other targets like LaTeX, not just HTML.
markdown-it-py. 517 GitHub stars. Looks comprehensive, has a bunch of plugins. It’s a port from NodeJS code. Plugin code looks pretty complicated.
mdformat. 263 stars. Has plugins and code is connected somehow to markdown-it.
marko. 249 stars. Says it has very easy plugins and is not very fast but correct.
No real conclusion here. I’ll stick with mistletoe since I already have it working, then look to jump when I get to the part where I need my own plugins. marko or Mistune look most promising to me if mistletoe won’t work.
Update: some very simple evaluation
I did some quick tests comparing mistletoe, marko, markdown_it, and Mistune.
The output of all three were substantially similar. mistletoe emits actual ” ASCII quotes whereas the other two are outputing ". Which reminds me I need to enable typographic quotes.
Some very simple benchmarks show mistletoe and markdown_it takes 2-3x as long as mistune, marko is about 4x. timeit 9000 byte input: mistune (1.13ms), markdown_it (2.78ms), mistletoe (3.60ms), marko (4.84ms) 1800 HTML posts: mistune (490ms), mistletoe (860ms), markdown_it (925ms), marko (2000ms)
Update 2: markdown_it
After reading docs and setting up typographical quotes I think I’ll go with markdown_it. I was turned off at first because it was a NodeJS port and its code seems quite complicated, they really want to explore details of parsers, ASTs, renderers to you. But it does typographical quotes right! And it’s fast and popular. Now that I’m over the learning hump it seems a good choice. I haven’t tried writing a plugin for it yet though.
I’m once again trying to port my ancient Blosxom blog to a static engine. Focusing on Hugo this time. I no longer care which engine I use, just want to use one, and the most popular one is probably a good choice. I am adamant that I have to write my own theme, collection of templates and layouts and stuff. I want complete control over site layout and page contents.
Most tutorials are toys that never talk about pagination. Many have a default home page of “all your posts”. This seems to be for crummy marketing sites with 3 pieces of content and are not useful for a real blog with 1000+ posts. Pagination is a whole complex topic I don’t understand yet.
A lightbulb went off when I looked at this classless-blog Hugo theme. It has no Javascript. It produces really simple semantic HTML with no CSS classes, just clean tags like <header> or <main>. You can then change how the page looks with pure CSS, perhaps starting with one of these classless CSS resets. That is the One True Way to web development, IMHO, at least for simple static textual content. I’m glad to see a clear path to doing it in Hugo. (Seriously, people are stuffing React into Hugo blogs? Ugh.) Unfortunately the classless-blog theme isn’t really suitable for me to just use (it doesn’t have the right structure for me) but I can steal a lot of ideas from it.
As for writing my own theme, I’m finding this tutorial really helpful. It’s from 2020, so a little out of date, but mostly good.
The tutorial neglects to mention at the start that you have to set the theme= in your configuration TOML. That file recently got renamed from config.toml to hugo.toml. Fun fact; if you don’t set that variable, Hugo throws an opaque error message.
WARN found no layout file for “html” for kind “home”: You should create a template file which matches Hugo Layouts Lookup Rules for this combination.
What that error really means is “theme not found so you have no layouts at all for your blog”. It’d sure be nice if the tool caught this simple beginner’s error.
Hugo themes are programmed in Go template languages. Last time I encountered this I got mad but I read the excellent Go docs and now understand it’s pretty simple with just a few control flow items. The weird thing is some syntax like {{if}} are genuine control flow things, others like {{printf}} are more like function calls. Also there’s a {{define}} which creates new functions. The confusing part about Hugo templates is the implicit context hidden in . the cursor and how {{range}} is a looping construct. Also it’s still not clear how often templates are invoked. But...
Hugo has a concept of “Kinds”. These are the various sorts of pages that Hugo will create as it runs and it’s a little confusing and poorly documented. The docs here for .Kind are the most explicit I could find.
The page’s kind. Possible return values are page, home, section, taxonomy, or term. Note that there are also RSS, sitemap, robotsTXT, and 404 kinds, but these are only available during the rendering of each of these respective page’s kind and therefore not available in any of the Pages collections.
Each of these kinds is in turn instantiated by a template file. Hugo will look in many places for the template for a kind, with up to 46(!) different paths. The template lookup order docs are essential for understanding this.
It’d be nice if Hugo had a debug mode which printed every HTML page it created, why (what kind maybe?), and every template that was used to create that. That’d really help understanding what the generator is actually doing. I did find hugo --printUnusedTemplates useful for at least finding when template files weren’t being used.
I just upgraded from Ubuntu 22.10 to 23.04. Which means I upgraded from Python 3.10 to 3.11. Which means all my old Python programs don’t work anymore. Because each has a virtual environment and the venv is hardcoded to Python 3.10.
Am I doing it wrong? Yes, I was doing it wrong.
In the old days I’d create a venv with a command like python3.10 -m venv venv. This results in a venv/bin directory where python3 is a symlink to python3.10 in the same directory, which in turn is a symlink to /usr/bin/python3.10 (which no longer exists).
Awhile back I changed to running python3 -m venv venv. This results in all the binaries in venv/bin being symlinks to python3, which in turn is a symlink to /usr/bin/python3. That should be robust to upgrades. And Python is good about backward compatibility so using 3.11 to run a venv built for 3.10 should mostly be fine.
FWIW the docs just have you invoking python on the command line, so I guess that’s what the intended usage was. More generally it looks like venv is doing its best to set up an environment with the exact same Python pathname you used to create the environment, which seems reasonable enough.
I’ve seen some folks talking about setting up a new linkblog so I thought this would be a good time to document how my linkblog works. I’ve run this publication over nearly 20 years and am pretty happy with the current iteration. See also previous detailed posts.
Summary: I post links to pinboard. A cron job on my own server downloads the pinboard data to sqlite and renders static HTML, RSS/Atom, and Mastodon posts from it. There’s also some code for generating screenshots of the linked pages.
Simpler alternative
There’s no need for custom code or your own server. You can run a simple linkblog just using Pinboard or Raindrop. Those sites offer both an HTML view and a very functional RSS feed. There’s a bunch of services that will mirror RSS to social media like Mastodon; IFTTT, maybe Zapier. That’s how I ran my linkblog for many years.
My data model
My linkblog is a collection of posts. Each post has six elements:
URL of the page I’m linking
Short description
Extended description
Tags (including a +/- sentiment tag)
Date I made the post
Hash of the post
This is basically Pinboard’s schema, not an accident!
One thing I don’t have for each of my posts is a URL for my post itself. There’s no way to link to one linkblog post of mine. My RSS feed’s links don’t go to my own linkblog; they go directly to the page I’m linking. I think this is the defining feature of what a linkblog is but not everyone who linkblogs agrees. I have some detailed notes on what other linkblogs do.
The hash is a little strange; it’s something Pinboard generates, a 32 character string. I use it in places where I need something unique for each link I blogged like the ID for each Atom feed entry or the URL for an image preview.
Posting a new link
When I want to post a new link I use the Pinboard Plus extension in my browser. Really any way to create a Pinboard post would work, this one is just convenient for me. The posting UI looks like this:
Publishing new posts
I have a cron job on a personal server that polls Pinboard every 5 minutes checking for a new post. When it finds one it does a series of things:
Add the post to a local sqlite mirror of Pinboard data
Create image previews for the new link
Render static HTML and Atom feeds for the whole linkblog
A side / optional feature, an image for each link I post. It boils down to using Metascraper to look for a suitable image unfurl or else shot-scraper for a screenshot. Here’s some detailed notes on page previews.
HTML and Atom rendering
Most of the code I wrote is for rending my linkblog to HTML and Atom feeds. It’s pretty straightforward though. It should be possible to use a static blog generator like Hugo instead but I wanted complete control so I rolled my own. I don’t worry too much about the HTML page functionality, I expect most people read my linkblog via a feed reader or else social media.
Social Media posting
New posts go to social media, these days that’s Mastodon (it used to be Twitter.) This process is driven entirely from the Atom feed, not from my rendering code or sqlite mirror. Currently I’m running feed2toot on my server to do the posts, it works fine. A service like Zapier or IFTTT would work too and be one less thing I have to manage myself.
Thoughts
I set up this new architecture last year and have been very happy with how robust it is. Cron jobs and static publication are a great way to build things like this. I do regret running my own server for the rendering piece but I wanted to experiment with something custom to me, so it was effort well spent. Fortunately it seems to be running by itself with little work for the last year.
I think an existing bookmarking service could run a whole linkblog. I haven’t tried it but Raindrop.io looks to have all the important components: image previews, feeds, and a nice public page for an HTML view. It’d come down to details and whether they center links to raindrop.io itself or the destination site that was linked.
More work on my little Javascript hack. Unlike that first video this system is actually working correctly. Some examples of other rules; Ising model not depicted.
I took a quick look at Astro, a newish open source framework for building (mostly) static websites. It looks pretty nice but may not be what I want for my current project, (once again) trying to replace my ancient dynamic blog engine with a modern static site.
The big thing Astro seems to enable is Javascript-heavy static sites. If you want to use React, Vue, Svelte, etc to build a complex Javascript site, but you want everything statically pre-rendered, Astro looks to be your choice. There’s a lot of fancy support for dealing with Javascript, CSS, fonts, etc and getting them to assemble to a nice static page for the client. Also integration with GitHub (for code hosting) and Netlify (for site hosting). I think that’s an interesting spot to be in for a framework in 2023. (Also kind of the opposite of another paradigm I think is interesting, very lightweight Javascript and using HTMX to bridge to a dynamic server.)
One minor annoyance: even the very first empty template project loads about 5kb of client side Javascript. It doesn’t seem to be doing anything and I think can be removed. But it says something to me that even the null project already has client side Javascript; this is a tool intended for Javascript sites.
What Astro doesn’t have out of the box is a blog engine. They have a great tutorial that has you create a blog, very nicely written and easy to follow. But along the way you’re writing code like “enumerate all the markdown files for the posts then use that to build an index of my blog posts”. Ie, you’re coding your own blog layout. That’s fine as an example of building your own static site. But I’m just trying to set up a blog, I’d rather have that stuff built in already.
Maybe that stuff does exist. Astro has a bunch of blog themes, perhaps Astro + an off the shelf theme is what I’m looking for. So I gave Blogster minimal a try. It’s kinda nice and has zero Javascript in the built output, a goal I want. But this looks more like another demo of how to build a blog. In particular there’s no easy way to extend this code short of forking the github project and building your own. Which is fine, but more like programming Javascript and less like customizing some static HTML templates. That’s great if you want to really customize but is work I’m hoping to avoid.
I’m left with the impression Astro is a good choice if you are expecting to write a lot of code to build something unique and custom.
I’m writing a little browser toy where I calculate a model in the background and render it frequently. Think something like an animated cellular automaton.
Rendering is easy in modern browsers: you just use requestAnimationFrame and hopefully it’ll call your code once per screen refresh or at least as fast as it can manage.
But how do you do background compute work in Javascript in 2023? I want it to run as fast as possible (ie, 100% CPU for the browser tab) but still be smooth and responsive. I think the right answer is “web workers” but then that requires the overhead of passing the calculations back and forth via messages (and JSON serialization?!).
Here’s some other things I tried for background Javascript work. I tested using a calculate function which executes in well under 1ms.
Use setInterval to fire off the calculation: 4ms is the minimum allowed in modern browsers, limiting you to 250 calculations / second.
Use a spin loop. This works and I can do but now the main browser thread is blocking everything and it’s a UI disaster. Not feasible.
Use a spin loop with a Promise to yield via a short sleep. Still subject to 4ms on setTimeout, but overhead means it’s more like 5.2ms in practice.
Use requestIdleCallback. I had high hopes for this but in practice I’m getting called every 11.1ms or 90 updates / second. Turns out that’s my screen refresh rate and the idle callback rate changes if I update the display driver refresh. It’s like VBlank interrupts in 2023 only about nineteen layers removed from the hardware.
I think in practice setInterval will work for me; my calculations are likely to take a few milliseconds and anyway I don’t want it to run “too fast” because it won’t be visible. Still kinda wacky this is so hard in 2023. Web workers are probably the right way if I need faster than 4ms.
// Calculation loop using idle callbacks
function calculate_idle() {
calculate();
window.requestIdleCallback(calculate_idle);
}
// Calculation loop using ersatz sleeps. Note 4ms is minimum here.
async function calculate_sleep(interval) {
// https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
while (1) {
calculate();
await new Promise(r => setTimeout(r, interval));
}
}
switch (mode) {
case "idle":
// Seems to be every 11ms per quick testing in Chrome
calculate_idle();
break;
case "interval":
// Browsers seem to make 4ms the minimum interval
setInterval(calculate, 1);
break;
case "spin":
while (1) {
calculate();
}
break;
case "sleep":
calculate_sleep(0);
break;
}
Thought I’d give Datasette a quick try. I was curious about which countries were the most and least diverse. Seemed like a good simple use case for the data exploration tool. This is my first time really using it. I am trying to use higher level tools rather than write low level code that works exactly like I want. Here’s what I did. An hour or two of tinkering and learning here, maybe a little more.
Manually edited the CSVs to change the column headings to simpler things without whitespace.
Installed datasette, sqlite-utils, and csvs-to-sqlite via pip.
Ran csvs-to-sqlite *.csv diversity.db to make a database.
Merged the two tables into one by using sqlite to run create table combined as select * from diversity left join population on diversity.Country = population.Country;
Removed an extra copy of the country name with sqlite-utils transform *db combined --drop 'Country:1';
Converted the population column from string to text with this code:
And with that now I have a nice little web GUI. I used it to make a report of the diversity of large European countries. Which immediately yields a lot of questions about exactly how we’re defining diversity, but that’s not Datasette’s fault.
Thoughts
Datasette is cool, a nice generic HTML front end to tabular data.
Preparing data was more fiddly than I liked. I felt like Datasette and related tools wasn’t doing a lot of work for me I couldn’t just do in sqlite. For instance, I was hoping for a GUI in datasette for doing the join between the two sources tables. It will let you do the Datasette slice-and-dice on top of any sql, so you can have an ephemeral table where you write the join yourself, but I wanted a persistent table for convenience.
The management of the population column types seemed awfully awkward. My input CSV had quoted text-looking columns for the numbers like "233,319". The code uses pandas to import CSV files, which I thought was smart enough to parse those as numbers. Maybe there’s a way to get csvs-to-sqlite to import them that way. It’d be nice if sqlite-utils convert inspected the Python type and changed the column automatically. (There’s a -transform option but I think it only works if you create a new column.)
I was hoping for some way to do a chloropleth of the diversity measures, but no one’s written that plugin. Would be easy enough to export a CSV and use some other service to visualize. There are some map visualization plugins for Datasette but they seem oriented to working with lat/lon pairs, not country names.
It’s really cool how easy it’d be to publish this little set of data to some cloud service.
I’m surprised the integer columns don’t have separators in their display! “144713314” is hard to read. This would be an easy plugin I imagine.
create temporary table stats as select year, month, count(year) as count from (select strftime("%Y", ts, "unixepoch") as year, strftime("%m", ts, "unixepoch") as month from links) group by year, month;
Some notes on how to use the zstandard compression system for files as a replacement for gzip. I spent a lot of time looking for subtle but important differences but really zstadnard is quite easy. zstandard files are named “.zst” instead of “.gz” and there are command line tools that are mostly equivalents for gzip.
gzip -> zstd --rm
gunzip -> unzstd
zcat -> zstdcat
tar czf -> tar --zstd -cf
tar xzf -> tar xaf
pigz -> zstdmt
Why use zstandard? Because it is much faster and smaller. I’ve used gzip for years and years to compress files. (I am old enough to have used BSD compress and have the .Z files to prove it.) I briefly used bzip2 but it just took way too long to compress to be worth it. I also use pigz when I remember too, the parallel gzip, and that is a lot better. But, eh, what about the new hotness?
zstandard seems mostly to be an algorithm product. the zstd(1) command line tool is pretty good though and is thoughtfully documented. It mostly does the things you want with files, preserving timestamps and permissions and such. he one important difference is that zstd does not remove the original uncompressed source file, unlike gzip. There’s a --rm option to zstd if you want that behavior.
The default compression level of 3 is fine. I assume it’s the default for a reason. Higher levels get slower very rapidly for not a huge advantage. Using the 100MB Wikipedia corpus from this benchmark the highest normal level 19 makes a file that’s 25% smaller but takes 100 times as long. Some quickie data:
Algorithm
Compression ratio
Compression speed
source
1
0
zstd -3
2.809
201 MB/s
zstd -9
3.710
1.92 MB/s
gzip
2.739
25 MB/s
gzip -9
2.744
19 MB/s
bzip2
3.447
16 M B/s
zstdmt or pzstd for parallelism. Much like pigz, it’s possible to compress with zstandard in parallel. pigz compresses my test data in 9% of the time of single threaded gzip; 11x speedup for a 16 thread Ryzon 3700. Both pzstd and zstdmt take 20% of the time of single thread zstandard. Not sure why it’s not better than that, didn’t dive deep. zstdmt produces a file that’s identical to single threaded zstd. pzstd makes a very slightly bigger file; I’m guessing it’s doing a block approach like pigz does.
Recovery from corruption may be a weak point for zstandard. One nice thing about gzip is that it compresses in chunks. If one byte is corrupted in a gzip you don’t lose the whole file, you can use gzrecover or gzrt and maybe get most of your data back. (This chunking is also how pigz parallelizes). I’ve actually done this for real once and was grateful to get most of my tarball back. I don’t think zstd(1) has any equivalent behavior by default, and this GitHub issue suggests the zstd team thinks it’s out of scope. There is block chunking via the -B flag (and probably pzstd) but in the absence of an open source recovery program I wouldn’t count on it.
I see no reason to not use zstandard everywhere instead of gzip. Except habit, and I suspect in reality I won’t change my behavior unless it’s something where it really matters.
Node seems to have some serious stability problems; various apps are sensitive to which version of Node you run. Here’s some recent versions:
Ubuntu 22.10 / kinetic: 18.7.0
22.04 / jammy: 12.22.9
20.04 / focal: 10.19.0
Nodesource packages different versions of NodeJS for Ubuntu. It’s basically a PPA but they want you to use their shell script to install them.
I ran into a problem with Nodesource where “apt install” really wanted to keep installing Ubuntu’s 18.7 despite having a PPA. I fixed that with apt install nodejs=14.21.1-deb-1nodesource1 to select a specific version.
I want an ActivityPub server so I can do Fediverse experiments and see them in Mastodon. What I really want is something like CGI; I don’t care about the protocol server, I just want to write little scripts that easily federate. I don’t want a consumer product with a web UI, I want a little platform for which I can create experimental scripted accounts for people to subscribe to. I’m not sure that exists.
I asked on Mastodon about servers and got some suggestions. Here they are. Lines of code are rough estimated calculated with scc.
takahe. 9,000 lines of Python. Active, seems very new (2 months old), not yet at a 1.0 release. Seems web UI centric.
gotosocial. 58,000 lines of Go. Active, six months old, labelled “alpha”. Also focussed on a web UI and consumer product.
epicyon. 103,000 lines of Python. Active, 3.5 years old. Also web based but an emphasis on being simple. OTOH runs as a proxy server and needs nginx in front.
honk. 10,000 lines of Go, 3.5 years old. Not entirely active, but has had some recent updates. Seems.. idiosyncratic. But also nicely minimalist. Someone mentioned it has lots of forks.
minipub. 7200 lines of Typescript+Javascript. A year old, but no edits in 6 months, maybe one developer. “for posting federated podcast comments”.
minimal-activitypub, 650 lines of Python, 4 months old, one author. Found this one myself and as the name says, it’s minimal. May be a suitable start for the platform I want? I note from the docs that it’s all client to server stuff, not server to server, and I don’t even understand enough about ActivityPub to know exactly what that might mean. There’s a couple of the author’s projects built on top of it.
express-activitypub. 440 lines of Javascript, 4 years old, one author and seems largely moribund. OTOH it’s by the great Darius Kazemi, ActivityPubber extraordinaire, so it’s worth a look. Darius says his projects are live, just stable.
rss-to-activitypub. 700 lines of Javascript, 4 years old, also Darius and mostly moribund? But this specific RSS product is very close to what I want to tinker with, also worth revisiting.
snac2, 6000 lines of C. Two months old, active but maybe just one developer. Has a simple web interface. Mostly runs like an old school Unix daemon, this post talks about setup. The earlier snac was a prototype in 3800 lines of Python written in six weeks.
microblog.pub. 13,000 lines of Python. 5 months old (v2), active. Simple web UI. Single user, minimalist, blog-oriented. This looks promising as a starting point for me.
6 static files. 0 lines of code, just some static JSON. Not a real server but a nice demonstration of a very very simple ActivityPub participant. The writeup notes that you have to accept POST requests to handle people following you, so that takes a little code.
Playing with ActivityPub, tmcw’s article about writing his own very simple ActivityPub instance. Describes the complexity required.
Still working my way through learning ARM64; I can write loops now! I have my first “real” program, something which takes a 64 bit number and prints it out in hexadecimal. This got me interested in how the CPU is really running my code, which leads me to the perf tool in the Linux kernel. This is an strace or prof-like tool that monitors CPU performance counters, of which ARM64 has an awful lot.
Notes here are from a rank beginner; anyone who’s used perf before will not learn anything here.
I installed it on Raspberry Pi OS with apt install linux-perf. That installs perf_5.10 which you need to invoke with the version number; the perf shell script wrapper is trying to run perf-5.15 to match my kernel version.
Running perf as root also lets you see all the cycles the kernel used, which for my toy program is most of it. Presumably overhead setting up the process? The --all-user flag restricts to only show user time. Or alternately, don’t run as root.
Note the number of cycles it takes varies each time I run it. Why? Not sure, but I assume it has to do with some unpredictable interaction with other system activity and/or the way the process got created. But while cycles varies, instructions don’t. My program is deterministic.
$ for i in $(seq 1 5); do perf_5.10 stat ./ch4printword 2>&1 | grep cycles; done
1,288 cycles:u # 0.004 GHz
1,034 cycles:u # 0.004 GHz
1,376 cycles:u # 0.005 GHz
1,039 cycles:u # 0.004 GHz
957 cycles:u # 0.005 GHz
perf supports running a job a bunch of times and showing average and SD
perf by default is printing counters for events it thinks I care about. You can see all possible events with perf list. One chunk are performance counters from the armv8_cortex_a72 itself. There’s a lot of data here, like cache misses and bus access and stuff. I was interested in branch prediction, so
One small mystery; my program has 32-48 branch instructions executed. why is br_pred bigger than 48? Perhaps this has to do with speculative execution?
167 instructions in 1000ish cycles is not very good. I thought ARM was RISCy enough you could expect 1 instruction per cycle but in reality it’s way more complicated. The Cortex-A72 is a superscalar CPU with a 15 stage pipeline and can be running five instructions at once! But this is a very short program so maybe not the best test.
I did some quick tries with perf on CPU-bound jobs.
1.10 instructions / cycle: stress -c 1 -t 5:
0.94: zstd -19
0.44: zstd -3
0.89: gzip
Those last three are I/O intensive so probably not a great test.
This blog post on performance tuning demonstrates 2.053 instructions / cycle for matrix multiplication. It also says “In scientific code with a mix of integer and floating point operations, an IPC of 2 is a good starting goal.”
Learning all this reminds me how complex micro-optimization is. Particularly for C code; you’re having to not only predict what the CPU is doing but also what the C optimizer is capable of emitting. I’d naively thought programming in assembly would make it easier to get some highly optimized code for things but I’m quickly discovering it’s so complex you probably get better results letting a compiler do the real work.
Since I’m in the guts of assembly programming I’m curious about system call numbers in Linux. What’s weird is they differ depending on system architecture; exit is 93 on aarch 64 but 60 on x86_64. How does this work?
The usual source for getting system call numbers is /usr/include/sys/syscall.h. But trying to read that stuff is a twisty maze of nested includes and CPP magic (that path doesn’t even exist!) If you find your way to /usr/include/x86_64-linux-gnu/asm/unistd_64.h you’ll finally find a list but even then it’s not exactly authoritative. Those are the numbers C programs using the system calls are using.
The Linux kernel itself defines the system calls in the kernel in files named syscall*.tbl. There’s 20 right now. These are also extracted in handy table form on this web page which makes for a nice (if possibly outdated) reference. exit is 1, or 60, or 93, or 9437185, or... why are these all different?
This Stack Overflow question has a partial answer; the x86_64 numbers were rewritten in 2001 by aa to “optimize it at the cacheline usage level”. Talk about baking in implementation details for ancient hardware! But the numbers are arbitrary anyway and I doubt it’s harmful.
To complicate things further not every system call is implemented on every architecture. nice, for instance, is system call 34 on i386 but isn’t in x86_64; instead the more modern setpriority system call (141 or 154) is used. Presumably libc is papering over these differences for most programs.
I think system call numbers tend to be assigned in ascending order, so sorting by number gives you a little history of additions to the Linux kernel ABI.
So the reason I’m playing with Raspberry Pi stuff is I have a mind to learn ARM64 assembly, aarch64. And figured it’d be fun to do that with a native hardware experience. There’s no practical reason for this, just felt a desire to get back to my roots. (My first real programming was all 6502 assembly as a kid.)
So far I’ve been doing my little exercises in an aarch64 shell, either directly or using VS.Code remote development to ssh in. I like the idea of actual ARM hardware being in the mix. But cross compiling and emulating is reasonable too. And so easy!
To cross-assemble on an x86_64 host, all you need to do is
That will install as and ld and related tools for assembling and linking object code. There’s lots more packages for cross-compilers for C++, Go, Modula 2... apt search aarch64 gives you a list. (I once spent a month trying to get a gcc cross-compiler working.)
But here’s the real magic:
$ make hello
$ file hello
hello: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), statically linked, not stripped
$ arch
x86_64
$ ./hello
-bash: ./hello: cannot execute binary file: Exec format error
$ apt install qemu-user-static
$ ./hello
Hello World!
WTF? I’m running an aarch64 executable on my x86_64 system. That is some serious magic. For extra credit the x86_64 system is actually WSL, a virtualized Linux. Which probably doesn’t really matter but is kinda neat.
Half the magic is done with the binfmt-support package. That is a kernel module that tells Linux how to execute various binaries it doesn’t know about. It’s the same trick that makes .jar files directly executable. So that’s the part that’s intercepting the aarch64 binary to run it somehow.
QEMU is doing the actual running of the foreign binary. It’s a software emulator, not hardware emulation, so it is pretty straightforward to have it support a bunch of architectures. qemu-user-static just packages it up nicely. It looks to support 29 different architectures including s390, riscv64, even the good ol’ mipsel I cut my teeth on in college. The emulator binaries are pretty big, 3-4MB each and statically linked.
I didn’t read up much on the environment QEMU is providing; there’s lots to read. It’s definitely not a whole operating system in a persistent VM. It seems to translate syscall numbers though; my aarch64 program works even though it calls exit as syscall 93 when on x86_64 it’s 60. The docs says it translates signals and maps threads too.
Update: WSL isn’t completely seamless; after a reboot the QEMU stuff stops working because it relies on systemd to install stuff. You can run sudo update-binfmts --enable to fix it. There’s also a related problem where after installing the emulator WSL complains /proc/sys/fs/binfmt_misc/WSLInterop: No such file or directory; that is fixed on reboot.
I’m upgrading from Ubuntu 20.04 to 22.04 which means Python versions are changing. Ubuntu 20.04’s last version they distribute is Python 3.9. Ubuntu 22.04 starts with Python 3.10. My own code isn’t particularly version sensitive but venv makes it a mess. I’ve chosen to go ahead and move to Python 3.10 for everything.
My main problem is when you create a virtual environment it’s locked to a specific verison of Python. All venv is doing is installing stuff to venv/lib/python3.9 or whatever. If you created the venv in python3.9 and try to use it with python3.10, it will not work. So you have two choices: either rebuild the venv for the Python version you have, or install the Python version the venv was set up for.
Installing Python versions is very easy thanks to the deadsnakes PPA. They port older and newer versions of Python to older and newer Ubuntu. Their 3.10 build works just fine in Ubuntu 20.04.
The other problem is the venv needs to have been set up to invoke the right Python binary. If you create a venv with python -m venv venv, then the important symlink in venv/bin/ will be to /usr/bin/python. No version number. But the rest of the venv is version specific, so that’s really the wrong thing. The solution is to create the venv with python3.10 -m venv venv. That way the symlink for the binary is to /usr/bin/python3.10 which will work whatever a system’s default Python version is. Also pays to be careful with pip; I now invoke pip as python3.10 -m pip instead of relying on /usr/bin/pip or whatever.
Now that I have 18,363 screenshots of linkblog web pages, what can I do with them? My first thought was to make a giant zoomable collage but an experiment with the 960 most recent makes me think that would not be very interesting. (This image is 2688x1470; click to embiggen.)
Generated with ./magick montage -geometry 80x45+2+2 *.webp output.webp. (Fun fact; if you forget the output filename imagemagick will happily overwrite the last input file.)
I think the old screenshots could be interesting but not in this random jumbled display.
Doing all 18,000 images would result in a file about 19x bigger. 11 megabytes, and about 12000x6400 pixels big. That’s shrinking the screenshots down from 640x360 to 80x45; a full resolution file of all images would be 64x bigger, so 700MB and about 100,000 x 56,000.
I decided to roll my own feed for my linkblog, to put my nice images in with the text. (Pinboard’s RSS 1.0 feed has done me well many years!) This turns out to be surprisingly difficult and all tainted by the way RSS/Atom hasn’t really gotten any development in 5+ years.
So which; RSS or Atom? Ugh! Happily the answer in 2022 seems to be “literally no one cares”. So I’m going mostly with Atom for old times’ sake. But I ended up coding this with feedgen which can emit both RSS 2.0 and Atom. (RIP, RSS 1.0 and 0.91). There’s still a lot of work in actually creating the feed and populating all the complicated fields.
One thing I couldn’t find is a nice Atom preview tool to render what the feed might look like. In the old days I’d use a desktop feed reader or maybe my browser to do this but all I know about now is hosted apps like Feedly where it’s a little tricky to get it to reload as I iterate. Oh well.
Boy Atom sure is complicated. I was briefly involved in the creation of the Atom format but I am kind of horrified at what it is. Every single feed is supposed to have a “self link” pointing to itself. Feed entries can too, but it’s not necessary. Entries can have titles, contents, and summaries. Two dates per entry; published and updated. Etc etc. Not all of these are mandatory but sheesh. Also it’s all XML. Still better than RSS 2.0 though. It’s a shame JSON Feed hasn’t caught on although the last thing we need is yet another feed format.
Update: feed seems to work on my first try! Not sure I’ll promote it though, it’s not really better than the Pinboard feed. The thing I added was an <img> tag in the description with the preview. But both Feedly and Slack are providing preview images even without it, through their own preview systems, and the result is more or less the same. I’m not sure if they’re even using my image tag at all. For about 10% of my links it should allow for a screenshot from my own code for links where Slack/Feedly won’t show an image at all.
Update 2 My last post (ERCOT Dashboard) is a good test; there’s no OpenGraph-style preview image available but I got a good screenshot. Slack just shows no image (ignoring mine). Feedly shows my screenshot though!
For the past two days I’ve been taking web previews of all 25,000 links from my linkblog. Akamai seems to have blocked me in retaliation. Requests to Akamai-hosted services like www.justice.gov are giving me an old school unstyled 403 Forbidden.
I assume they think I’m a scraper of some sort. Which I am, but an awfully low key one. I’ve got a single thread downloading web pages one at a time, every 1-10 seconds. Surprised that triggers Akamai’s defenses. It’s not a huge deal for my current project, but I sure hope it goes away once I stop my survey because it’d be awfully annoying to be blocked from 10% of the Internet permanently.
A little curious how they even caught on to me. I imagine user agents; the only place I make an effort to pretend to be a desktop browser is when I download the actual image named in OpenGraph data. (Oddly this fixed a lot of problems; apparently I can download the HTML with some user agents but not the linked image?!)
I’ve got metascrape set up using undici as the HTTP client and it sends a user agent of undici.
shot-scraper’s default user-agent is Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/102.0.5005.40 Safari/537.36 which looks close to a legit desktop browser but not exactly. It’s possible to reconfigure what shot-scraper uses.
User agent is the dumbest sort of security; it’s trivially easy to spoof, so really you’re only blocking lazy well meaning people like me if you filter on it. But there’s much more aggressive forms of user agent detection. See curl-impersonate which tries to mimic desktop browsers’ SSL behavior to evade more hardcore detection.
Update: 24 hours later and still blocked. I’m mad about this now. If I’d been aggressively scraping one site repeatedly I’d understand. But some lightweight automated screenshotting of sites all over the Internet once every few seconds should not cause me to get blocked forever. I had to set up tinyproxy just to book a damn hotel. Ironically I can’t read Akamai’s own support notes on their bans, since they are all hosted on Akamai.
Update 2: the block slowly expired starting the morning of July 23, 3 days after my screenshotter tool stopped running. It wasn’t lifted all at once. justice.gov was the first site I noticed working again. Later tripadvisor.com. schwab.com took the longest and for all I know some Akamai sites are still blocking me. Schwab showed a really irritating failure mode; the main page loaded fine (hosted elsewhere?) but the login iframe was blocked. At least that showed an error; I also hit some sites where some invisible AJAX refused to load, invisibly.
After a week or two of tinkering (and more research) I’ve come up with a nice clean web page for my linkblog. Each post has its own box with an image preview. I’m pretty excited how it looks. Also reminded myself of a cardinal rule of design projects; get something that looks good and functional ASAP. It’s so motivating!
Here’s screenshots of design iterations (from newest to oldest).
It’s a pretty straightforward layout but there’s one clever thing I’m doing, highlighting positive sentiment posts (white) from negative (black). I like how I iterated from a simple vertical design to something with alternating left and right. It’s idiosyncratic but I think it’s interesting.
Code architecture
It’s all pretty simple. Custom built Python static site generator driven from Pinboard data making liberal use of external Unix tools for complicated things. Very basic hand coded HTML and CSS, no frameworks, no Javascript. Static sites for static data!
The main loop is to sync data from Pinboard once an hour into sqlite. Then run a process to generate image previews for new links. Finally render HTML from the data in sqlite and push to a web server.
I used my friend Dan’s PugSQL for database access in Python. Very nice little tool; you write actual SQL code with just the lightest sprinkling of metadata for variable names, then execute it in your Python code. It takes some of the hassle out of writing SQL in Python without doing anything too magic. Worked great for this project. I only have two tables in SQLite and a total of 7 SQL queries. One nice thing about sqlite is there’s less need to optimize; I’m happy to make several SQL calls to render one post rather than try to do some complicated join to minimize database round trips.
Previews
I’ve written several blog posts about preview generation and I’m glad for all the research I did. I settled on a single 320 pixel wide image for a preview, height up to 320 with a preferred height of 180. My code supports multiple engines for generating an image preview but in the end I’m only using two. Metascraper, a standalone program that analyzes HTML for OpenGraph tags, etc to select an image. And shot-scraper, a standalone program that takes screenshots with a headless browser. I also tried the linkpreview service and a Python library called webpreview but they were redundant with metascraper.
Multiple engines yields multiple candidate images. I pretty much always take the Metascraper image; it’s available for about 90% of the links. In a few hand-coded exceptions I’ll prefer the screenshot. (Metascraper offers crappy images for Hacker News posts and Wikipedia pages that don’t have featured images. Also sometimes it returns an SVG image which the rest of my code can’t handle.)
Overall I’d say 90% or more of my posts have good images. A few of the Metascraper images are turkeys. Some screenshots are marred by cookie popups, etc. One neat thing is that web pages that don’t screenshot well also tend to be the ones with thoughtful OpenGraph previews.
The preview images are downloaded or generated and resized to 640 wide with lossy cwebp. Major savings there, the results are maybe 10% the size compared to just serving the actual image. Screenshots average 27kb, metascrape’s website images averages 50kb with a few oddball much larger ones because I couldn’t resize the source image. (cwebp can’t deal with animated GIFs!)
Page size and performance
I’m going for a fairly maximalist presentation so I don’t care too much about page size. 100 links on a page makes for a 5MB download, almost entirely the image previews. Google’s PageSpeed Insights gives me a pass on “core web vitals” and an 85 on Performance, which isn’t awful. The main complaint is just that it’s a 5 megabyte page with 100 medium sized images on it. I could easily solve this by just including fewer links on the page 👿. Or maybe go to an infinite scrolling / load on demand design, but the extra complexity of that does not seem worth it to me.
The one performance thing I’m not happy with is the image reflow. I don’t set an explicit height for the images because I’m using CSS to calculate the height. I’m not cropping the images but relying on overflow: hidden to contain them to max-height 320px. This all looks good, is less work for me, and has the nice property that the full preview image is available if you click on it. But it does cause a lot of reflowing while the page loads. I should revisit this.
Update: Thanks to a hint from Thomas S I now am including the native file image size in the HTML img tags. Combined with CSS rules for max-width: 100% and height: auto and the browser does a nice job laying out the images before loading them. I also added loading: lazy to the image tags at his suggestion which is a big help. The new mystery is font loading; Firefox loads them after the visible images. But that’s a deep rabbit hole.
Responsive design
This is the first time I’ve coded a mobile-friendly view for a website with a responsive design. All by hand, no framework to help me. My design is intended for desktop use, I worked with an 800px wide frame as the core design element. 320px for images, about 440px for text, and some gutters. But I wanted it to look reasonable on a phone too. So I read a couple of MDN articles and figured out how to do responsive design. It’s simpler than I realized.
The first principle is that you need to set <meta name="viewport”>. Without it mobile browsers seem to go into some compatibility mode where they render the page for a screen that’s 960px wide and then shrink it to fit in the actual CSS pixels for the screen, often about half or a third the size. That’s why fonts are so tiny for non-mobile websites on phones! So you set the viewport to width=device-width and now the page will render at the phone’s native CSS width, typically around 400 CSS pixels. (Which is probably actually 800 or 1200 physical pixels thanks to high DPI.)
The second principle is just to design the site so the page looks good at various widths in a regular desktop browser. I originally hardcoded a rigid width: 800px in my main display element which looks terrible if you shrink the browser below that (it clips). Making a more flexible layout works better. I was a bit constrained because I really wanted the preview images to be fixed at 320px, but now the text could go anywhere from 440px to about 250px and still look good.
The third principle is media queries to define explicit CSS rules for different screen sizes. My main rule is if the screen is smaller than 800 pixels to render differently; switch to a single column layout (images below text), use smaller margins, etc. For smaller mobile size screens I knock the font size down a bit too, to make more text fit. I did the opposite of the recommended “mobile first design”; my default CSS rules are for wide desktop screens, then I have overrides for small mobile screens.
Firefox has a great “responsive design mode” that lets you simulate how your page looks on various real world phones. Big help.
Future work
I’m pretty happy with where this stands. But I’m sure I’ll tinker.
One future work idea is to do some sort of pagination / archive view. Right now I’m just showing the last 100 links, without even dates displayed. That’s fine, there’s an archive view on Pinboard. But maybe I’ll eventually do more on my static site. See notes above about infinite scrolling as a possibility, too.
The other thing to tweak is continue to get better previews. Metascraper could be improved. Also I realized I could use Feedly to generate previews for me; they have an API where I can pull their preview images. There’s diminishing returns for this kind of work.
Finally I have one unexplored design idea. Display each preview as a full-bleed image in the background of a box for the post. Then put my descriptive text on top of the preview image, using some combination of blur and shading and maybe text halos to make it readable. It’s a pretty aggressive design but I’ve seen stuff like that look good before and it’d be fun to try.
I just spent about an hour learning about converting images to WebP. For my linkblog; I want my link previews to be small files. Target display is 320x180ish images.
Here’s where I landed to resize everything to 640 pixels wide with a fairly high quality:
cwebp -quiet
-af -q 90
-resize 640 0
-metadata all
These are guesses but seem to work about right.
-af -q 90 are the quality settings. 90 is fairly high, the default is 75. af means “spend more time making it look good”, it seems to take about 2x as long. I also experimented with the -m setting to trade off time vs compression quality but the default -m 4 seems fine to me.
The resize forces all images to a width of 640 and whatever height is natural. Twice the target display resolution for retina display.
The one surprise is some of the images (but only some) seem to get a little brighter after conversion. I thought that was a symptom of ICC color profiles not being applied right, which is why I added the -metadata all flag. But it’s still happening. I don’t care enough to figure it out; it could just be the difference in the browser resize algorithm vs cwebp.
Starting with a bunch of 1280x720 screenshot PNGs the webp versions are about 10% the size. If I leave out the image resizing it’s about 25%. That’s mostly thanks to the lossy compression which is fine for my purposes given I’m resizing too.
Overall this got my full page down from 24MB to 2MB. Worth the time!
Some notes on another way to generate one image per link for my linkblog: unfurls. Those are the site previews things like Twitter Cards or Slack Unfurls or Facebook Link Previews. They try to extract a few words and an image from the page; the resulting preview is structured data, not just a picture. Most of these basically work by looking for oEmbed tags, OpenGraph tags, or Twitter’s card tags and then just guessing if those metadata tags aren’t present.
Most unfurls are a mix of text, a little structured data, and an image or video embed. I’m focused on the image. Possibly I could generate an image from textual data too.
Page metadata: OpenGraph and friends
Facebook, Twitter, Slack, etc rely primarily on page metadata to get a text summary and example image. Only works for sites that publish the metadata but since it’s so commonly used now a lot of sites have it. These formats all offer one image. By custom that image tends to be 400+ pixels wide and roughly 2:1 aspect ratio.
OpenGraph is the big standard, originally from Facebook, here’s a useful description of how it works in practice. Dates to 2010. For my purposes the key tag is og:image. og:title gives text.
Twitter’s cards are a popular expansion of the OpenGraph idea dating to 2012. More details on supported tags here. twitter:image is the most relevant, and possibly twitter:player. There’s more tags for textual metadata than OpenGraph.
oEmbed is the oldest standard, from 2008. Metadata isn’t in the page itself, instead you have to make a query to a special JSON endpoint. Interesting image fields are thumbnail_url and maybe the photo and video types. Lots of textual metadata too. I don’t know how popular oEmbed is these days but Slack supports it.
schema.org Articles also are relevant, particularly since Google supports them. It started in 2011 as a way to tell search engines how to summarize a page. Metadata is in the page in one of three encodings (sigh). There’s also an overwhelming number of tags; maybe thumbnailUrl is what I want? or image? Honestly this is all so complicated I’m not in a hurry to learn more.
Without metadata
Metadata is great if it’s present, what do you do if it’s not? Maybe pull an image from the page? This approach doesn’t seem so popular but Feedly does it. There’s a description in item 4 of what they do. Boils down to images tagged webfeedsFeaturedVisual, or else the first big image in the story, or else the biggest image on the page.
Another option would be to take a screenshot of the page itself. I have some notes on that but it’s not very simple to get a good result.
A third option would be to use the favicon. Not awesome, but it is there.
Heuristics for combining preview data
So now we have myriad ways to find an image for the site; which one do we use? Slack has a great post (from my friend Matt!) about how they generate unfurls. They give oEmbed priority, then Twitter+OpenGraph, then HTML meta tags as a fallback. They also seem to combine data from multiple sources; their cards have room for a lot of text.
Tyler Young from Felt recently tweeted about their solution. Light on details though, mostly it’s just “it’s complicated”. That echoes what I’ve heard informally from folks who’ve worked on this problem at various companies. Lots of one-off hacks in the end.
Code Tools
All this stuff is complicated and of general interest; is there a reusable library for generating previews I can just use? npm.io has a big list, here’s some highlights from it and some others.
metascraper (GitHub) looks to be the most active of the NPMs. MIT license, active development. Has a lot of configurable options and also custom code for popular sites. This looks like a strong contender I should evaluate further.
iFramely (GitHub) is mostly a hosted service but their parser is on GitHub with an MIT License. Javascript, looks like fairly active development. Also promising.
unfurl (GitHub). TypeScript, active development, MIT license.
Link Preview (GitHub) generates OpenGraph, TwitterCard, and oEmbed previews of pages. The source is Javascript and MIT licensed. Last updates about 2 years ago. Looks like a small project.
pyUnfurl (GitHub) does the various metadata things and falls back to favicon. Python, MIT License, small project with last main development 3 years ago.
extruct is in Python (BSD license) and recently updated. OpenGraph but not Twitter (yet, there’s a pull request).
webpreview is in Python (MIT license) and was last updated two years ago. OpenGraph, Twitter, Schema, or else “from the webpage’s content”.
Metaphor is the Python code with the most Google juice but hasn’t been updated in 5 years.
Buying a service
Another option for unfurls is just buying a blackbox service for this. Embed.ly is the one I know; part of the value ad is they have “700+ Official Content Providers” who they’ve worked to interoperate with. Their $9/mo product wants to embed “cards” though, which I take to mean Javascript running on your site. Not for me. The $99/mo product is a lot more flexible but is more than I’d want to spend. iFramely also looks promising although similar problem with pricing / embeds.
Update: Ryan B mentioned using linkpreview.net, it looks promising. It has a JSON API that returns data including an image. The free plan might work for me or paid plans start at $8/mo.
It’d also be possible for me to do a bit of guerilla scraping for my own “service”. Post the link to Feedly or Twitter, then capture what preview they come up with. That might actually work pretty well, at least right until it doesn’t.
My Plan
I should start with Metascraper. It looks good, my only complaint is dealing with Node. Alternately I think I’m stuck writing my own thing, a lightweight OpenGraph / Twitter card scraper plus reimplementing some image choosing heuristics. That’s a lot of work I’d rather not do.
Once I have an unfurl tool I can use I should test it on my linblog. I’m really curious how many of the links I’ve posted have useful metadata. I’d guess about half of them in the last 3 years. Seems worth doing a survey.
Screenshots may still prove to be a useful fallback.
I’m working on a way to get one image for a link for each link in my linkblog. There’s two basic approaches: screenshots and unfurls. This post has my notes on screenshots, particularly Simon Willison’s shot-scrape tool based on Microsoft Playwright.
Screenshots boil down to running something like a normal browser and capturing the page after it renders. Sounds simple but the modern web with ads, cookie popups, etc makes this hard. The problem is getting a screenshot that shows the intended content. I tested about 50 links of mine with shot-scraper and maybe 40% didn’t work at all, or had a paywall notice or a cookie consent popup covering everything or otherwise didn’t show anything useful.
One straightforward solution would be just to take screenshots manually when adding a new link. I already like what I’m seeing when I choose to blog a link, why not take a picture? I don’t want to create new work in my flow of posting to a linkblog but honestly this wouldn’t be too much, particularly with a browser tool automating the screenshot process. A related solution would be to pay someone else to do the screenshot for you via Mechanical Turk or the like. But at my small scale I don’t think that makes sense.
shot-scraper is a promising new tool for automated screenshots. It’s a wrapper around Microsoft Playwright, an automation framework that wraps up browsers like Chrome or Firefox and makes it easily programmable. Simon’s shot-scraper puts a nice command line interface around it and while it’s written in Python, it’s more of a command line tool than a Python API. It’s fairly subtle and allows for extracting specific CSS pieces, running some Javascript in the page context, etc. I’ve had promising results with it so far but it needs some tweaking to get the more recalcitrant pages to display.
Ben Welsh’s News Homepages project is open source and also uses Playwright to take screenshots of newspaper pages. The clever thing there is a bunch of extra rules to make the 200 sites they care about look better. There are generic rules like “don’t show anything named popup_wrapper”. Also site-specific rules that boil down to hiding specific CSS classes or running a bit of extra code to adjust the page layout. The bespoke approach won’t work for me since I don’t have a short target list but some of the generic rules might work.
I wonder if it’s possible to install an ad blocker or other addons inside Playwright’s browser? (Simon thought maybe in the Javascript version, but not Python). That might be a good general purpose way to improve the screenshot quality.
Another tweak is to the user agent you send when taking the screenshot. Looking like a bot often gets you blocked so emulating a browser may be necessary. I have a suspicion that the screenshots from mobile versions of sites are likely to be better than desktop ones. Although Tyler warns that different sites work better with different user agents.
There are some web services that do screenshots that might work well: Site-Shot ($15/mo for 5000 screenshots), url2png ($29/mo for 5000), urlbox ($99/mo for 20,000), or the old Thumbshots (shutdown). Update: SavePage.io (free for 7000, $25/mo for 500k). A bunch more listed in urlbox alternatives. (Pikwy looked promising but didn’t work for me.) One thing to check with these is how easy it is to store the screenshot yourself; some seem oriented to them hosting the screenshot and charging per-view.
Overall I’m not very excited about screenshots and will probably not pursue this further for my linkblog. Unfurls / site previews seem a better path.
I have a zipfile. It has a text file inside it. I want to read the first file as text. Here’s how to get a file-like object that has a text stream.
with zipfile.ZipFile(fn) as zf:
data_fn = zf.namelist()[0]
bfp = zf.open(data_fn)
fp = io.TextIOWrapper(bfp, encoding='utf_8_sig')
The tricky bit is all the last line. The problem is ZipFile.open returns a bytes stream. So you have to wrap it in TextIOWrapper to decode it to text. Also my source data has a Unicode byte order mark in it, so utf_8_sig is a magic decoder that will strip out the BOM if present.
This is very remedial Python but I had a hard time figuring it out.
I’m working on my linkblog and went looking to other linkblogs for inspiration. Some notes on their data design and presentation. Note that the heydey of a linkblog was in 2003 so a lot of these designs are quite dated. See Cameron Marlowe’s roundup for a bunch of the old ones.
Common data elements (“authored” means the person linkblogging created the data themselves; otherwise it’s from the page being linked or automated.
URL of page (maybe more than one in a post)
Authored short description of page (sometimes title of page; not authored)
Social media engagement: Tweet this, Tumblr reactions
Full text comments (on LinkMachineGo)
“Via” metadata, the source for the link (on Waxy links)
Morale, positive/negative sentiment (Erik Benson) (I’m doing this now myself and like it a lot.)
To me the defining characteristic of a linkblog is that each post is a single URL. And that the linkblog post itself has no permalink, page view, etc. The point of the linkblog is to point to other stuff, not to be a thing itself. (A key corollary is the RSS feed for a linkblog should have links directly to the destinations, not links to the linkblog posts.) But not all linkblogs are like this; Cal’s is more of a freeform blog, just with very short posts, as is Waxy’s. And there’s a constellation of link-heavy blogs like Today in Tabs or Webcurios.
I’m not thinking of a linkblog as a social conversation. To me it’s a one-way publication.
I think it’s interesting how text-heavy all these linkblogs are, even the modern ones. Hot Links is the only one that had page screenshots / thumbnails. A couple of the modern ones seem to be doing unfurl-like images too, like a youtube embed or a single picture from the page. Mostly text though. My guess is it’s because making images is a hassle.
Here’s some screenshots from modern linkblogs.
And here’s some from O.G. linkblogs (2003ish)
Thoughts for my design
I’m going to stick with the Pinboard data schema. The important elements there are URL, short description, extended description, and tags. I also have a special tag now which indicates sentiment. I’m ambivalent about whether the other tags are useful; the old tagging metadata ethos seems like a failure to me. But I dutifully type six or so random words per link, might as well display them.
What I’m most interested in is what else can I add to a linkblog entry to make it more interesting / convey more about the target. My big wish is for an image: either a screenshot or a Slack/Twitter/Facebook/OpenGraph like unfurl. I’ve been researching how to do that. I also am curious if there’s an AI driven web page summarizer that would be useful. Probably not, and limited to text-heavy links anyway. But worth a look.
As for visual design I’m most inspired by that Hot Links screenshot above. I want to avoid the “list of text links” look although with a fancy layout like Balaji’s (4th modern screenshot) it looks better.
Sources
Here’s a list of all the linkblog URLs I looked at for this little survey.
Got distracted by a yak today; trying to add Python static type checking to PugSQL generated code. I got something that kind of works but it’d take some effort to make really useful. The basic idea is to create a .pyi file for PugSQL’s queries module.
The challenge with PugSQL is it’s generating functions dynamically. At runtime it reads a .sql file that says “create a function called pugsql.compiler.Module.count_links()”. So of course VS.Code’s static type checker pylance/pyright has no idea what count_links() is and it displays a red squigglely line.
I kludged it by using PyRight’s type stub support. I used PyRight to autogenerate type signatures for pugsql, including a file named typings/pugsql/compiler.py. (These generated signatures were not very good; the command line guessing tool does less of a good job guessing types that VS.Code’s interactive stuff.)
Then I edited that file to add some type signatures for my custom methods I am creating using PugSQL.
count_links is the simplest, it’s a basic select count(*) from links query. Takes no arguments, returns a number. select_recent pulls off N rows and returns them as a list of dicts (select * from links limit 10). Finally upsert_link is taking a list of rows (as dicts) and inserting them.
These are pretty generic type signatures. For instance select_recent is returning typed data from sqlite; those dicts actually contain entries with types you could infer from the SQL schema. That’s a good deal more complicated to do automatically, though. It’d be awfully nice, but then my main goal here was just to shut up the red squiggly line and for that a more generic type is sufficient.
Having done all this it’s enough of a nuisance I probably won’t pursue this further. But I could imagine PugSQL emitting these .pyi files automatically, it could be pretty slick.
Starting a new project and want something to take the tedium out of a small sqlite database (like 2 tables, a few thousand rows). I don’t want to write wrappers for SQL to insert and select rows. OTOH I don’t want a complex ORM like SQLAlchemy or Django. What are my options?
Peewee. Well established, seems to be the consensus choice. Don’t love the code examples but they’re fine. Docs are good. Supports migrations.
PonyORM. The other frequently mentioned option. Has nifty metaprogramming so you can write queries in Python. But it does not support migrations.
Datalite. A very small binding between Python Dataclass types and sqlite tables. Docs are thin but code is small and readable. Supports migrations, surprisingly.
Based on my last project with SQLAlchemy, migration support is important. So that rules out PonyORM. Peewee and Datalite are very different in scale. I’ll start with Datalite and if it’s too limiting, consider moving to Peewee.
Update: Dan reminds me of PugSQL which is a wrapper for easy SQL execution in Python. Not really an ORM but does take the tedium out of simple SQL queries. And avoids ORM magic.
CAVEAT LECTOR: these are my notes after 2 hours of reading Wikipedia articles. I’m a rank amateur, in no way is any of this stuff authoritative. Better resources than this blog post: Learn Hangeul, Let’s Learn Hangul.
I’m interested in Korean writing, specifically Hangul. It’s so graphically beautiful! And I love writing systems. It seems possible to learn enough to pronounce words clumsily in just a few hours.
Hangul 한글 is what modern Korean is written in. But historically there were other writing systems. Hanja 한자 / 漢字 is the big one; was used starting around 4th century BCE and is based on Chinese characters. I think it’s a little like how kanji works for Japanese. Hanja is still in occasional use but I think mostly in text describing historical things or some proper nouns. There are some other historical writing systems too, mostly efforts to use Chinese characters to represent Korean word sounds. There are several modern Romanizations including a standard one. Also Kontsevich, a transliteration into the Cyrillic alphabet.
Hangul was invented in the 15th century by King Sejong 조선 세종 (or his advisors) and published in a written Chinese document called the Hunminjeongeum 훈민정음 / 訓民正音. It wasn’t immediately popular, Wikipedia implies the educated classes were snobbish about their classical Chinese writing. Hangul became official right at the end of the 19th century. It’s been slightly reformed over time, with some phonemes being removed or unified as they fell out of use.
Despite looking a little like Chinese on first blush Hangul is actually a phonetic writing system; each square that looks like a character is actually a syllable composed of (usually) three phonemes. In general Korean is a CVC language. A block like 한 (“han”) is really three letters called jamo 자모. So 한 can be broken down into three jamos drawn in one block: ㅎㅏㄴ (H A N). There’s a claim that Hangul is a featural writing system, that the visual shape of a jamo reflects the shape the mouth makes when making the sound. Not sure how accurate that is.
Jamos are pretty much never written alone. Instead they are combined into a square block with a fairly straightforward algorithm nicely visualized on Wikipedia. The last consonant is at the bottom. The first consonant is either to the left or above the vowel. It gets a little more complicated because some letters have complex forms.
One extra detail: at least in Unicode, jamos come in both leading (choseong) form like ᄀ and trailing (jongseong) form like ᆨ. The shapes look the same but in this font I’m using they’re shown at different heights. I’m not sure why leading vs. trailing is encoded differently or whether Korean native speakers think of them as different things; since jamos don’t normally appear alone it’s a pretty academic point.
English speakers should be aware that Korean phonology is quite different from English or similar European languages. A “t” sound could be a simple t ㄷ, a tense t͈ ㄸ, or an aspirated tʰ ㅌ. These variants are written as different jamos and are basically entirely different consonants even if they sound kind of the same to an English speaker’s ear. Modern Korean is not tonal but historically it was. Hangul used to use diacritics to indicate tone.
Korean in Unicode is a bit of a mess. My understanding is almost all systems encode Korean with Hangul Syllables, characters in the range U+AC00 to U+D7AF. Each code point is a single syllable. Use those and it’s pretty simple, there’s just a lot of them. The odd thing is these 11,184 code points are entirely algorithmically derivable as combinations of the individual jamos that make up the syllables. The graphical combination is also algorithmic. Instead of thousands of syllable code points you could just write Korean unambiguously as strings of 67 different jamos, they are in Unicode (U+1100 to U+11FF). But that’s not what people do in practice (see the road not taken). I think the only time you’re likely to see the jamo form is if you use normalize and decompose input into Unicode NFD.
A second historical complication of Korean Unicode is mentioned in a tart comment in the UTF-8 RFC
Amendment 5 to ISO/IEC 10646, however, has moved and expanded the Korean Hangul block, thereby making any previous data containing Hangul characters invalid under the new version. Unicode 2.0 has the same difference from Unicode 1.1. The official justification for allowing such an incompatible change was that no implementations and no data containing Hangul existed, a statement that is likely to be true but remains unprovable. The incident has been dubbed the “Korean mess”, and the relevant committees have pledged to never, ever again make such an incompatible change.
Mentioning this mostly because it’s funny, doesn’t seem relevant to contemporary systems.
Next thing for me is I’d like to learn more about Korean calligraphy and font design. How Korean artists think about their own writing and manipulate it.
I very much like my idiosyncratic coding setup with proportional fonts and automatic code formatting in VS.Code. But it doesn’t play well with others. Every time I save a file it completely reformats it in my preferred way. Not popular at pull request parties.
Making per-workspace settings that are more collaboration friendly is very easy thanks to VS.Code’s flexible settings. It basically boils down to creating a .vscode/settings.json file in the project workspace with a few settings to override the weird ones I have. By far the most important is “format on save”; the others just make my display fixed width like most people’s so I see what they’re seeing. Here’s the overrides I have in my workspace settings:
In this post I build up an absolutely minimum working Hugo theme for my blog based on the files generated by hugo new theme. The result isn’t a blog I’d publish, but it’s a useful start in understanding how Hugo works.
I’m still wrestling with learning Hugo. Clearly the simple thing is to use someone else’s theme. But I need something custom and specific and also I want to understand what Hugo is doing. So I’m making my own. It’s slow going. There’s no great examples to crib from (all the “minimal blog” themes I could find are elaborate things that include lots of styling and extra features.)
One useful resources is the lookup order page buried deep in the Hugo docs. It explains the basics of how theme template files are used. The best part is where it says “The examples below look long and complex.” Yes, yes they do. But then it also then tells you that in fact there’s 4 templates that are most important:baseof.html,. list.html, single.html, and index.html. Most of my notes here are going to focus on those files.
One useful thing to know about is partial templates. These are HTML snippets intended to be included in other HTML templates. They’re kind of like subroutines, but for templates.
I’m going to follow this tutorial on creating a Hugo theme. It adds some extra stuff (some partial templates for inclusion, CSS, Javascript, a menu) but at its core are those 4 files listed above. I’m going to skip the parts I don’t want and document what happens along the way.
This whole process started with Hugo’s quickstart. I did that first and got my blog working with someone else’s theme. Then I removed the other themes I was using and created my own.
Content
I’ve seeded my blog with a bunch of content (1771 posts) in directories like content/weblog/tech/good/ and content/weblog/politics/. I’ve tested this content works OK with other people’s themes. My blog has several top level directories: politics, tech, culture, etc. For simplicity I put all these directories not directly under content/ but in a single subdirectory (weblog/). This results in a /weblog/ in the URL I’d rather not have but it renders the whole blog in one giant list. With subdirs I was getting one list per top level category. I think this has to do with Hugo Sections, something I don’t understand yet.
config.toml
Before you create a theme you need to configure a blog. I did this in the quickstart.
“theme” is the name of a directory under themes/ we’ll create in a minute. Note the baseURL matters: it’s going to be hardcoded in a lot of output files. (Although Hugo seems pretty good about supporting relative URLs where possible.) I made a mistake at first and had it set to https://www.somebits.com/weblog/; but that causes duplication of /weblog/weblog/in the URLs given the section setup I did.
An empty skeleton theme
Step 1 is running hugo new theme nelson. This creates a skeleton theme. There’s 11 files that creates but they have very little in them. In particular index.html, list.html, and single.html are all empty. baseof.html does have some HTML boilerplate with a <html> tag and inclusion of some partials for page headers and footers; those partials are also generated as empty files. There are no template files for XML or RSS.
You can go ahead and build a Hugo blog with just this skeleton theme but not much happens. In particular no HTML is generated, despite Hugo saying 4 pages were created. But Hugo will create some XML. Two identical RSS 2.0 files under index.html and public/index.xml, both containing all 1771 blog posts entirely. My whole blog in one XML file! Also two empty RSS 2.0 files for “recent content in tags” and “recent content in categories”. Finally a sitemap.xml with 1775 URLs in it, presumably my individual posts and a few index pages. All in all it looks like Hugo has some default blog XML generation. That’s handy but I’m surprised those aren’t implemented with a generated template file. They can be overridden though.
You can also try to load URLs by running “hugo serve”. The suggested URL http://localhost:1313/ contains an empty <pre> block and nothing else. There is no .html file for this in the static blog, nor anything in the templates, so I guess this is something the Hugo server does. http://localhost:1313/index.xml does load and gives back the RSS contents that were generated. Useful URLs for individual posts like http://localhost:1313/weblog/tech/electrify/ from the sitemap give 404s; they weren’t generated, afterall.
Formatting single blog posts
So how to get posts rendering? The absolute simplest thing is to put any content at all in single.html. I put 3 bytes in that file; “Yo\n”. Rerunning hugo results in 1775 pages being created, 1776 files. The 4 XML files from before, the sitemap, and all 1771 blog posts. Nice! Every blog post is at the expected URL and all have the content “Yo”. Note that the HTML in baseof.html did not appear, that’s a little strange.
The next step is to make single.html a little more complex. {{ define "main" }} Yo {{ end }} Regenerating with this also creates 1776 files that all say “Yo”. But now the “Yo” is sandwiched inside the HTML template matter in baseof.html. So that’s a bit magic; apparently Hugo does something different depending on whether that “main” block is defined in the page template or not. (Note that the “main” section is used by baseof.html). Almost all the docs for templates always suggest defining a “main”, so that’s the ordinary thing, and it is shorthand for “slot this into baseof.html”. I wonder if this is explicitly coded behavior or if rendering baseof.html fails with no “main” defined.
Finally I replaced my single.html with a useful template that shows post content:
Regenerating with that and I get something that’s starting to look like a real blog. Each post gets a title and the post content. Nice!
It’s worth noting at this point that Hugo’s preference for “pretty” URLs means that all your blog posts are in files named “index.html” in subdirectories named after the post filename. Ie, you get a tech/electrify/index.html, not tech/electrify.html. This behavior is configurable.
This was all more confusing than necessary; when I first generated my new theme I could not understand where my posts had gone. If it were me I’d make the new theme command generate something like my last single.html, not an empty file which then means don’t generate pages at all. But then maybe that would confuse people trying to use Hugo for something other than a blog.
Lists of blog posts
Having gotten single posts working it’s time to visit lists. Starting as before, I put just “Hi\n” in list.html and regenerate. Unsurprisingly, this creates a file with just “Hi\n” in three places: weblog/index.html, tags/index.html, and categories/index.html. Putting the “Hi” inside a {{ define "main" }} gets it to use the baseof.html template, just like single posts did.
Moving on to an actual useful list, I took a page out of the tutorial I’m following and put this in list.html
{{ define "main" }}
<h1>{{ .Title }}</h1>
{{ range .Pages.ByPublishDate.Reverse }}
<p> <a href="{{ .RelPermalink }}">{{ .Title }}</a> </p>
{{ end }}
{{ end }}
And voila! Now http://localhost:1313/weblog/ loads with a list of all 1771 posts. As the template suggests, each post is rendered inside its own <p> tag with a Title and a relative link (no hostname) to the Post. It’s like I have a real blog now! Well, the basics.
The magic is thanks to that {{ range }} in the template. The range Hugo function is incredibly important, it’s the hidden loop in templates. It stands for “iterate over this whole collection of things and insert stuff one by one”. Range. I read Hugo docs for hours before I found this key concept.
Gestalt
We’re not done yet but I’m going to declare victory with this ultra minimal blog. In summary, all that was necessary was the create a new theme template, then put some very basic stuff in single.html and list.html. There’s plenty more to do. The tags/index.html and categories/index.html files are still empty; I’d like categories to be populated by directory name. I’d also like to generate monthly archive pages. Could do with some pagination too, not to mention more formatting and breadcrumb navigation. But now at least I understand how to render a list of blog posts in Hugo. And I’ve got it rendering a useful top level list.
The main thing I learned in this exercise is what Hugo does by default with very little templating. It renders every content item through the single.html template (and usually, baseof.html). It also renders list.html for the basic list of all blog posts; it’s up to you to use the range function to build and render that list. As an aside Hugo is also doing some basic RSS and Sitemap creation for you. And that’s it!
I’m trying to port my blog to Hugo. It’s not going well. The problem is Hugo is complicated. And nothing out of the box does quite what I want (admittedly, my blog is pretty special snowflake stuff). So now I’m diving in trying to learn how to create my own custom theme, control pages generated for indices, etc. It’s a mess.
What doesn’t help is Hugo is incredibly complicated. Right now I’m struggling to learn Go’s template language, which is the basis of Hugo templates. It’s confusing and gross and I don’t want to learn yet another ad hoc programming language. It’s really confusing because I still don’t have the gestalt of how all Hugo fits together. Like at its core there’s some thing that reads a bunch of content blobs and renders those to HTML along with some list pages of things. Where is that simple structure expressed? Somewhere, but I still don’t quite get it.
Not helping things at all is weird magic. I kept trying things in a simple shortcode and getting the result ZgotmplZ inserted. WTF is that? It looks like a mangled C++ class name or something. No, turns out that’s Go Templates saying “you have used a thing in an unsafe context”. So that’s super confusing. Now I have to learn what contexts are, what safe means in this context, and how to make unsafe things safe. If it’s even possible.
Maybe I should give Jekyll a shot. I already tried Pelican and didn’t love it.
So I’ve been using noise functions in my plotter art. One thing to be aware of with noise functions is the output distributions aren’t uniform. I don’t just mean the smooth variation of nearby points that you’re using a fancy noise function for, but even if you sample uniformly from a large space the values are still closer to a normal distribution than a uniform distribution. To put it more concretely; these noise functions all return values in the range [-1, 1]. (2d Perlin noise is [-0.7, 0.7] ish.) But results near 0 are more common than results near 1 and -1. See below for some histograms.
This isn’t necessarily bad. You can always scale the output up to a uniform distribution or whatever you want. Although that requires knowing what the original distribution actually is. Perlin noise looks like a real normal distribution but both Simplex and OpenSimplex noise have a weird boxy distribution where results are uniformish in the range of -0.5 to 0.5.
More than the usual caveats apply; this is sloppy code and I might have gotten it wrong. Histograms are for 1 million samples drawn from OpenSimplex and caseman’s Perlin and Simplex noise. 2d noise in each case; the coordinates were uniformly sampled in the range of [-100_000, 100_000]. (A small range because caseman’s code seems to be using 32 bit floats). I did not alter the scaling or octave parameters at all, library defaults. My code is in this gist.
Update: I asked about this on the Plotter Art Discord and someone suggested empirically measuring the distribution then doing a correction. They offered this matlab snippet:
p = randn(1000,1);
p2 = (p-min(p))/(max(p)-min(p));
x = sort(p2);
CDFp = linspace(0,1,numel(p2));
pUnif = interp1(x,CDFp,p2);
Once again contemplating moving my blog away from the ancient Blosxom setup I have. Static generators are clearly the way to go. Here’s what I found among Python options.
Pelican looks to be the most popular. Nikola is also compelling. Lektor may also be an option. Cactus and Hyde are abandonware.
I normally frown on time spent customizing coding environments. But since I’m switching to VS.Code I figured it was time to also consider trying proportional fonts for coding again. It’s ridiculous how we still write code as if our I/O devices were line printers and ttys (or worse, literal punched cards.) Proportional fonts are certainly idiosyncratic for coding but there’s a growing community of folks doing it. GoLang gave it a lot of legitimacy; Rob Pike has been using proportional fonts for decades and who’s going to say he is wrong?
Here’s where I’ve landed so far. To get there I had to set up VS.Code to deal nicely with proportional fonts, then adopt a Python code formatter that put out code that looked good in my setup: YAPF, not Black.
The first chunk sets the font. Note you have to set the terminal font to a fixed width font: by default it will inherit the editor fontFamily and proportional fonts do not work at all in a terminal window. They never will work well, too much Unix console UI assumes fixed width.
The rest of the settings are for making proportional fonts look nice for my Python code. Read below for details.
Font Choice
The nice thing about proportional fonts is you have so many to choose from. Want to program in Zapf Chancery? Go right ahead. (No, don’t do that). One thing to look out for is a few characters special to programming. You want 0/O and l/1/| to be distinguishable. The { braces} and [ brackets ] are also important and often overlooked in non-coding font design. Another thing to think about is the overall width of characters; many programmers want a narrow font to get more on the screen. I don’t.
I started with Calibri;. I like how it looks, it’s calm and innocuous. It’s not designed as a coding font but it’s not bad for the purpose. I’m currently experimenting with the five new Microsoft candidate fonts that fell off the back of a truck. They all look pretty good. None are designed as coding fonts but they all seem to work OK. The screenshot above is Tenorite.
I’d still rather use a proportional font designed for coding. There are precious few of those. Input is the standout and it is a very thoughtful font, including proportional options. I just don’t like the way Input Sans looks. Purely a subjective opinion. The Go Fonts are another good option but again don’t like how it looks, it’s a very opinionated design.
(PS: font installation still sucks in every OS. After you install new TTF fonts in Windows 10, close and reopen the Settings program or else it will hang / crash randomly. You also have to restart VS.Code to make it aware of newly installed fonts.)
Update: since taking the screenshot I added the letterSpacing. It’s a kerning kludge, to add 0.6 pixels of space between all letters. Text was just too tight, particularly things like the empty string ‘’. A single fixed value isn’t ideal for this but it helps.
Tabs vs Spaces
You can just change the fonts in VS.Code and start coding, things will mostly work. But the indentation isn’t awesome. The space in a proportional font is so narrow that the typical 4 space indent ends up being too narrow (and 2 spaces is impossible).
So I switched to tabs. Yeah, really; this is my embarrassed face. I’ve spent nearly two decades expunging tabs from all my code (except Makefiles and other monstrous systems that require them.) I had clearly chosen sides in programming’s stupidest controversy. But in the back of my head I always knew tabs were “theoretically” better; tab is a semantic character, saying “this is a new level of indentation”, and the fact it’s 2 or 4 spaces shouldn’t matter at all. The tab character is the way to express that logical structure. It’s also the practical way to make Visual Studio work, because it lets you customize the look of the indentation without changing the bytes in the file.
So the second block of my VS.Code setup is setting the tab size to the size of 8 spaces. That “looks right” to me in Tenorite. It happens to also be the standard. For Calibri 12 looks better to me. 12 would look terrible in a fixed width font but you make sure your output only ever has tabs (not 12 actual spaces) and it’s fine. Wouldn’t it be nice if this setting were in terms of an em-space or en-space instead of the tiny space character? In real typesetting spaces are variable width.
Code formatting: YAPF, not Black
Automatic code formatting pairs nicely with proportional fonts. You’ve given up the ability (or requirement) to vertically align blocks of comments and code and stuff. Might as well use a tool to just format everything for you. Again the Go community is a guide here; gofmt is a standard tool. The same principle works for Python too!
I switched to using Black a few days ago and loved having a formatter make choices for me. However Black is very serious about making specific choices and they are very clear they won’t support tabs. Nor anything but 4 spaces. That’s Black’s whole shtick and I kind of like it, right until I don’t.
So I switched to YAPF, Google’s formatter. It’s a whole lot like Black but it’s more configurable. Out of the box there are some slight differences I prefer (fewer vertical lines for braces, etc.) but it basically does PEP8 more or less like Black does. But YAPF invites configuration. I tried to use a light hand here, I really wanted to not do anything too personalized.
The second chunk is all about using tabs instead of spaces for indents. You have to tell it to use tabs twice; for most things, and then specifically for continuations (with the cryptic value valign-right). I’m not positive that the indent_width setting even means anything.
The column limit is.. I don’t know what’s right. 80 columns is very narrow, one nice thing about a proportional font is it typesets a good deal narrower than fixed width. 132 would be a natural choice with precedent. But I’m going to go to (near) infinite. We’ll see how that works out. 999 might be a better choice to catch pathological cases.
The last two entries are preference things for me, idiosyncrasies. I figured hell I’m customizing YAPF already, why not go whole hog!
(PS: if you want to understand what YAPF styles are, look at the --style-help output. The code for making styles is also interesting.)
Drawbacks
As I write this I just set this up today; I haven’t lived with it. We’ll see how it goes.
The primary drawback is interacting with other programmers. Folks would right be mad at me if I submit a 2 line patch to some code when 800 other lines changed reformatting the code. It’s always more important to follow an existing style! But right now I have the luxury of mostly working alone on my own code so I can experiment a bit.
The other drawback is interop. Much of the Unix world (and my own environment) is designed around monospace fonts and 2 or 4 character indents. Things like my .bashrc look weird in this new setup, at least until I convert them to tabs. It’ll never look right in a terminal window which has to be fixed width for most things to work right. I think writing code in an editor is the important use case, so I’m OK optimizing for it, but we’ll see.
I’m also a bit uneasy that this setup is so Python specific, relying on the code formatter. I guess most languages have formatters now though.
Update (Jan 2022)
This setup has worked great for me. I’ve basically used it unchanged since I posted this and am much happier. My code looks nice! The only real problem I’ve run into is YAPF has some bugs where it seems to reformat my code slightly incorrectly sometimes, something about comments and multiply nested blocks. It’s purely cosmetic and I mostly just ignore it.
Update (Nov 2023)
Still working with proportional fonts, still like it. Thanks to this discussion I now know a new term for right-aligned comments that don’t work with my setup. “Hanging comments”. There’s a nice writeup of a solution for this called elastic tabstops; basically you make the editor capable of tabbing comments to a second left-aligned column. Unfortunately there’s no plugin to do that in VS.Code with a proportional font, and the discussion in the feature request implies it’s not easy to add as a plugin.
After years of using Sublime Text 2 I decided to switch to a newer code editor. The tipping point was wanting to use the Black Python formatter; ST2 doesn’t have support for it. (ST3 does but I don’t own that). VS.Code seems to be the new hotness so I’m giving it a try. So far I like it! Some thoughts:
Good: it feels very fast. It’s amazing how slow so many programs feel on my very fast desktop computer. VS.Code feels fast.
Good: the extension store. There’s a rich ecosystem of addons. I’ve already lost track of what all I’ve installed: Python, WSL, SQLite ... I’m still looking for a good JSON extension (the one I tried is very very slow). I’m still understanding the extension model; I keep having to install black and pytest and pylint in every project’s venv. That’s awkward but kinda makes sense.
Bad: It’s an IDE. I don’t like IDEs, I just want a tool to edit text.
Good: It’s an IDE! I can code with tools as good as the Turbo Pascal environment I used in 1986. VS.Code is notable for being a cross-language IDE. It’s also a fairly low impact IDE, you can mostly use it as a text editor to start and it’s fine. But I’ve started making peace with the Python IDE stuff and it works fine. It runs unit tests nicely (albeit without support for continuous testing on save.) The debugger works.
Mixed: linting and PyLance warnings. These are enabled by default and mostly don’t seem to show up. But I just got a warning from PyLance because os.getenv can return None and I was passing its output to a function that needs a string. But I was anticipating that and already had a try/catch block for that. At least you can suppress warnings on a line by line basis with the comment # type: ignore
Good: black. It’s instantly freed me about worrying about code formatting. My only complaint with the default black setup is it does weird multiline formatting if any lines go over 88 characters by default. You can change the line length but the whole point of black is one standard consistent style, so I hate to change that.
Mixed: Intellisense suggestions. It’s very nice when exploring but the default settings are awfully chatty. Currently trying out these settings to tone it down some:
Good: The command palette UI is nice. VS.Code didn’t invent that but seems to lean on it heavily. Emacs users used to typing M-x will feel right at home.
Bad: preferences. For years the only way to change preferences in VS.Code was editing settings.json. There’s now a GUI for it but it’s clearly generated from the JSON specs and it shows. It’s clumsy.
Good: Settings sync. You log in via Microsoft or GitHub and VS.Code syncs your settings, UI state, etc. It’s optional.
Mixed: the look and feel. Something about the very spare UI chrome and the color schemes feels wrong to me. Maybe I’ll get used to it. I’m using the Dark+ theme now and it’s mostly fine, I just feel a bit dislocated. I have a particularly hard time with the filename tabs. This customization might help:
Great: git integration. I don’t think it’s trying to be a full git client but it has a nice UI for quickly seeing what code has changed and staging and committing code. The diff viewer is terrific.
Good: I can launch VS.Code from a WSL shell with code . It automatically loads the VS.code project file for me. It also seems to detect my venv/ directory and use it.
???: security. Every time I load files from a new directory VS.Code asks me if I trust the files in the directory. WTF? I guess VS.Code or some extensions will run code snippets it finds in files you are editing in some circumstances. That seems like a terrible security risk and passing it off to the user is not good.
Somehow I’ve done generative art experiments for 30 years without every really understanding noise functions. I mean I’ve certainly used some but never directly, generally by incorporating someone else’s noise-derived textures or something. So here’s some notes.
Noise functions
Processing’s noise function is probably how most generative artists first encounter noise. It is straight up Perlin noise, the classic 1985 algorithm. It’s defined for any number of dimensions but let’s just focus on 2D noise for now. You give it an x, y and it gives back a random number 0-1. The key feature of Perlin noise is it’s smooth; two x, y points near each other will have a similar value. Note there’s an implicit scale in Perlin noise; is (100, 100) “near” (0, 0)? Or do you have to go as close as (10, 10) or (1, 1)? This scale factor is not very interesting but you do want to dial in a scale that has features of the size you want. Perlin noise implementations often provide other tuning like how many octaves to calculate and how much each contributes.
Perlin noise has a problem in that it’s somewhat directional; you can see horizontal and vertical artifacts in the top 4 images above. (Taken from this blog post). The bottom 4 images are similar treatments of OpenSimplex noise. Simplex noise is a different algorithm Ken Perlin made in 2001; see here for an explication. Unfortunately Simplex noise has some worry about a patent (expires January 2022!). So that’s why there’s OpenSimplex: it has similar features but was designed to be avoid the patent. (Patents on math: so stupid.) In addition to being isotropic both kinds of simplex noise are also faster to calculate.
FastNoise is really a collection of different noise functions with an emphasis on fast implementations. Includes Perlin, Simplex, and a bunch of other choices. The project is ambitiously multi-language and has several iterations as the author has supported SIMD first and then rewritten everything as FastNoise 2. Note the author Jordan Peck works on No Man’s Sky, one of the most ambitious procedurally generated videogames out there. It’s full of noise functions.
There’s a bunch of other noise functions out there too. Worley noise, Fractal noise, Gabor noise... It’s like after Perlin got an Oscar for his noise function everyone wanted their own ;-) There’s also a lot of work in making fast implementations, running on GPUs, etc. I’m getting in the weeds now so I’m just going to look at some simple things to use with Python implementations.
Python implementations
perlin-noise, a basic Python implementation of Perlin noise. Works with any number of dimensions.
noise, a native code implementation of Perlin noise and true Simplex noise. 1-3 dimensions for Perlin, 2-4 for Simplex. Also includes a GLSL implementation for shaders that I did not test. This code is mostly 9 years old! But there’s no reason that should matter for something this simple. Note it has no API support for setting a seed. You can override the entire random integer function though which would let you also control seeding.
pyfastnoisesimd is a SIMD optimized, parallelized implementation of FastNoise. There’s no simple API for generating a single sample; it’s designed to generate large grids of numbers all at once (very quickly).
I’m currently using OpenSimplex in my projects, mostly because it’s the first library I found. It’s easy to use and fast enough for me.
Benchmarks
I don’t really much care about speed in my applications but I was curious, so here’s some simple timeit statistics to generate a single 2d noise sample.
Constant
50000000 loops, best of 5: 0.00469 usec per loop
math.random()
10000000 loops, best of 5: 0.0359 usec per loop
OpenSimplex
100000 loops, best of 5: 2.34 usec per loop
perlin-noise with 6 octaves
5000 loops, best of 5: 90.6 usec per loop
noise.pnoise2
5000000 loops, best of 5: 0.1 usec per loop
noise.snoise2
5000000 loops, best of 5: 0.0844 usec per loop
So there you have it. About 0.1 microseconds per sample for the C implementations, 2.3 for OpenSimplex (Python), 90 for Perlin (Python). To it it another way, that’s roughly 10M samples a second for the C code. For comparison pyfastnoisesimd says it’s a few nanoseconds / sample, or 200M+ samples / second.
Using noise for art
Noise functions are just random number generators; how do you make art with them? Ha, as if there were a simple answer to that question.
I did make one simple demo that a zillion people have done; making a grid of OpenSimplex noise and then visualizing the number with a short line segment rotated by the noise value. You have to fiddle the scaling to get it to look interesting. Here’s a result that looks pretty nice plotted, although drawing all ~5900 line segments took 90 minutes.
Another classic plotter use of noise is to draw “flow fields”. It’s a simple physics simulation; you drop a particle at a point and then interpret the noise value as an angle of force. Then you draw the trace of the particle as its buffeted around your grid. I’ll probably do that next, it’s a classic with a lot of interpretations.
Seeds
An aside on seeds. It’s nice to use words as seeds instead of numbers. There’s a zillion ways to do that but one easy way to turn a string into an int is zlib.crc32(seed.encode('utf-8')). Note that’s a 32 bit int; 64 would be nicer. Oddly there are precious few 64 bit checksum and hash functions, I don’t think any are installed into Python by default.
Having worked on rendering text on my AxiDraw, the next question is how to typeset text. The challenge is SVG 1.1 text elements are explicitly single line, no automatic wrapping. There’s no text flow in an SVG renderer, you have to do it yourself. (SVG 2.0 promises to add this, and I guess there was an ill fated effort in SVG 1.2).
There is a nice way to express multiline text in SVG using the <tspan> element.
<text class="verse">
<tspan dy="1.2em" x="10"
>How doth the little crocodile</tspan>
<tspan dy="1.2em" x="10" dx="1em"
>Improve his shining tail,</tspan>
<tspan dy="1.2em" x="10"
>And pour the waters of the Nile</tspan>
<tspan dy="1.2em" x="10" dx="1em"
>On every golden scale!</tspan>
</text>
Note the use of dy to do the line spacing; that’s nearly automatic. (the dx parts are for some fancy indentation. Not sure why x is being set explicitly every time.) All you have to do is decide where to break the lines! Ha.
I can’t find a Python library that will break lines for you or do more fancy automated typesetting. It is possible in Javascript, or at least you can write code to do it, using the getBBox() function to inspect the pixel size of some text and use that to break lines.
One approach in Python would be to calculate metrics for a font and then use that to estimate the width of a word. That won’t work if the kerning isn’t predictable. Also it’s a lot of work to do right for arbitrary fonts.
A second approach is to use something to render SVG in Python and use that to measure widths. Something like the pyrsvg wrapper for librsvg. That’s a lot of code to bring in though and I’m not confident it would perform very well. py3rsvg looks promising as a lighter / standalone option. See also this discussion.
A third option is to skip SVG text entirely and work directly with HersheyFonts generated paths in Python. The library has support for inspecting the width of glyphs; bounding box, etc. But this library is a separate work from the Evil Mad Scientist / AxiDraw code for Hershey text, the one that’s an Inkscape extension. They’ve done some nice work on fonts, etc so I’m not sure how much you’re giving up going with this other code instead. SVG Fonts, for one; I think the HersheyFonts library is using the actual Hershey format. That means no Unicode. I’m not sure the ESM HersheyText Inkscape code can be repurposed though, it seems to be written in a very Inkscape-specific way and relying on their renderer. I could be wrong about that though.
I think that last option may be best; it’s closer to the actual SVG I want to send to the plotter.
I’m looking for some tools / inspiration for creating text with my pen plotter. The issue here is that most of desktop typography doesn’t apply to plotters because it all relies on filled fonts, effectively bitmaps. Pen plotters draw single lines. You can try drawing and filling the outline of a traditional TrueType font but that seldom looks good. OTOH there’s a whole art form of handwriting text with pens, so maybe some ideas from artists that can be borrowed?
Unfortunately traditional calligraphy is out because most calligraphy requires varying pen pressure to change line width and that’s something an AxiDraw and most other plotters simply can’t do. You can get somewhere using an italic nib (basically a pen tip that’s a wide line, not a point) but it’s pretty tricky. And it still relies on you having a font to draw the shapes.
The other quick solution is what’s called “Hershey Fonts” (after a Dr. Hershey!). AxiDraw has support for them as does this third party product but the actual classic Hershey fonts are, let’s just say, unaesthetic. The image below was plotted poorly with a bleeding pen on cheap paper, so ignore the dots and bleed, but nothing’s gonna fix these tragic shapes.
Update: when writing this up I neglected to talk about the EMS fonts, a series of free SVG fonts included for use with the HersheyText 3.0 plugin and SVG font format
The Good Stuff
So I asked on the drawingbots Discord for inspiration and got a couple of good suggestions.
A simple option is to just use better fonts. Single Line Fonts sells a handful of nice looking fonts for very modest prices, $20 or less. (And try the coupon TAKE25OFF). A bit heavy towards cursive scripts (but not true cursive, since the letters don’t actually connect.) There’s a very limited set of SVG fonts but a larger number of TTF fonts. I think those can be used with an AxiDraw OK, they mention that each line is drawn twice because of technical requirements.
A more sophisticated (and expensive) option is Quantum Enterprise’s single line fonts. There’s 59 fonts in a variety of styles. At $130 a font these aren’t cheap! But they’re nicely designed and have a lot of technical details on how to best use them with AxiDraw. Also these aren’t simple fonts; they have variant characters so that you can draw text without every single instance of a letter looking identical. They have a software tool (“Scriptalizer”) that will render variable text for you, demo it here. They also offer a service that will generate a custom font from a handwriting sample for $350.
Inspirations
One interesting point someone made is that a lot of what’s driving handwriting with plotters is marketing. Folks trying to mass-print mailers that look like they were hand written so you don’t just throw their junk mail immediately in the trash. I wonder if that’s part of AxiDraw’s business; you’d want a faster machine for mailing thousands of pages but it’s suitable for small runs of envelopes, etc. Anyway, sleaziness aside I’m glad to lift any approached they’ve developed. One interesting merchant in this area is Handwrytten, they sell robot-hand-written cards as a service ($3.25 a card!).
But what I really want to see is experimental / artistic plotter typography. Something like the explosion of interesting art folks were doing in the early 90s as desktop publishing technology made it so easy for artists to manipulate text. Stuff like this or this, only plotter-focussed. Someone must be doing this kind of work out there but I haven’t found it yet.
I’m also wondering what the state of the art is for true cursive script being generated in software. Something similar is essential for Arabic typesetting and is more-or-less a solved problem, so it seems likely that English cursive script could be doable?
Updates
There’s some good resources on the EMS Wiki also here. And some other stuff.
I tried taking a TTF font from vLetter (Hobbs), converting it to SVG font format with Convertio, and then using it with Axidraw Hershey Text (in Inkscape). Unsurprisingly this generates an outline font, not a stroke/engraving font, so each character is overdrawn twice (slightly off shifted). Probably no point converting the TTF to an SVG Font; the text to path tool in Inkscape can do the same thing. Anyway, my sample of 10pt text looked OK with a very tiny 0.05mm Staedtler pigment liner but it’s obviously not as good as a real stroke font. (Note the tiny hollow letters; that’s a fine nib on that pen, anything normal width would work better.) It’s not a bad option though if you want a quick handwriting look; vLetter has a lot of free handwriting fonts.
Playing with this made me wonder how hard converting a TTF outline font to a stroke font for SVG would really be. Taking the centerline of the font would be one possibility, although you would have to identify that with some heuristics (maybe following the TTF outline?) Also generating a path that’s inset a bit from the outside of the bitmap would work more nicely than centering the path on the edge; that would account for the width of the pen ink. For research, a program called SFEdit can do it but it looks like all it does is do centerlines for paths (not fonts).
BTW I’m a total novice at Inkscape, but the way it handles flowed text is confusing to me. I had reasonable luck flowing text to a circle and then converting it with Axidraw’s Hershey Font extension. First I had to do Text / Convert to Text to change the type from “text flow-in-shape”. Also it only worked if the text was left justified. Center justified ended up being positioned entirely wrong.
Mike Migurski reminds me his Skeletron project solved a similar centerline problem, for maps. Code is here. He says he designed it using ideas from this paper. Hand-waving a lot, the technique is to calculate Thiessen polygons (related to Voronoi diagrams) for the roads, then calculate the center of the edges of those polygons. The flowline for the center of the road goes through those polygon centers.
Some links on automating centerline creation in Inkscape:
Wanted to give a shout-out for a great tool for working with SVG files and plotters: vpype. It’s a multifunctional tool for taking an SVG file you’re about ready to plot and then making it “better” for the plotter. Here’s an example of how I use it:
That’s a pipeline that does the following (in order)
Read my input SVG
Crop the SVG to the given rectangle.
Merge lines if points are within 0.05mm of each other. This “cleans up” the SVG and makes for faster plots with fewer, more complex paths.
Re-order loop lines so that each loop starts at a random point. This breaks up artifacts from the pen at rest blotting ink into the paper.
Sort the lines to minimize pen up travel distance. Axidraw does this too but supposedly vpype works better.
Write out the output SVG
It’s a pretty powerful tool and what it can do is confusing at first. But the docs are good. The feature overview is the best list of commands it understands grouped by theme. Beyond that check out the cookbook and the CLI reference. There’s also a handful of plugins; the one that caught my attention is occult which will emulate the masking you get if you put a filled polygon on top of other stuff in an SVG file.
vpype works by default as a command line tool. It also has a Python API and the ability to write your own plugins in Python.
Under the hood what vpype is doing is interpreting the SVG to build up geometries in memory. It’s sort of like rasterizing things on a grid, although not quite. It then uses that model to allow it to combine lines, simplify geometry, etc. Along the way it squashes all curves into collections of little short lines. (The plotter would do this anyway, so no great loss).
Bonus image: it has a fun “squiggles” filter which makes the lines not straight.
I bought myself an AxiDraw pen plotter. Inspired by the work of my friends Joshua Schachter and Michal Migurski, not to mention the wide world of #PlotterTwitter, I figured I’d take a turn at doing some pen art. It’s been a long time since I programmed any original generative art of my own and I’ve never really worked with pens and paper, so it seemed fun. Here’s my first work.
Yes, its dicks. A lot of people’s first plotter piece is small multiples of things with slight variance. But why draw lots of circles when you can draw lots of dicks? I confess I still have the sense of humor of a 12 year old. Also I like dicks. I had in mind Keith Haring or something when planning this although I’ve quickly found owning a fancy plotter and knowing some Python does not make you Keith Haring. His dicks are so charming!
Learned a lot doing this. Most of it is about the fussiness of pen on paper. Pens all have different rates of ink flow and papers have different absorbancy. I was doing my first tests with sharpie on cheap printer paper which bleeds all over the damn place; the moment the pen dwells for even half a second you get a big blob. This is a somewhat inexpensive Lamy Safari Fountain Pen, a classic beginner fountain pen. Writes like a dream; I may switch to it for ordinary writing too! Good for thin precise lines. I also bought a whole bunch of other kinds of markers and pens including some meant to simulate watercolors.
The AxiDraw is a neat device too. It’s basically a metal framework with two very high precision servos (2800 dpi!) to move the pen to any X, Y coordinates. Also a simple pen-up/down device to lift the pen off the paper or let it rest on its own weight. That’s it; no pen pressure, no paper movement. Just pen up/down and move to x, y. It comes with an Inkscape plugin that can draw any SVG file you give it, and from that you can draw pretty much any vector graphics. The SVG interpreter has some limits; no masking. There is sort of hacked on support for text fonts and for fills, although really it’s about drawing lines.
This first piece I did in PyCairo, the classic drawing library. I don’t have much love for it. It’s very confusing about when you’re working in relative vs absolute coordinates and it has some vesitgal confusing path building thing that makes drawing arcs more confusing than it has to be. The big strength of PyCairo is you can draw in high level code and then render to SVG, PDF, various raster formats.. And it rasterizes beautifully. I don’t need all of that. My plan now is to re-write my dicks thing in a lower level SVG framework, maybe svgwrite. I want something like D3 for producing SVG drawings, just a little DOM manipulation help. An alternate approach is to do everything in Shapely, make an object scene graph. Shapely has SVG rendering support.
Beyond that I have a host of other arty projects in mind. Bringing in geographic data is an obvious thing; may be time to revisit my old watershed maps, rivers, even just a simple OSM map renderer could be fun. I’m hoping to get inspired by the messiness of the ink medium, I’ve seen some neat work from other artists that really leans into the aesthetic of slightly scratchy lines of slightly bleeding ink.
One of the themes on this blog is “I want a really simple interface to databases for Python”. But then I’m never happy with the options. ORMs are too magic, Records is weird and limited, etc etc.
A friend of mine has written a new library: PugSQL. It’s inspired by Closure’s HugSQL. You write templated SQL statements in separate files, anything you want; selects, updates, etc. PugSQL wraps those so you can easily fill in the template parameters, call the SQL, and process the results as Python objects.
It seems like a good approach to me. Very little magic. Direct access to the actual SQL. You’ll probably end up writing some boring simple SQL that some ORM could have auto-generated but then again you’ll never be unpleasantly surprised, either.
Did some hair-pulling work with Javascript Promises recently. I’m calling a paginated database API (CloudKit JS), so I want to fetch N results at a time until there are no other results to fetch. In simple synchronous programming you’d do this with a while loop. But Promises can’t be reused or iterated in this way, so instead you do something that amounts to tail recursion. The Cloudkit docs have a handy example:
I use code much like this for real and it works. But it’s complicated! database.performQuery is an asynchronous method in CloudKit JS, it is a Promise. This code creates a new query promise, then chains it via .then() to some synchronous code that processes the response. The last thing the processing code does is check if there’s more results to come (the pagination API) and if so it creates a new Promise and returns it. Which causes the Promise execution framework in the browser to go to resolve that new promise next.
It feels very much like tail recursion. I get conflicting answers on whether it genuinely is recursive, in the sense of some Javascript stack or Promises chain growing larger and larger with each request. It’d be simple enough to do basic tail recursion optimization to eliminate that growth, just no idea if implementations do it.
My problem
So I’ve got code working. My problem is the moment I try to do something more complicated, I get lost. As a practical example; what if I want to inject a one second delay between each call to that performQuery() function? I can make a new promise with setTimeout() and chain it in there, but half the time I type the code to do that I get it wrong. I got lucky and it worked once and I don’t really understand why. Then try passing arbitrary parameters conveniently through the call chain; you can, but it’s hard because Promises only take one argument to pass along so you have to stuff your parameters into a new Object. And I haven’t even tried to reason about getting error handling right, although I think if you’re naive and don’t do much of anything then the default reject/catch behavior will probably work.
async/await
There’s a new hotness coming in Javascript with the async and await keywords along with async interation. Here’s another example of it in use. I haven’t ever used this stuff myself and am not sure if it works yet in browsers.
This is an unsatisfying blog post where I investigated a problem and don’t really have a solution. Honestly, most of the time I do async programming in any language I feel the same way. Python, Javascript, even select()-based C code back in the day. My model of programming computers is so heavily based on imperative execution I always feel all twisted when I program asynchronously.
I need to do a series of exercises fully in an async model and get comfortable. Either that or find a good Javascript wrapper for Promises that provides higher level components like “iterate this set of promises” and the like.
Well this is a nuisance. A lot of CloudKit requests have two different ways of signaling errors when you make Javascript calls to the iCloud API.
The request can look like it succeeded and returned a Response object of some sort. But instead of the response you want it can have the hasErrors flag set, in which case there’s a whole array of errors objects. This method is what’s shown in example docs.
The request can also just fail and the method returns a CKError object instead. This object has an isError property, also an isCKError. I’m not positive but I think this mostly catches client-side programming errors, like when I put in an integer where a string array was expected.
In neither case does the Promise reject; it resolves with some sort of error status. So for now every call to a Promise in CloudKit JS I make has right after it:
if (response.hasErrors) {
reject(response.errors[0]);
} else if (response.isError) {
reject(response);
}
I wonder if there’s a better idiom.
Dismal programming language law: no matter how many language features there are for signaling errors out of band: Exceptions, Promises rejects, etc.. Programmers will ignore those and return error values in-band instead.
I just wrote these notes up for a friend. esridump is a Python tool that will take the URL from an ESRI ArcGIS REST server and dump all the data in it to a GeoJSON file. It works by doing REST queries on the predicate “where 1=1;”, the only subtle thing is you have to paginate the requests because there’s a limit to the number of results from one query. It’s a nice tool; there are several others floating around out there like it.
Installing it is basically as simple as “pip install esridump”. It has very few dependencies, no GDAL or other GIS giant libraries. But I wrote these detailed notes for a friend of mine:
ArcGIS RES
Install Python 3.7.3. Make sure to click “Add Python 3.7 to PATH” when installing.
I finally updating my old somebits.com CSS to use a wider text box and a modern font. Goodbye, Arial 400px wide! I’ve not paid much attention the development of CSS3 font technology so this is all new to me. I’m using free fonts.
Which font?
Free, not ugly, and with decent Unicode range. I looked through this Wikipedia page and hit on several likely options: Bitstream Vera, Liberation fonts, Noto fonts, and Source Serif Pro. I decided I liked how Source Serif Pro looked best. I don’t know how great its Unicode coverage is; from what I’ve read it’s mostly western scripts. Fine for normal use, and hopefully the browser fallbacks will suffice for the occasional CJK or obscure other stuff.
Update: I just realized that Feedly uses ITC Charter, which is free. There’s also a Unicode-enhanced version from SIL called Charis. I converted their WOFF to WOFF2 using an online tool and tried it on my blog. It’s stylistically very similar to Source Serif Pro but not quite as good looking and significantly larger files, so I won’t use it.
Hosted fonts
The easiest way to use a custom font is use a hosted solution like Google Fonts or Adobe Fonts (nee Typekit). They have you include a single CSS stylesheet and then you can refer to the fonts by name in normal CSS. The problem with this is they then get tracking info on every page that uses the font, which is bad for privacy. So I’d prefer to self host.
Self hosting
First you have to download the font in the right format. Choices are EOT, TTF, OTF, WOFF, WOFF2, and SVG. This website says EOT and SVG are obsolete, and TTF and OTF are unnecessary, and that WOFF is basically a wrapper for TTF/OTF and WOFF2 is just an improvement on WOFF. Confusingly, Adobe’s distribution of Source Serif includes both “TTF WOFF” and “OTF WOFF” versions. This page says OTF is better. WOFF2 seems to be nearly universally supported so I’m going to go with that with the OTF variant. (A lot of sites still serve WOFF as well, but I think that mostly only matters to MSIE 11 at this point.)
You can get a clue how to self-host fonts by just copying what Google or Adobe serves as CSS. See Adobe, Google. You can get pretty far just by copying what they do but changing the URL. But starting from first principles...
The simplest thing that work is this little bit of CSS
This says “I’m declaring a new font-face named source-serif-pro and you can find it at this URL”. Then tell the body of the document to use that font. And it all works, done! It also does reasonable Unicode fallbacks for things that aren’t in the font. But not quite done; this font only is normal font; the browser will fake italic and bold versions (ie, ugly). This is better:
@font-face {
font-family: "source-serif-pro";
font-style: normal;
font-weight: 400;
src:url("SourceSerifPro-Regular.otf.woff2");
}
@font-face {
font-family: "source-serif-pro";
font-style: italic;
font-weight: 400;
src:url("SourceSerifPro-It.otf.woff2");
}
... versions for Bold and BoldItalic as well ...
That will let the browser use a properly designed italic font when necessary instead of just slanting the letters to the right. That really matters for bold, bold is used a lot in CSS (like headers). The key thing here is you’re expanding the options available on the source-serif-pro family, with the cost of now the browser has to download more files (100k each). In theory you can bundle all 4 variants into one file using variable fonts but I think that’s still a little bleedingedge.
There’s some advanced options too. You can tell the browser you only care about certain Unicode ranges, which may help with download sizes. You can tell the browser to preload the fonts or use local copies if the exit. You can fine tune whether it will use a system font until the real font is loaded. You can also tweak font rendering settings and kerning.
I’m working on using my Flickr export. I naively thought that working with EXIF metadata from images in Python would be easy in 2019. I was wrong. Particularly if you want to write EXIF data. I’m tentatively trying PyExifTool, a wrapper for a Perl command line program. More on that below.
PyPI has 126 packages for EXIF. But a closer look shows a lot of them are bad in various ways and there’s no one consensus package. Lots of version 0.1s, stuff that was abandoned 4 years ago, etc. PIL/Pillow has EXIF support but it’s very low level and a clunky API. Piexif looks somewhat promising as a pure Python thing but also very clunky API.
Turns out the real problem is EXIF is a mess. When we say EXIF we actually mean three separate metadata formats: EXIF itself, the older IPTC tags, and the more modern inlineed XMP tags. Some of these formats have overlapping metadata in them. EXIF itself is a real mess of a binary format. For instance the GPS location info looks more like raw data from a GPS chip than a simple WGS location. For instance it supports multiple formats for lat/lon. Want decimals? minutes? seconds? Some mix? You can write anything!
The gold standard for good EXIF+others support is ExifTool, a 15 year old Perl library / command line program. It has an active community of developers who’ve spent a long time fiddling with all the weirdness in image metadata formats and making a bulletproof tool that can read and write them. So why try to rewrite all that code in Python?
Enter smarnach’s pyexiftool and the several separately packaged versions of it on PyPI. It’s four years old and as far as I can tell there is no active fork. Fortunately the code is pretty simple.
The main thing it does is fork a single exiftool process with the -stay_open flag. That causes the Perl program to keep reading commands. The rest of the Python code is a little wrapper around the JSON api and some convenience code if all you want is to read metadata. It seems to work.
So there we go; I’m gonna be writing EXIF tags by passing command line arguments over a file descriptor to a running Perl program. It’s a kludge, but if it works I’ll take it.
Just wanted to give a shout out to noUiSlider, a nice Javascript library for building slider controls. We just used it to add a time-range slider control to Wanderings, my little location tracker. Now you can restrict what data is shown to specific date ranges. Our control looks a lot like this demo.
There’s a zillion slider controls implemented in Javascript. Most of the well known ones are 5+ years old and require jQuery. There’s some fancy new ones that require React. What I like about noUiSlider is it’s standalone, doesn’t rely on any other frameworks. It’s not tiny but it’s pretty small, about 90k uncompressed or 25k gzipped.
noUiSlider is also remarkably professional. It’s quite flexible; you can have any number of handles, linked or not. It’s straightforward to restyle. It gives off a nice collection of events when the user interacts with it. It works thoughtfully on touchscreens. And it’s all well documented! Nice library.
The one thing I haven’t figured out how to do in my app is add a nice UI for “filter to one month” for “one year”. It’d be easy enough to add buttons but the UI would be so cluttered then. Want something less obtrusive. For now we have a bunch of hotkeys defined on the main window (YQMWD for ranges, also HL to pan back and forth) but that’s pretty mysterious.
Brad and I pushed our first new release of Wanderings since the big release last January. No user visible changes, but we upgraded all the versions of third party packages and build tools we were using.
The real thing is I had to get over being whiny about webpack and npm. Right after we finished 1.0 Brad stepped in and reorganized our code to use fancy web tools. Previously we just had a big ol’ wanderings.js file we imported on every page, along with a bunch of third party minimized redistributables included one after the other in the HTML file. You know, the old school way. Brad redid everything nicely in webpack and npm so that third party modules were fetched from a repository and bundled together. Our code was refactored and then combined into the bundle. All with nice frontend scripts like “test” and “deploy” and “start development server”.
Unfortunately I don’t know anything about these fancy new fangled tools, I live or die by press-F5-in-the-browser. And it was kind of a big hump for me to get over it, learn the tools, and use them. I have a categorical problem any time someone tries to inject a “compile” or “link” phase into what should be simple interpreted code. It always slows me down. npm is very hard to love, too.
But webpack solves a lot of problems too. Managing distributing the right versions of things. Bundling them so they distribute efficiently. Minimizing the code for obfuscation + network savings. Keeping it possible to still run devel versions with source maps, etc for easy debugging.
The fancy devel server we get from webpack is pretty nice too. It seems to automagically arrange for things to recompile and reload when they change. I had a problem with this at first because our devel bundle is like 4.5 megabytes and I was running my devel server remotely, on another continent. That’s a bad idea; once I got the devel server running locally on my laptop it was much better. (We might want to split our bundle into two pieces though, a big one of third party code that seldom changes and a small one of our own code. Just to keep reload overhead down).
I’m still grumpy about some things. I’ve lost all my global variables I used to reach into to inspect the state of the running system in the console. I’m not sure I can get the Firefox debugger working at all, the source maps or something aren’t working. Chrome seems better though.
I still hate imposing any overhead in the “change code, reload, run” loop. But all this build stuff solves real problems in the Javascript ecosystem so I think it’s best to play along.
I continue to fail to use ORMs with Python. They’re just so complicated and mysterious. But maybe that’s really just SQLAlchemy and I should look elsewhere.
PeeWee popped up on my radar recently, an ORM explicitly designed to be small and simple. It looks pretty good. Also have heard a couple of people mentioning PonyORM recently. It seems far too magic.
Going even simpler, I should circle back and spend more time with requests and/or dataset. They’re not even really ORMs, just convenience wrappers for database rows, and that seems fine by me. Still bugs me they both depend on SQLAlchemy even if the actual interaction is minimal.
People put secrets in environment variables all the time. AWS keys, database credentials, etc.
But in Ye Olden Days environment variables were not secrets. At least on Ultrix 2.2, the BSD 4.2 variant I learned on in the early 90s, you could see everyone’s environment variables
Note that denying other users read permission [to your .profile] does not mean that they cannot find your PATH or any other of your environment variables. The -eaxww options to the ps command display in wide format the environment variables for all processes on the system
Linux explicitly does not do this. Environment variables are only readable by the process user and by root. Now I’m curious about the history of environment privacy. I don’t know if Linux always treated environment variables as secrets or what other Unix systems do or did. It seems like an interesting change in behavior. I’m not clear on what POSIX says either.
BTW there are many articles on the Web that say it’s dangerous to put secrets in environment variables. (Example.) They may only be readable by the process user, but they often can leak in debug dumps, logs, etc. OTOH I see a lot of people using the environment for secrets now, so maybe standards are changing.
I was using mktemp to create a file. Why was bash showing it as $’filename\r’?
Turns out, derp, SublimeText on my Windows box create the file. With Windows newlines by default. Which bash will treat as important whitespace and not strip. So if you ever see a $’\r’ in your bash -x output, that’s your damage.
The new hotness is web sites using visitors’ CPU to mine cryptocurrency. Typically without consent, often via malware, although sometimes as a disclosed alternative to ads. Fuck everything about that.
Still I was curious how this works. Mining most cryptocurrencies requires speciality hardware to be worth the bother. GPUs, at least, and in the case of Bitcoin ASICs. So I’ve been wondering how a Javascript miner would work, surely it’s 100-1000x slower than a native GPU program? Are they using WebGL?
The most popular solution for Javascript mining now is CoinHive. And they mine the Monero currency. Why? Explicitly for performance reasons. The Monero hash (Cryptonight) is something designed for CPU computing and doesn’t really run better on GPUs. So it’s a reasonable thing to do in Javascript.
BTW I found this CoinHive demo useful for playing around with a Javascript miner in my own browser. Yup, it takes 100% of all 8 of my CPU threads very easily.
(Related: the NoCoin extension is a way to protect your browser from this crap. Ad blockers will typically block them too (uBlock Origin does), but I want to see the icon specifically about whether some website is running a miner.)
Discussion on Reddit led me to this official Python benchmark site. If you fiddle the settings you can get a comparison of how various Python 3 distributions compare to Python 2 on a bunch of benchmarks.
Bars below 1.0 mean Python 3 is faster than Python 2. The different colors are different point releases of Python 3. The broad picture here is that Python 3 is generally about as fast as Python 2 or a little better. The big slower in the middle is Python startup; that’s 2-3x slower now. No other obvious pattern to me.
I’d had in my head Python 3 was generally about 20% slower. Partly because it does Unicode properly now, partly because some of the switch from collections to iterables in the core tuple and list types added slowness. But that opinion is not born out by this data.
PS: this screenshot brought to you by Firefox’s awesome screenshot tool. Not sure if it’s new to everyone or just me, but it makes saving an image of a DOM chunk of a page very easy.
I’m really glad I chose to use Dexie as my interface for IndexedDb storage in browsers.
Mostly it’s just really professionally packaged. The docs are great. The basic API is very simple to use. Where things get complicated they make right choices. Like bulkAdd() will abort if you’re inside a transaction and try to add on top of some duplicate keys unless you explicitly override that. But outside of a transaction it’ll just do its best to add data that doesn’t conflict and log a warning.
It also has nice support for schema migration. I haven’t stressed this too hard, but adding new columns works nicely and transparently for users. It has simple support for writing custom migration functions, too.
Dexie supports some fairly complex interactions with the database. All I’ve had to do is simple things and I appreciate that simple things are simple. But it looks good for doing complicated things, too.
Wanderings uses iCloud’s private databases as a backing store for data. I wanted to delete some data from them and it is terribly, terribly slow. Roughly 40ms / record.
We’re using this Javascript code to delete records:
If the data is 100 records it takes 4000-5000ms to complete. 10 records takes about 400-500ms. So much for batch deletion.
Exacerbating this we had a bug where I was trying to delete 60,000 records at once. This hangs for a very long time and then returns with an error that the operation is too big. Also there was a second bug where we were executing several requests in parallel. This does seem to work but isn’t a good idea. Chrome crashes outright (Oh, Snap) if 26 requests are running in parallel. Firefox didn’t crash but other bad things happened.
So now I’m deleting 60,000 records, 100 at a time every 5 seconds. That’ll be most of an hour.
I wanted to do some simple unit testing in a Browser context; no NodeJS. I decided to use Mocha and Chai, then found it remarkably difficult to figure out how to just get it working without a bunch of complicated setup.
I finally figured it out: demo here. It’s pretty simple really, grab the CSS and JS from a CDN, then write the tests.
Boy there’s a lot of stuff in these frameworks. Mocha + Chai is literally 26k lines of code, 820k bytes. Minified it’s more like 300k but that’s still huge. I see why folks like tape instead. I wasn’t sure tape really supports running in a browser though.
Some notes on a survey of what all I find in IndexedDB storage in Firefox. That’s something like cookies, a way for a website to store data on your computer, only in this case it’s a fancy NoSQL database. I’m using it myself and have found Firefox’s Storage Inspector unreliable and limited, so I built my own tool to look through my profile directory and tell me what it finds.
Twitter has a database called “dm_typeahead” with three tables; conversations, metadata, and users. Users has two columns, name_lowercase and screen_name. It has a version string of “20160920” and was 98304 bytes big when last vacuumed.
Smithsonian is using some SDK to create some tables about notifications, but they contain no columns at all.
The Guardian created a database named “test” with no tables at all.
So what’d I find?
A bunch of empty “test” databases, presumably testing the browser can do IndexedDB at all. This may be for detecting if the browser is in private mode.
A bunch of sites use One Signal, which I guess manages those horrible HTML5 website notifications that spam pop ups. I’m religious about never allowing that, which is probably why I have no data.
How awesome is that! And I have no idea if it’s correct and no practical way to test it. I’m trusting Favic-o-Matic here. I tried reading docs about what to do online but every single website says something different. And who knows; maybe Apple will innovate with a new 79x79 size next week. (To be fair, Favic-o-Matic does offer the option to have fewer sizes; 16 / 32 / 144 / 152 is the minimal set.)
The original favicon standard wasn’t so bad. Nothing in the HTML at all, and a single /favicon.ico file in your root directory. That format was weird and semi-proprietary but it had the advantage it could hold multiple resolutions in a single file. Simple and done.
Then Apple screwed it up by starting to fetch random weird URLs on the website for its precious iOS icons. Then webmasters complained and so this linking standard started. Apple went overboard in supporting every single possible pixel-perfect resolution. Then Microsoft decided that was neat and added their own new incompatible formats for the stupid Start menu tiles no one uses anyway. And here we are.
Really want I want is to publish a single reasonable image, maybe 256x256, and just let the desktop clients auto-scale them. Yeah it won’t be pixel perfect but it’s not like I’m redrawing these icons at every size anyway. Either that or modernize the old favicon.ico idea so a single file has all the icons. A zip container would do nicely.
I’m fond of testing my webapps in porn mode (aka incognito mode, private browsing, etc.) It’s a very convenient way to test a webapp starting from a blank slate.
I just finished a short project I was working on, an analysis of data from League of Legends about how people are using the new rune system the game just introduced. The report is here and speaks for itself; writing here to talk about how I wrote this up. For context the project consisted of scraping about 250 web pages off a site, parsing them, stuffing data into a database, then analyzing it for patterns.
I decided to do this project as a purely Jupyter notebook project. In the past I’ve used notebooks frequently for data exploration but seldom as my full workflow. In particular it’s not clear notebooks are well suited for production scripts like “scrape this website” but I decided to do it anyway, with some success.
I wish there were a way to hide cells. I want to keep some code around but I don’t want it to show in whatever report I’m publishing.
I hid the code entirely so civilians don’t get overwhelmed. I did this with a “toggle code” button borrowed from here.
I wish notebooks had explicit named checkins. I find the commit cycle of git is good discipline for getting me to do only one thing at a time. There’s a Checkpoint feature in notebooks which is similar but it doesn’t prompt you for a comment so I never use it.
It seems worth noting that my virtualenv for the project was 550MB. Pandas is big but I wanted it. Somehow I ended up with all of scipy even though I just wanted a few colormaps from Seaborn.
Scraper
I wrote the scraper with BeautifulSoup. As noted before there’s a nice addon for Jupyter that gives notebook previews of scraped data. Interactively working towards robust scrapers was really nice in a notebook. I ended up creating a main loop to scrape all the pages I needed and write them to a simple shelf database. The full scrape only took a few minutes so I just ran it interactively; this wouldn’t work nearly as well for a run that takes hours or is perpetual. One clever thing I did was create a new shelf database for each run, so I could keep old data easily.
Data processor and database creator
My second notebook loaded the scraped data from a shelf and processed it down to a more query-friendly SQLite database. Like shelf files I kept one timestamped database per run so I could easily go back to old data. Interactive development for this part was nice, particularly being able to do some very simple sanity check reports along the way.
I used the dataset module to create the database for me. It’s quite nice; create a list of dicts and it just makes a schema from them and writes the data, no fuss.
Ad hoc queries
For my primary data exploration I used ipython-sql to run SQL code directly as Notebook cells, no Python requires. This was my favorite use of notebooks and no surprise, it’s exactly the kind of work Jupyter is for. Write query, see data as HTML table, done. ipython-sql allows you to mix in Python code, you can capture the results of queries as result sets and do things with them. I started trying to get fancy with that and realized that wasn’t working very well; better to stick to mostly SQL. Also the presentation options are very limited, once I started thinking about sharing this data with other people I wanted to give it more polish.
Final report
For my final report I made a new notebook using Pandas DataFrames with sql queries developed in the ad hoc notebook. Mostly used Pandas as a better table presenter; it makes it easy to round off numbers to 2 digits or color data cells based on their contents. Also I ended up using Pandas Python code to manipulate my data after it came from the database, convolutions that would be awkward to do with SQL queries. This all worked fairly well but in retrospect part of me thinks I should have gone with styling JSON blobs using D3 instead. That’s more work though.
The result of this sheet is the report itself and while it’s a fine Notebook it’s not a very nice deliverable for my target audience. LoL players are used to infographics like this, not boring tables. I’m uninterested in doing that kind of presentation though, so I stopped there.
Update: I posted this to Reddit and got on the front page, as much attention as I expect for a project like this. OTOH most of the discussion doesn’t seem informed by the data I presented. Good ol’ Internet people. Lesson for me in the value of presenting simple conclusions, not data.
Following up on an earlier post wanting to be able to do database things simpler, some nice results.
I’m liking dataset as a quick way to write data from Python into a database. Basically you just insert dicts into a table; it takes care of generating a schema, selecting types for things, etc. I’m really liking it for writing data to databases. It helps read data too! But it doesn’t do much other than wrap rows in dicts which is nice, but I wanted more. (It also has support for fancy Python queries, but I just want raw SQL).
For reading data I’m liking ipython-sql. It adds a nice Jupyter interface on top of a raw SQL repl like that provided by sqlite or psql. It’s quite simple to install. And since it’s all implemented as an IPython magic you can mix it in with Python code in your notebook. I’m mostly just using it as a way to display SQL results as HTML tables; simple, but very useful. It has some support for fancier stuff like plotting and exporting the result sets into Python objects, Pandas DataFrames, and CSV files.
I hit a funny bug with the Python shelve module. I’d write a shelf database, then try to open it again and get this error:
db = shelve.open('foo.db')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/shelve.py", line 243, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "/usr/lib/python3.6/shelve.py", line 227, in __init__
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
File "/usr/lib/python3.6/dbm/__init__.py", line 88, in open
raise error[0]("db type could not be determined")
dbm.error: db type could not be determined
Turns out this is my mistake. I created the shelf with code like this:
db = shelve.open('foo')
This creates a file named foo.db, a Berkeley DB file. And then I tried to open it:
db = shelve.open('foo.db')
See the error? The shelve module is appending the .db for me; I shouldn’t have added it myself to the filename. Simple enough mistake I made, confusing error results. It’d be nicer if the code threw an error or opened a new database file named foo.db.db, but instead you get this confusing error.
Python 3.6.3 on Ubuntu 16.04, which I think is libdb 5.3.
Note this error is different from an often-referenced bug in older Pythons not recognizing GDBM databases consistently (issue 13007).
This isn’t very complicated but it’s nice: a demo of using ipython-beautifulsoup for an interactive Jupyter session to scrape HTML web pages. This looks better in my Jupyter session btw, the GitHub presentation of the notebook isn’t as nice as the interactive tool.
I’m using IndexedDB for permanent storage for a webapp. It’s pretty nice; a NoSQL transactional database in your browser! And all built with asynchronous calls. The API is notoriously confusing so I’m using Dexie as my front end. It’s very friendly and I like the way it uses Promises so directly. It also has a smart story about schema versioning. (See also LocalForage.) Anyway, some notes:
How much disk your data uses is a mystery. I have a database with 1873 records that consist of an integer primary key, an integer timestamp, and two doubles. Let’s call it 64 bits each, so that’s 32 bytes a record. OTOH on disk it’s taking 464k, or 254 bytes a record. There’s no Javascript API for asking how much space you’re using or what your quota is.
Storage limits are also confusing. Firefox has no upper bound but will use up to 50% of your disk’s free space and then start evicting stuff on an LRU basis. Chrome also has no fixed limit but may be based on the user’s hard drive size. Older references say a strict 5MB limit but that seems to be much bigger now. For a desktop user it seems likely to be gigabytes.
Firefox implements IndexedDB as sqlite files, but the sqlite schema on disk isn’t anything like my application’s schema. There’s tables named “database” and “index_data” and “object_store”, so I’m guessing they’re using sqlite more as a structured file than the actual database.
Neat little tool: gzthermal-web, which visualizes the efficiency of compression from gzip. Each byte is colored depending on how well it compresses; dark blue for 1 bit up to red for 9 bits. It’s a wrapper for the gzthermal tool, as discussed on Hacker News and in this sort of odd article. (Undocumented feature; append &w=1 for a wider image.)
Here’s my weblog visualized with it, sorry for the giant long image. It looks better if you view the image alone shrunk-to-fit.
Structure is clear. The bright yellow parts are inlined PNG images which won’t gzip very well since they’re already compressed. The dark blue chunk at the front is my calendar, a bunch of stupidly repeated HTML. Blog posts are the motley blue/green patches separated by the dark blue of the HTML boilerplate between blog entries.
I’m not exactly sure how I’d act on this information. But it looks neat!
I program in 2006-era Javascript. But recently I started doing some more modern stuff. Arrow functions, those are great! And easy. Promises! Those are great. And confusing. Here’s some notes about what I’ve learned about Promises.
Warning: I’m a n00b here, some of this info could be wrong.
The best single guide to Promises I’ve read is Google’s. The folksy tone at the start is annoying but keep reading. MDN also has a basic guide that’s useful. You’ll want the MDN reference too.
The key thing no one explains is that when you create a Promise, it is automatically added to the event loop and will be executed by the browser when it has time. You do not have to schedule a promise or create your own event loop, like you do in Python async programming. It’s all automagic.
The exciting thing about Promises compared to other async frameworks is the .then() function, the ability to chain a second promise onto a first one. “First do this thing asynchronously, then when it is completed start doing this second thing. And make this chunk of two things itself a Promise so it runs asynchronously”.
You can also combine Promises with all() and race() but I don’t see it being used that way very often.
The other neat thing about Promises is it has an API for error handling. I’ve never used this for real (I’m an optimist programmer), so I can’t say more about it, but it seems important.
A Promise is a Javascript function that runs like any other function, but will yield control and allow other things to run when it’s blocking on network IO. (At least I think that’s right, I’m not 100% confident.)
When I’m sloppy I think of a Promise as basically a Thread. An independent unit of execution that runs in parallel with everything else. That’s not really true; Promises aren’t Threads, in particular there’s no interrupting multitasking. There is co-operative multi-tasking though so as soon as your Promise blocks waiting for network or whatever, something else will happen. Specifically the browser’s event loop will keep running and the page will be responsive, the key reason to be using async programming at all.
It’s OK to create Promises that never invoke their resolve or reject functions. That means the Promise won’t ever have a return value to pass on to the next Promise in the then chain, but that’s OK. Maybe you wanted the side effects or something. It’s probably not a good idea though, the promise will stay in pending state forever and nothing chained after it with then() or whatever will ever run.
It’s also OK to mix Promises and events for different styles of asynchronous programming. Promise chains let you program in a more or less declarative way: do A then B then C. But it can be tricky to arrange your control flow for a whole page program to make sense this way. Events are nice because the publisher of the event doens’t need to know anything about who might be consuming it somewhere else. It’s fine to have a Promise post an event that something else listens to and acts on asynchronously.
This code is laughably simple, but I found it useful when learning about Promises:
var state = 1;
console.log("starting");
console.log(state);
p1 = new Promise((resolve, reject) => {
console.log("p1 created");
setTimeout(function() {
console.log("p1 finished");
state = 2;
resolve();
}, 1000);
});
console.log("made p1");
console.log(state);
p1.then(function() { console.log(state); });
console.log("made p1.then");
I’m using Google Cloud’s Postgres implementation. I thought I had it all working except my AppEngine server couldn’t connect to it in production. For dev work I’d just authorized my home IP address and connected directly to it from my dev box. But that didn’t work in production.
Turns out there’s complex docs for connection to Google Cloud SQL. Here’s what I had to do when following those instructions. (This was made significantly more different by intermittent outages either at Google or in my network connection; lots of failures and timeouts.)
Download cloud_sql_proxy to my dev box
Get some application default credentials on my dev box
gcloud auth application-default login
This does some OAuth thing with my Google account. In retrospect I have no idea how I was able to gcloud deploy, etc before doing this.
Authorize my home IP address to connect to the SQL instance via the cloud console.
Run the gcloud_sql_proxy and have it listen on 127.0.0.1:6432 (port 5432 is busy with my own Postgres instance.)
./cloud_sql_proxy -instances=projectname:us-central1:dbhost=tcp:6432
Note the instance connection name has three parts separated by colons. “gcloud sql instances list” does not show you names in this format, but the console does in the “Instance details” page for that specific SQL server.
Test I can connect to the database via local proxy
psql postgresql://postgres:password@127.0.0.1:6432/postgres
The proxy will log a line about the connection.
Add the beta_settings / cloud_sql_instance stuff to my app.yaml. I have no idea what this does or if it’s necessary, but the docs said I should.
In my dev environment, configure my code to connect to its database via 127.0.0.1:6432, so it uses the proxy. It’s not clear the proxy is necessary. I can connect directly to the database machine via IP address. I guess it’s nice in that the proxy is configured just with the instance connection string, not an IP address.
In prod configure my code to connect to
postgresql://postgres:{password}@/{dbName}?host=/cloudsql/projectname:us-central1:dbhost
I have no idea what this ?host= argument does or why it works. Is this a standard thing or did Google fiddle with its Postgres drivers somehow?
That’s more or less the process described in Google’s docs, but it took me an hour of trial and error to make it work.
Update: I asked Stack Overflow about how cloud SQL connections worked and got a very quick answer from a Google Cloud engineer named Vadim. “It’s a UNIX socket backed by Cloud SQL Proxy”.
In detail, /cloudsql/projectname:us-central1:dbhost is a Unix domain socket, not a TCP socket. There’s an actual file (or directory?) named /cloudsql/projectname:us-central1:dbhost in the Unix machine’s filesystem. The ability to connect to Unix domain sockets with a special host= parameter is implemented in libpq, the Postgres connection library. The Cloud SQL Proxy code talks about how it can proxy from a Unix domain socket.
It’s a nice optimization; it’s silly to use a TCP/IP stack for passing data between two processes on the same computer. I assume Linux has a highly optimized localhost driver, even so Unix domain sockets should be better. This discussion suggests 1.5-2x the throughput.
I continue to look for things that make working with databases simpler in Python. I keep doing projects where I end up dropping down to raw SQL, with awkward syntax for querying rows and bespoke one-off code for updating data in the database. The Python is messy but I like being able to use SQL in its full glory.
I’ve tried using SQLAlchemy a couple of times and have a hard time loving it. ORMs are a bad idea in general and SQLAlchemy is very complicated and magic. For a schema with 20+ tables and a lot of complex interactions it makes sense, but for a small project where you just want something more sane than low level DBAPI...
For my current project I’m trying to use plain psycopg2 and its NamedTupleCursor. It’s not awesome, but at least it gives you named access to the rows from the DB. So it makes reading from the database a little nicer, but does nothing for writing. It’s Postgres only.
Along these lines is the records library. It also gives sane access to results from queries; either as dicts or named tuples. Result sets also have nice export functions like “write to CSV” or “make into a Pandas DataFrame”. It doesn’t really do much for writing data, just querying, so it’s simple and small.
dataset is an effort to do even more. I love their tag line: “Because managing databases in Python should be as simple as reading and writing JSON files.” Amen! There’s a lot more going on in dataset than records. It’s more like an ORM-lite and contains support for creating schema, automatic upserts, complex queries without Python, ... It doesn’t have the export functions records has, but it does have a lot of thought for simple queries and updates. I’d have to actually use it for something to see if it’s sensible or if ORM-lite is an even worse idea than a full ORM.
Both records and dataset depend on SQLAlchemy, that turned me off at first. But they’re both mostly using it as a way to support multiple database types. In theory the Python DBAPI standard should be enough, but in practice it sucks enough I understand why they’d build on SQLAlchemy instead. With records you can mostly ignore that SQLAlchemy is there, but dataset exposes it more in the query system.
I wonder if some other programming environment has a much nicer database interface. The Microsoft world has LINQ, but that seems to have all the problems of other ORMs. I wonder if the R folks have a really nice way to work with databases, or maybe even Pandas.
Now that I have access to Python 3.6 I’m really enjoying the new PEP 498 format strings. Python has tried a bunch of different ways to format strings, from good ol’ %s notation to Template strings to str.format. They all seemed awkward to me because the thing you were substituting in was way far away from the string itself. Now you just embed a little python code right in the string to be formatted, maybe with a bit of presentation like how many digits to display. Done!
It’s pretty powerful under the hood. check out this example:
>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%b %d, %Y}" # using date format specifier
'January 27, 2017'
The format string is using the datetime-specific codes like %Y. Behind the scenes it’s calling the format() built-in which in turn can defer to the __format__() function on the object. In practice I suspect you can mostly not worry about this too much other than using basic floating point precision stuff.
I’m doing a new geo-project, a GPS tracker sort of thing. My database is very simple, just a Users table and a Locations table holding points. But I figured I’d front-load the work and use SQLAlchemy and Alembic and PostGIS and everything right now, not pay the pain of migrating later when I realize I need the fancier stuff.
Only SQLAlchemy doesn’t support PostGIS. GeoAlchemy2 does though. After an hour with it I can’t decide if it’s good or bad. It seems very simple.
In GeoAlchemy2 all geodata is represented in Python by just a few types; Geometry, Geography, Raster. You can’t do much with those things other than get the WKB or WKT for them. They’re not Points or Polygons or something, there’s no Python code for working with the shapes. You can pass them back to PostGIS though, to call functions like ST_Area to have PostGIS do a calculation. Requires a database round trip though. Alternately you can also convert them to Shapely shapes, use that excellent GIS library to do work in Python.
I guess that’s a reasonable compromise; GeoAlchemy2 is really just bridging to SQL, they’re not going to implement their own GEOS equivalent. It also has spatial functions declared in a SQLAlchemy-friendly way you so you can use SQLAlchemy syntax to do your work. That’s kinda neat.
Still I’m looking at a lot of third party Python code: SQLAlchemy, Shapely, GeoAlchemy, Alembic. All to manage a database with two tables and nothing more complex than a list of points. I may blow it all off and go to raw SQL. OTOH I may end up regretting that choice in a few months if I want to do more complex things.
Trying to figure out how to generate actual heatmaps for a bunch of geopoints. The usual hack is to draw blurry dots at 10% opacity and let them overlap. I want the real deal. The Sethoscope tool works in Python, but is pretty slow, see example below. Mourner at Mapbox is working on a WebGL thing.
The hard part here is heatmaps aren’t scale invariant; you need to render it differently depending on the scale the user is zoomed too. Realistically that means it needs to be in browser Javascript, and therefore fast. Maybe GL is necessary.
I’m writing some Twitter API code. A few lessons learned in using the tweepy library.
The error handling is not awesome. All API errors throw tweepy.error.TweepError, which is fine, but that object has no structure. The docs have some stuff about getting codes that seems outdated. In the code there’s an api_code field , but it’s set to None. I’m doing stuff like e.reason.endswith(“401”) to detect the 401 error code Twitter throws for protected users. (This is also the code Twitter throws for an invalid token, so that’s not great.)
The rate limiting handling is pretty good. In particular there’s a wait_on_rate_limit option that is pretty handy for simply waiting for a rate limit to expire.
When paging through user_timeline the default fetch size is only 20 tweets. You can instantly get 10x the effective calls by bumping up to count=200.
Twitter’s rate limits are confusing. Nominally it’s “calls per 15 minutes” but there must be some sort of grace period or something built in because sometimes you get more calls than that. There’s a nice rate_limit_status API call that is very helpful but is sometimes out of date; in particular I’ve seen reset times that are now in the past, so apparently my limit reset (and calls are working) but the status call doesn’t tell me that. Anyway, here’s some Q&D Python code to print out which API calls you’re currently at less than maximum on.
r = twapi.rate_limit_status()
now = time.time()
for resource in r["resources"]:
for name, status in r["resources"][resource].items():
if status['remaining'] != status['limit']:
print ("%4d of %4d left, reset in %ds %s" % (status['remaining'], status['limit'], status['reset'] - now, name))
On the heels of my post about simple persistence I decided to give the SQLAlchemy ORM a try. I’ve spent a few hours with it and liked it. Here’s some notes on what I learned.
I’m not a huge fan of ORMs; they’re complicated and it’s very easy to write code that is either broken or has huge performance problems. Relational databases are not object systems, trying to mix the two models is always problematic. OTOH an ORM can be convenient.
So far I like SQLAlchemy. I particularly like its idea that it is there to help with your database, not enforce structure on your database. It’s quite flexible and can be adapted to most (all?) schemas. I also like that it’s relatively straightforward. For instance there’s little caching of objects, pretty much any call that might require a database query will just go ahead and do that query. That makes for potentially inefficient code, but then it also makes it clear and unmagic and avoids a lot of hard-to-find bugs. One can always add caching but it’s up to you to manage it.
I also particularly like the excellent SQL tracing; just add echo=True to the session and you get a nice clean log of the SQL being executed. Makes it easy to understand what is happening and also think about performance. See also preventing lazy loading.
What I don’t like is the Python code magic in SQLAlchemy. The way you create SQL queries with Python operators like == is built out of some operator overloading that is very strange. Also the model classes you create (one per table) have a huge amount of magic in them so that when you reference something simple like User.name what’s really going on is a bunch of code with side effects, including possible SQL queries. When it all works it makes the code look simple, but in my experience this kind of hidden stuff can get you in trouble. But then again ORMs are all about doing ill-advised things marrying object oriented code to relational data, so might as well use some magic to make it look nicer.
Testing
I keep hoping to find an ORM that has first class support for mock objects for unit testing. So I can write all my higher level tests without any database, just mock objects generated by the ORM itself. No one seems to do this though, either because it’s hard or because it’s a bad idea to fake out such a key component of your software. So instead everyone uses a special test database and some combination of test fixtures and transaction rollbacks to manage it.
A lot of SQLAlchemy testing examples use pytest, in part because its fixture support is so good. So I’m using pytest for the first time and I like it.
sqlite’s in-memory databases are great for a fast test database. But only use this if you intend to deploy to sqlite; you must test against the same database you are using in production.
The asphalt project has testing patterns that I ended up cribbing from. Right now I’ve got it setting up a transaction for every single test whether it uses a dbsession or not, I should probably fix that. Note the listener for after_rollback events to handle application rollbacks, no other example I’ve seen is doing that.
More ideas of fixture patterns: this blog post, this book chapter. The latter also has an idea on mocking out the database connection itself to return fake formatted data instead of using a test database.
pytest-sqlalchemy is a resuable set of fixtures. It looks OK but pretty simple and the project is inactive. (Maybe it doesn’t need activity!)
factory_boy is a test fixture library with specific support for ORMs including SQLAlchemy. Alternative to pytest fixtures, I guess.
Alembic schema migrations
SQLAlchemy does not come with any support for schema migrations. Alembic seems to be the consensus choice for migrations. It’s only about half-automated, you’re expected to be reviewing and editing scripts. Which seems reasonable enough. One nice thing about Alembic is you can bring it in on a SQLAlchemy project that already exists, you don’t have to start from the beginning with it.
A few notes:
If your code isn’t in a Python package and just has simple “import model” style imports, you can fix up Alembic’s import by adding your source directory to PYTHONPATH. Or see the discussion for editing env.py
When you first set up Alembic you probably already have a schema in place. I decided to generate an empty migration to mark this existing schema. You still have to apply this migration so Alembic know’s what’s going on, by running “alembic upgrade head”.
There’s a cookbook for having Alembic history going back to an empty database.
What’s an easy way to build a Python app that grabs data from somewhere every few minutes, persists it, and then does some analysis of it?
I’m building a new thing that gets some data from Tweets and stores it. The main loop is downloading new tweets for a group of users and storing details of those tweets. It’s not very complicated. Structurally it’s similar to my lolslackbot project.
And I’m building it the same bad way. Persistence via sqlite with hand-rolled SQL statements. This is tedious, error prone, and makes upgrading / changing things difficult. Testing is also a huge PITA.
Is there some modern alternative that’s better?
My first thought is to at least use some sort of ORM. Django or SQLAlchemy, presumably. I’ve done a little Django and it’s hard to love it. Also ORMs cause problems, although maybe not at the small scale I’m working at.
I’m wondering if there’s some other fancier / funkier persistence system I should consider. I kind of want the simplicity and flexibility that an object database or maybe a NoSQL system promises. But those don’t seem to work out well in practice.
tl;dr: if you’re writing new Twitter API code, be sure you’re requesting extended tweets.
Boy am I out of touch. Twitter did a major API change over a year ago to better support modern tweets that don’t really fit in 140 characters. I stumbled into this while trying to use the API to get the URLs for this tweet. My old code mostly worked but this tweet is long enough to trigger the need for extended tweets. My old code was seeing a URL for the tweet it was in reply to and not the bendbulletin.com URL.
The clue was that the tweet object also had “truncated: true” set on it. What is that? Happily I found this discussion which explained about extended tweets. Twitter also documented this thoroughly last year, it’s explained well in this document.
By default the Twitter API still returns “compatibility tweets” which strictly fit in 140 characters. And in other ways are pretty broken, or at least incomplete. You have to add a tweet_mode=extended to your request URL to get the new extended format. Just to complicate things this new format has some changes, most notably there is no more “text” field. Now it’s called “full_text”. There’s also some funky third format for streaming and Gnip APIs that has both formats in a single message.
I fixed my Tweepy code by adding tweet_mode=’extended’ to the Cursor constructor.
I can’t see any reason any new code shouldn’t immediately switch to using extended tweets forever and always. It’s a shame Twitter didn’t go with a version numbering scheme to change things like this in a neater way, although versions have problems too.
While I’m here, two grumbles about the Twitter API:
Twitter’s own web client no longer is using the JSON API for everything, some stuff is pre-rendered. This means you can’t just use their web app to crib examples of API calls from.
Twitter’s API console for interactive testing of requests is kind of nice. But they don’t format the JSON responses in a useful way! You just get one long-ass line of text you have to paste into a prettifier to make sense of.
This Reddit discussion had me looking at a couple of metaprogramming tricks used in Python code.
The standard library’s namedtuple type is generated on the fly at runtime. When a new namedtuple is created the library generates it from a template string. It fills out the template with the necessary details and then passes the class definition to exec(). Exciting! But relatively straightforward and easy to understand. (Except for that extra bit to support pickling; yuck.)
pytest is an alternative unit testing library that has you just using the assert statement everywhere, no library functions. To report test failures in a nice way, it does some dark magic:
Reporting details about a failing assertion is achieved by rewriting assert statements before they are run. ... pytest rewrites test modules on import by using an import hook to write new pyc files
I haven’t read the pytest code but from the way that’s written my impression is they’re inspecting compiled bytecode and rewriting the assert statements to instrument them. That sounds a little scary, in particular if it fails it must be completely confusing. They do warn you that “if you are messing with import yourself, the import hook may interfere”. Update here’s a description of the code rewriting as of 2011.
That second technique reminds me a bit of the way that Protovis rewrote Javascript at load time so you could use more modern Javascript syntax than the browser supported. Mike abandoned that idea in D3, I think because it made things too complicated.
I want to write a program using the long-suffering Twitter API. There’s a zillion Python options, here’s what I found. I used the most recent PyPI release date as my primary criteria, because I want something actively maintained.
Of course release age isn’t everything. All four libraries linked above have similar APIs for doing simple things. I believe all four now support the streaming API too. On a quick glance tweepy and python-twitter have the most reassuring test suites.
I picked tweepy to start with because it has the most recent recommendations on /r/python. Also there’s still activity on GitHub, even if no recent releases. So far so good.
I’m on a quest to clean up my music library. I decided to give up and make all my music filenames ASCII; no µ-Ziq, no Sigur Rós, no préludes. I feel bad but after 10 years of struggles I still occasionally run into problems with Unicode filenames. Also most music players are grabbing the display info from metadata tags anyway, the filenames don’t matter so much.
The find range names any character outside 0x20 to 0x7f. The LC_ALL setting is presumably to disable any proper text processing. Ie: bytes, not characters.
The bigger project here is the music library grooming. I had this all locked down in 2008 or so when almost all my music was ripped by a service. But since then I’ve acquired a bunch of music of uncertain provenance with all sorts of random tags. I think it was when I discovered I had a Genre named “drownstep” I realized it was time to clean things up.
I’ve decided to stop working on lolslackbot, my social project for League of Legends players who use Slack or Discord. I wrote it originally for a few friends, then slowly expanded it to a few hundred users. But I’ve never put the work in to make it a consumer product and now am not motivated to do it.
The main feature missing is any sort of web interface so people could sign up for themselves. I’ve been maintaining it by hand with database update scripts, doing ~30 minutes of one-off work every few weeks instead of one focussed month-long engineering project. This blog is full of bold plans to port the whole thing to Django and get going on a web interface, but I never did it. Too much product work I don’t really know how to do well, designing interactive web UI. Hell, I don’t even have a proper name for the project.
Also some deeper technical problems. The Django port seems doable but requires database schema changes, specifically in how many-to-many relations work. And I got part of my core schema wrong, an assumption that an individual only belongs to one group. Fixing that would require redoing pretty much all the tests and half the business logic. Also at some point I’d have to migrate from sqlite to Postgres and that doesn’t sound like fun at all. In retrospect it’s too bad I didn’t start with Postgres+Django, but that seemed complicated at the beginning when I was thinking of this as just a cron job.
My real reason for lack of enthusiasm is the market. I like games and I like the idea of making game playing more social. But League of Legends is a hard community to build humble tools for. Most of the energy there is to highly polished and well marketed sites like LolKing and I’m just not that ambitious. There’s not much money in it (Riot’s API requires you don’t charge for services) and not a lot of love either. Me and my gaming buddies are on a bit of a LoL break too, which makes it harder to stay personally motivated. I’m also bummed that Riot hasn’t done anything more with Clubs, their social feature, my hope was to springboard off of that to build out the bot.
I did get some data from the last user population of Learning Fives, a cohort of ~80 people playing games together for a few weeks. 50% said they found it useful, 20% said it wasn’t, and 30% didn’t know what it was (despite seeing it in their channel). Not sure what conclusion to draw from that.
Anyway it’s a weight off my mind to just say I’m not going to do further work on this, at least for now. Truthfully my mind is on political work right now, I’d really like to do some sort of progressive activism combining data processing and GIS. (I’m following Mike’s work on redistricting closely.) To the extent I do anything for games it’s about time to revisit Logs of Lag, which 2.5 years later is still running just fine and uniquely useful. But I have some bugs to fix and maybe some improvements to make.
I have some census data in a fixed width format I’d like to parse. Stuff like “columns 23-26 are the year in 4 digit form”. It’s easy enough to ad hoc parse this with string slicing. But by the time you handle naming, and type conversion, and stripping padding, and validation, etc etc you end up with a fair amount of code. You can parse CSV with just string split too, but anyone sane uses the CSV module. Is there a good fixed width module?
Not that I could find. I gave up and just did the ad hoc thing.
I thought FixedWidth was a candidate but after 20 minutes trying it, gave up on it. There’s packaging problems and the docs are poor. The tests are incomplete. The API is weird and seems more designed for emitting fixed width than parsing it. The final reason I gave up is it seems to require you specify a full schema; you can’t parse columns 99-103 unless you’ve said what to do with columns 1-98 forst. That was a nuisance.
The other option I found was Pandas read_fwf. I didn’t try it because Pandas is overkill for my project. But I know from CSV work that DataFrame is really nice, and the Pandas CSV module is quite comprehensive. I also know that even after parsing with read_csv you still have to do a lot of work to get it into a clean DataFrame. I’d definitely look into using this for more serious work.
Related question: are there standard metadata descriptions for fixed width formats? The census data has this thing called data dictionaries that are clearly meant to be parseable. But they’re in at least two formats right on the site. I feel like I’ve seen other government records with similar metadata descriptions.
The concept of merging changes is central to modern source code control. Specifically the technology of a three way merge, like diff3, which allows two different developers to change the same file and then reconcile their changes together. In the bad old days before we had good merge tools locking files when editing them was common practice. “Yeah I’ll be done in about three days, then you can do your work”. The key insight of CVS in 1990 (and others) was it was OK to let people work on the same thing at the same time if you could reconcile any conflicts later.
So where did the idea of three way merging come from? The oldest code I’ve found is diff3 from V7 Unix, written by Doug McIlroy and dated January 1979.
Wikipedia doesn’t have any history for diff3, but the entry for diff has helpful history on the basic two-way diff saying it goes back to the early 70s, again by McIlroy, based on ideas from other computer scientists. There’s a short technical paper from 1976 about diff, but it doesn’t mention three way diffs.
That same diff page has an intriguing reference
Diff3 compares one file against two other files. It was originally developed by Paul Jensen to reconcile changes made by two people editing a common source. It is also used internally by many revision control systems for merging.
Unfortunately I can’t figure out who this Paul Jensen would be. There’s no citation. The text was in Wikipedia way back in 2004, added by someone from the University of Vermont while fleshing out the history section. But I couldn’t learn anything more.
The use of three way merge in version control dates back to at least 1985, where it’s mentioned in Tichy’s paper on RCS. SCCS dates back to 1972, but I didn’t look into the history of its merge tools. (A 1975 articleseemed to say merging was dangerous.)
(Surely there are plenty of people alive today who have personal knowledge of the answer to my question, but I’m too shy to bother them with my idle curiosity.)
Big update with authoritative info
My old Google pal Dan Bentley was kind enough to ask his father (a former Bell Labs person) to ask Doug McIlroy himself about the history of diff3. Here’s the reply Doug wrote, edited a bit:
Paul Jensen’s role was to say, “I’ve wanted a program that ...” As far as I know he never made one. But Paul’s nudge was more than sufficient to spur the creation of a candidate program for the purpose. Is it good enough? I don’t know; it strays from an important Unix lesson: programs tend to be better if their authors use them.
There’s an obvious 3D analog for the 2D longest-common-subsequence dynamic program; and the improvements discovered by Harold Stone, Hunt/Szymanski (Harry Hunt, not my coauthor) and Gene Myers likely have analogs too. Whether I considered such–or even thought of them–at the time I can’t remember. Diff3 works by combining results of 2D diffs. This keeps it at O(n^2) worst case for two sequences of length n vis a vis O(n^3) for a true LCS of three.
I’m curious about where Wikipedia learned of Jensen’s role in diff3, for I can’t think of any description of diff3 other than Unix man pages.
Paul was (and still is) a creative type from a development department, who took a sabbatical in 1127. Paul moved on to the Denver Labs, then set up shop in Boulder, http://agileimage.com.
The details of the output report would be mine; such things don’t get worked out in corridor conversations.
Presumably diff3 has been reimplemented out from under Unix licensing, but if it still has that name, then it has proved Paul’s instinct right. And it gratifyingly proves me wrong in having thought that diff3 “persists mainly as a curiosity”.
‘I’m flattered, but must point out that diff was just one of a sequence of more capable and robust versions of proof(1), which Mike Lesk contributed to Unix v3. It, in turn, copied a program written by Steve Johnson before Unix and general consciousness of software tools. Credit must also go to several people who studied and created algorithms for the “longest common subsequence” problem: Harold Stone (who invented the diff algorithm at a blackboard during a one-day visit to Bell Labs), Dan Hirschberg, Tom Szymanksi, Al Aho, and Jeff Ullman.
For a legal case in which I served as an expert witness, I found several examples of diff-type programs developed in the late 1960s specifically for preparing critical editions of ancient documents. However, Steve Johnson’s unpublished program from the same era appears to be the first that was inspired as a general tool, and thus as “social software”.’
Awake early I read this interesting blog post about making a very fast modern website. Lots of good stuff in there, like React alternatives that are lighter weight, avoiding polyfill overhead for modern browsers, the value of server side rendering, etc. Also two things that were entirely new to me: “Progressive web apps” and “Service Workers”. Also new-to-me: Google’s web fundamentals instructional material.
Progressive web app is the buzzword for a web page that works like a little application. Like Gmail in the days of yore, or Google Docs, or any modern / complex site like Twitter or Facebook or whatever. Or my own single page apps like WindHistory and LogsOfLag. Web apps are nothing new, but the “progressive” is meant to suggest a site that works fast even on mobile devices with slow and unreliable networking. Key ideas are rendering quickly and handling unreliable networks intelligently. They also have a neat tool called Lighthouse that audits a web app for progressiveness. A lot of what it checks for is mom-and-apple-pie, deferring script loads etc.
But Service Workers are the key magic. They are “a programmable network proxy, allowing you to control how network requests from your page are handled”. Basically it’s a background Javascript thread running asynchronously doing all the network for your web app. The web app page installs a service worker once the first time the site is loaded. Then it lives in the background doing things for your app like loading resources, receiving push notifications, synchronizing data to the server, etc. It communicates asynchronously via messages to the Javascript in the browser page.
It sounds pretty powerful. Basically it gives the developer control over the browser’s network, how stuff is cached and when it is loaded, etc. It also sounds pretty complicated, and I imagine 95% of developers won’t code to this API themselves and instead use a framework that takes advantage of it to optimize performance.
The big problem is service workers aren’t fully supported: on desktop Chrome and Firefox support it, but not MSIE/Edge nor Apple Safari. Mobile support is not good either. And this feature is so complex I don’t think you can polyfill support in, certainly not in a meaningfully performant way. I don’t have enough perspective to see whether service workers have momentum. Chrome has supported it for two years, which in a way is a bad sign that it’s been that long and there’s no clear consensus for implementing it everywhere. OTOH it solves a real problem and Apple and Microsoft are certainly not known for leading the way in web development.
Bonus links from reading that blog post. The fetch API is a modern alternative to XMLHttpRequest, etc which is nicer to use. Polyfills exist. And speaking of polyfills, polyfill.io is a nice CDN service that delivers optimized polyfills to browsers based on their User-Agent. Finally freegeoip.net does free geolocation of IP addresses and powers a polyfill for the HTML5 location API. It runs as a free service with usage limits, or you can download the IP database and code and run your own.
Resources served from AWS S3 can have CORS headers set, useful for JSON data intended for inclusion. But testing it from the command line is not simple.
Plain old “curl” doesn’t work because it doesn’t show headers. “curl --verbose” works, but even if CORS is configured on S3 you won’t get CORS headers. You have to set an Origin: header in the HTTP request to induce Amazon to set a CORS header in the response.
Also doesn’t work: “curl -I”. That’s supposed to be curl’s “print headers” option but it also switches to doing a HEAD, not a GET, and S3 doesn’t set the CORS headers for HEAD requests.
Interesting conversation on Reddit about scalable webapp frameworks. Lots of endorsements for Pyramids, the successor to the old Pylons project. After a brief review it looks like it’s similar to Flask. The Reddit discussion says it scales better, that it’s thread safe and there’s a hope of running it async.
Megaframeworks make decisions for you. But if you don’t fit their viewpoint, you end up fighting their decisions. Microframeworks force no decisions, making it easy to start. But as your application grows, you’re on your own.
In both cases, the focus is on the start: either too much or too little. Either way, finishing and staying finished is hard. You need a finishing-focused framework with an architectural design that scales down to getting started, then up as your application grows.
It seems to mostly be focussed on URL dispatch, with a structure for web views and sessions. And support for logging and testing! Also has some connectivity to various template libraries in Python. No database code at all, but there’s extensive docs on using SQLAlchemy. Also the note “Pyramid has a strong orientation towards support for transactions”.
Been a month since I had to set up Jupyter for a new project. Here’s all the steps, which seems awfully complicated for a “standard setup”. Some of that is idiosyncratic to me though.
newvenv
a shell alias I have. What it does:
python3 -m venv venv;
source venv/bin/activate;
pip install -U setuptools pip
pip3 install jupyter
pip3 install matplotlib numpy pandas seaborn requests
these are standard visualization libraries, plus a sane HTTP client. Fortunately these install from precompiled wheel files so it’s quick
jupyter notebook --no-browser >> jupyter.log 2>&1 &
Jupyter really, really wants to be an interactive program. This sort of makes it headless.
ssh -L 8888:localhost:8888 my-server.example.com
I’ve installed and run Jupyter on a server. I run this command on my local development machine to forward the port to access it.
I’m thinking again of doing some work on lolslackbot, in particular adding a web frontend to it. Tired of adding users with ugly SQL hacks, tired of having no reporting views. I experimented with using Django six months ago and even sort of still have the code but have totally forgotten how it worked. I also never came to a conclusion about the path forward. In particular whether I should add Django first, or I should port from sqlite to postgres first.
Well I’m cutting that Gordian knot based on 30 seconds advice on IRC. I should add Django first, Django + sqlite. It should all work fine, the only drawback is sqlite database level locking will suck with multiple web users. Which is fine for now. Adding Django lets me add new features to the product, which is what motivates me. I’ll port to sqlite later if I open the webapp to multiple users and need better locking. A rough plan:
Get some basic read-only views of the database
Related: sort out my problem with representing many-to-many relationships. I fear this might require changing my database schema to be compatible with Django’s way of doing things.
Focus on the social tables: People, Groups, Destinations. Create views like “who is in which group” and “where do these messages for this group go?”
Also do some reporting, like “show last 10 messages sent” and “how many messages total are we sending a day?”
Implement some basic tests for the Django code so I have a test environment for Django database code.
(Cautiously) add some write capability for the social tables. Like “Add this person to be tracked” and “add this person to a group”.
Take a deep breath! Stuff is working!
Work on a plan to let other people log in and add users / groups.
Well this is neat; matplotlib supports generating animations, and you can inline HTML5 video right in Jupyter. The only wrinkle I hit is the stupid Ubuntu ffmpeg/avconv kerfuffle. Trying to produce the animation by default produced the error “KeyError: ‘ffmpeg’”; I solved it by setting
There’s a GitHub comment saying that avconv may not be reliable, but it seems to be working for me in Chrome.
Now to figure out how to make this work with Seaborn. Some hints here.
Update: the Seaborn hints mostly just worked. Hilariously the inline video solution is to encode the whole MP4 file in a data64 blob right in the HTML, some 130k worth in my case. Hey, it works.
Took a quick tour through Seaborn, the enhancement library for matplotlib. It’s very good! It does two basic things. It makes the default matplotlib charts prettier, and it gives you an easy API to do some fancier types of statistical visualization. I’d say it’s a no-brainer to use Seaborn if you’re doing exploratory data visualizations. It still just renders raster images in Jupyter, so it doesn’t fulfill my goal of having nice SVG interactive charts in the browser, but Seaborn is solving a different problem.
Prettier
“Drawing attractive figures is important”, the docs say, and I couldn’t agree more. Seaborn reconfigures matplotlib so the default charts look better. I don’t just mean nice anti-aliasing, but also reasonable grid ticks and color choices. Seaborn has good perceptual palettes which are really important. I believe stock matplotlib has recently improved in part with input from Seaborn.
The other part of “attractive figures” is the Seaborn API is DataFrame-aware and will label your plots using the labels in your DataFrame. Getting nicely labelled axes and titles and stuff takes several lines of manual code with matplotlib; with Seaborn it’s a single line of code.
Fancier statistics
The meatier part of Seaborn is it has more complex chart types built in.
distplot: 1 dimensional distributions, an enhancement of matplotlib.hist. It adds a continuous kernel density estimate to the bars, and also has a rug-plot option.
jointplot: 2 dimensional distributions, an enhancement of matplotlib.scatter. Adds correlation coefficient, histograms on the side, a sort of quicky ggplot. Can also do continuous contour plots. One drawback is there doesn’t seem to be any easy way to set the hue of the individual dots, so no sneaking in a third dimension of data. Pass in kind=”reg” to have it try to fit a regression curve to the scatter.
pairplot: pairwise jointplots for your N dimensional dataset. So nice to have this in a single command, although it’s unwielding for N > 5 or so. (Note this does have a way to set the hue of individual dots.)
Regressions are for fitting various kinds of statistical models to your dataset.
Categorical graphs are for looking at statistics for qualitative categories, plots like swarm plots and violin plots. They’re really quite beautiful. Here’s a sample visualization of the distribution of a variable (y axis) for each of 5 categories (the x axis). I’ve used a violin plot which shows a KDE continuous approximation, along with a swarm plot to show the actual dots on top of it. (The data set is # of games players have for each of 5 roles in League of Legends. That one crazy outlier is Fiddlesticks Jungle; players tend to have 220+ games on him!)
Finally data-aware grids are used for making small multiples plots of the same dataset. I already mentioned pairplot, for doing NxN visualizations of N variables, pairwise. FacetGrid is a tool for quickly generating a bunch of graphs comparing across multiple categorical variables.
Conclusion
I like Seaborn. I like that it looks good out of the box. I also like that it allows me to make more sophisticated graphs very simply, with little effort. It may be a little too easy; I’m not sure a violin plot is really the right treatment of that data above, for instance. But it sure looks good!
As much as I’m liking Jupyter, I don’t much like that matplotlib is the default charting library. I mean matplotlib gets the job done, and it’s powerful and popular. But end of the day you’re rendering raster images with 10+ year old software. (Even if seaborn has made the raster images better.) We’ve got a fancy browser viewer, why not have fancy SVG/Javascript graphs?
That’s what mpld3 provides. Using it is as simple as importing it and calling mpld3.enable_notebook(). All (most?) of your old matplotlib API code will still work. mpld3 emulates that charting API but renders to SVG using D3, instead of rendering to a static image. It’s kinda nutty that it just works. The resulting pixels look good, although admittedly matplotlib’s raster backend (agg?) looks pretty good too.
The real advantage is the graphs are manipulable with Javascript. Out of the box every graph is now pannable / zoomable, right in the browser window. You can do fancy linked brushes across multiple figures.
There’s also plugins to add more capability. PointLabelTooltip plugin is particularly nice, it adds an easy way to have HTML tooltips on a scatterplot when you hover the points. There’s also MousePosition (useful for images).
And... and that’s about it. After a bunch of work a couple of years ago development seems to have stalled. That’s OK, it’s useful as is. Particularly since it’s such a simple drop-in upgrade for matplotlib.
Probably time to look at alternatives. Bokeh is the “better matplotlib” and includes a bunch of browser / notebook stuff. However it’s still rendering raster images (albeit in an HTML5 canvas). The examples sure are pretty though. I also see frequent references to VisPy, which is GL based, but although there’s some noises made about WebGL and notebooks I can’t find a working demo. Other options I’ve run across are pygal, bqplot and Altair. People also talk about Plotly but it’s a hosted system and costs money.
While I’m here, ipywidgets is kind of nutty. It lets you add interactive controls to a notebook like sliders and input boxes, to turn your notebook into an interactive app.
Diving more in to using Pandas DataFrames, I spent some time learning about MultiIndex. Long story short it’s a way to have a composite key for your data, to say “these two columns of my CSV file are the name for the row”. Or more complex things.
Pandas has some fairly powerful mechanisms to subset your DataFrame based on aspects of its MultiIndex composite key. They’re a bit confusing though, the slicing syntax is abstruse. Also there’s a hidden gotcha: you really have to sort your DataFrame before you can slice it if it has a MultiIndex.
For the search engines: if you see any of the following error messages, this sample notebook will help you figure them out. Summary; call DataFrame.sortlevel()
PerformanceWarning: indexing past lexsort depth may impact performance.
KeyError: 'Key length (1) was greater than MultiIndex lexsort depth (0)'
KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (1)'
PS: if you want to get the series of index labels for a DataFrame with a MultiIndex, use get_level_values(). I keep forgetting how to do this.
I’m in the top 6% of Stack Exchange users, despite seldom contributing to the site. How? I got in early.
I didn’t do anything clever. I just happened to have asked a well-worded question seven years ago that’s been popular with Google searchers ever since. It helps that I got a great, surprisingly simple answer.
It just keeps paying off, a reliable karma trickle. Something like half of my reputation points come from the one question.
I think the Stack sites are terrific, btw. I now go to Stack Exchange first for questions on new libraries like Pandas, before I even go to the code’s own documentation.
I’m looking at some League of Legends data; champion win rates by player tier. I’m curious which champions have higher win rates with skilled players, and/or which are more popular. You can see the resulting report here, notebook (without nice CSS) is here.
Learning me some Jupyter and Pandas
Really I’m using this project to get more comfortable with using Jupyter and Pandas DataFrames to analyze data. The DataFrames part is overkill; I’ve got about 10k of data, not the 10G of numbers DataFrames’ highly optimized code is for. But DataFrames have lots of functions that replicate SQL’s analysis capabilities and they display nicely in Jupyter, so here I am.
My data starts as web pages of HTML tables. I imported those into a single Google Spreadsheet with multiple tabs.For a single sheet, rows are champions (120 or so) and columns are statistics like win rate or games played (5 of them). There’s 7 sheets, one per tier Bronze / Silver / Gold / ... I then exported those sheets as CSV files, one per tier, for analysis. (Google Spreadsheets turns out to be a remarkably good HTML table data scraper.)
I then played with various forms of Python code for reading those CSV files and doing some statistics on them. Starting with simple raw Python data structures, a bunch of dicts and tuples all the way up to a full Panda Panel. Along the way I learned how to analyze the data using Pandas a bit, and to format the results nicely in Jupyter. My real goal here is to make interactive reporting as natural as if I’d loaded all the data into a SQL database. Being able to do natural things like sum all values, or get the average of numbers grouped by some criterion.
Data loading
One thing I found is that the more I whipped my data into Pandas shape, the simpler my code got. I finally settled on doing all the parsing way up front, when I read the CSV files, to make clean DataFrame objects with well named columns and rows. That makes the later analysis code much simpler.
The read_csv() function has a lot of options to configure parsing, it’s worth the time to set them. “thousands=,” for instance will allow it to parse things like “1,523,239” as an integer and not a string. I also ended up doing “header=0” and specifying my own “names=[...]” for columns, just so I could make the names valid Python identifiers. (You can access named things in a DataFrame with attribute syntax; either df[“winrate”] or df.winrate.)
But the most important thing for read_csv was index_col. The concept of index in a DataFrame is particularly important. That’s the unique key that names each row; in my data the index is the champion name. In a CSV file this would probably be the column named “label” or the like. In a database table it’d be the primary key. The word index is used all over the docs and it confuses me all the time. Once I set up my data index correctly the code got a lot better.
The thing I find most confusing is the shape of data. DataFrames, for instance, mostly seem to want to treat a column of numbers as a single feature. But I really need to work row-rise most of the time. Slicing a DataFrame is particularly bizarre. df[n] gives you the nth column from the dataframe df. But df[n:n+2] gives you rows n to n+2. I find I often have to transpose my dataframe to make operations convenient, or use the “axis” parameter to functions like sum() to indicate whether I want to sum over columns or over rows.
The final fillip was using a Pandas Panel to store my data. A Panel is a collection of DataFrames; in my case one per tier. This 3 dimensional data structure is a bit confusing, the docs apologize for the names and it’s not clear that Panel adds a lot of value over a dict of DataFrame objects. But it’s Pandas’ way of representing a collection of spreadsheets, so I am going with it. My panels “items” are the tier names, the major_axis is champion rows (named by the index) and the minor_axis is the stats (the columns.)
Data analysis
So now I have my data loaded into a panel, time to analyze. The pattern I’ve settled on is generating a new DataFrame that’s a report table. For instance I’m interested in average statistics per tier. So I start with a 3d Panel of tiers x champions x stats, and I boil that down to a 2d DataFrame of tiers x average(stats). When I do ad-hoc Python report generation I usually just iteratively print out report lines, or maybe make an array of dicts for my data. Those are still fine too, but I wanted to go full Pandas.
I started out by writing lots of laborious loops over panel.iteritems() and the like. See cell 7 and how I first build up a dict named ‘spreads’ and then converted it to a DataFrame. Over time I’ve refined to simply doing operations like dividing a DataFrame by a Series and the like. Cell 8 shows that style, the creation of pick_rates is about the same computation as spreads before, but it’s less code. The whole process feels a lot like vectorizing code, like I did for my machine learning class in Octave/MatLab. The code gets shorter, which is nice, but it should also be more efficient which matters for large datasets.
Presentation
My final goal was to make nice-looking reports right in Jupyter. That proves to be quite difficult. Pandas is amazing at inlining graphs and visualizations with matplotlib and friends. But it’s not quite as good at textual reports. I mean Jupyter will display any HTML you make in python, but I haven’t found any good HTML generation convenience libraries out there for, say, DataFrames.
Fortunately the default DataFrame presentation HTML is pretty good. Labelled columns and rows, decent formatting of numbers. All that’s really missing is right alignment of numbers (and why is that not the default?!) But I want more control, for instance rounding floating point numbers to specific precision. For that I used the DataFrame.style object, which gives you a D3-esque ability to apply per-datum CSS styles to cells. I mostly used .format() to control text formatting of numbers and .set_table_styles() to add some CSS to the HTML table. The .applymap() function is the really powerful one that lets you control things per-datum.
I also threw in the background_gradient style, to give a sort of heatmap coloring to the number cells. That required installing a bunch of crap like python-tk and numpy just to get the colormaps. But it’s pretty painless in the end.
Conclusion
Pandas + Jupyter is a pretty good platform for ad hoc exploration of data, and with some learning and effort you can produce pretty clean code and reports. I love the way notebooks are reproducible and shareable. I think using SQL for this kind of work is probably more effective, but there’s a lot of overhead in getting set up with a database. And the interactive exploration isn’t as nice as a Jupyter notebook. (Hmmm, there’s no reason Jupyter cells couldn’t contain SQL code!)
About once a year I need to hash some data to give it a name / short checksum. I don’t need a cryptographic hash. But I end up using SHA-1 or MD5 anyway because it’s so available. A non-crypto hash should be ~100x faster to process data, which could actually matter. But finding a standard, portable, non-cryptographic hash with optimized implementations for Python, Node, etc is a challenge.
A lot of history of hash functions is producing 32 bit values on 32 bit CPUs. That stuff is mostly obsolete. 32 bit hashes are not useful for many applications; you expect hash collisions after just 2^16 ~= 65,000 objects. And 32 bit CPUs are largely irrelevant now. You really want a micro-optimized machine code implementation for AMD64 that is aware of cache geometry, pipeline optimizations, etc. It may be now that you want a GPU implementation; you certainly do for high throughput crypto hashes. Not clear if it matters as much for non-crypto hashes and deployment realities mean you may not have a GPU at all.
Stock Python has the hashlib library, which includes crypto hashes like MD5 and SHA-1. It’s highly optimized. There’s also CRC32 and Adler32 hiding in the zlib library, but they are only 32 bit hashes and therefore not useful.
MurmurHash3 is the usual recommendation for a non-cryptographic hash. It’s been around a long time and widely implemented. It’s also a bit confusing, with both 32 and 128 bit versions and multiple Python implementations.
SMHasher is the standard test and benchmark suite for hash performance. I’d love to read a carefully done comparison of hash functions out there in contemporary languages and deployment environments.
I’m doing a lot of trashy video editing on the command line. I’m taking FLV files from a screen recorder, trimming them to a time frame and converting them to MP4. And then I’m concatenating multiple MP4 files. This is all very confusing to remember how to do in ffmpeg so here are two shell functions I use to do the work for me. There’s nothing particularly clever here except the <() process substitution for the catmp4 program, which creates a temporary file (or named pipe or something) with the output of a command.
function tomp4 {
ffmpeg \
-i "$1" \
-c:v libx264 \
-preset slower \
-crf 19 \
-ss "$2" \
-to "$3" \
"${1%.flv}".mp4
}
function catmp4 {
ffmpeg \
-f concat \
-safe 0 \
-i <(for f in "$@"; do echo "file '$PWD/$f'"; done) \
-c copy \
out.mp4
ls -l out.mp4
}
For years I’ve been doing bash arithmetic like this
echo $[2+2]
TIL I’m supposed to be doing it like this
echo $((2+2))
Who knew? Everyone, and apparently since 1996 with the release of bash 2.0. The $(()) syntax goes back to the 1988 Korn Shell, which predates when I learned Unix. But I learned most of my fancy shell scripting in the 1989–1994 time frame, when bash was the new hotness and it felt edgy using advanced features unimagined by Bourne (blessed be his name). And I preferred bash to ksh.
I learned this when someone edited one of my StackOverflow karma factories, on how to generate random numbers in bash. I updated the syntax in my answer. (Stack’s moderation review decided it was a bad edit. They were wrong.)
I’m very encouraged with how my little Django experiment has worked out. I’m ready to start using it with lolslackbot. A big breakthrough was realizing that I can start using Django as soon as I trust it not to corrupt my database. Keep the existing Python cron job in old code, not using Django, and then have a separate webapp that also uses the same database. The cron job and the webapp will be reading the same tables but in general not writing the same tables. It seems like a good transition plan.
Only now I really have to face the sqlite question. I’m confident that ultimately I need to be using PostgreSQL. I’m envisioning thousands of web users updating the database; there’s no way that works with sqlite’s database-level locking. Even with low traffic the cron job and the webapp will be stepping on each other. I need to switch. But when?
Do I switch databases first, porting my cron job code over to a Postgres-backed system? That seems really painful and not much fun. Lots of backend work with no visible features.
Or do I use Django first, having it talk to the sqlite database? The lock contention won’t be a real problem if I’m the only webapp user. It lets me build fun / useful features sooner. And it gives me some more experience with data modelling. I’m pretty sure I’m going to want to refactor the schema along with the Postgres update, it’d be better to do that after doing some of the webapp work. The risk with Django-first is I do a lot of sqlite-specific work that is ultimately wasted. But Django’s ORM insulates you from the underlying database pretty well, so maybe that doesn’t matter?
Also curious how the Django ORM is going to work for me. I use a couple of non-standard SQL things now. Mostly “insert or replace”, which is sqlite’s upsert-like extension. Does the ORM expose those? Also very curious how testing will work. sqlite is so simple when managing test environments. But I know the Django folks have thought this through.
I had to add my bot to a new Slack today (8 new users!) and forogtten how. My bot isn’t a full Slack App, it’s just a bot user, which in Slack terms is a “custom integration” tied to my personal user account for Nelson. Here’s the steps to set it up:
Log into the Slack as Nelson, in the Web UI
The account needs permissions to add custom integrations. You get this by default if you’re an Admin, otherwise it needs to be added under Team Settings / Permissions
In upper left corner, click the down arrow near the Slack name to get to the menu for preferences / etc. Choose the “Apps & Integrations” option under the Slack team’s menu.
Ignore the confusing app directory. Click “Manage” in upper right.
Click Custom Integrations
Click Bots
Click Add Configuration
Fill in the form and save it. Also copy the API token.
I had a problem with a new Slack where I couldn’t add a Bot user, I think the UI acts differently for the very first integration. I managed to create the bot though by hitting this link: https://my.slack.com/services/new/bot
Create a channel for the reports to go to. (Or use an existing one.)
Invite @gamebot to that channel.
That’s the Slack UI process for adding my bot. Kind of a mess, but it’s because I’m using the old bot interface and not the new fancy Slack App integration system that I should be.
After all that setup, then it’s on to Python code to find the channel token. Then set up the destination and subscriptions via code / SQL. All so manual, must build tools.
Speaking of tools I’m pretty convinced Django is the way forward. With a web UI, not some Slack interactive thing.
I’m soldiering on with trying to apply Django to my lolslackbot project, I thought I’d take a stab at letting Django try to use my existing database. My specific goal is to set up a read-only set of views on the primary social tables I have. People, Groups, Destinations all name entities in my system, I also have GroupMembership and Subscriptions tables which are many-to-many relations between the three primary tables. So far so good, at least for the primary tables; still working on the relations
Turns out starting with a legacy database isn’t too hard; you can use the inspectdb command to build skeletons of Django model classes from an existing database. Then hand-edit the resulting code. As a bonus this is an excuse for me to start learning more about Django models. Some random things I learned:
Django model classes define both a database schema and the UI validation behavior in HTML forms.
Every Django model class must have a primary key. The Python field is named “id”, not sure renaming it is possible or a good idea.
A model can have the option “null” set to true or false; this is whether empty values are stored as nulls in the database. (Why would you ever not?!) There’s also a “blank” option which has nothing to do with the database, but is whether the field is optional in autogenerated forms like the admin interface.
You have to hand-add each model class to admin.py to get it to show up in the admin interface.
Django coding style is lowercase_with_underscores for field names, CamelCase for class names. ¿Porque no los dos?
That’s the easy stuff. On to hard stuff.
I’m not sure how to translate my existing many-to-many relations tables to however Django implements relationships. I thought maybe the extra fields support (using the through keyword argument) might do it, but that seems like overkill and possibly awkward. I think I need to just adapt the ManyToManyField to my existing schema.
I’m a little scared to let Django start writing data to my database.
inspectdb sets up things with managed = False by default. That seems wise; it prevents Django’s schema management stuff from messing with tables someone else defined already. But some day I’m going to want Django to take all this over for me, can I later change managed to True and make sense out of it?
I haven’t even begun to think about testing in the Django world. I know there’s a lot of support for tests, maybe that’s my next learning.
Had a significant outage for my lolslackbot project yesterday. A few different things went wrong and I’m still confused for what the problem is.
The behavior
The problem manifested as me seeing the same message being delivered every time the program runs, every 3 minutes. That’s bad; I’m spamming my users. At the same time I was seeing errors in my logs from trying to deliver messages via Slack. No useful message mind you, but at least a hint.
I was busy last night when I spotted the error so I just shut the whole system down until morning. Then in the morning I tried a quick fix and run the script but that went badly, so I had to look closer. I finally got it fixed after two hours of work.
The delivery bug
This morning first thing I did was add more logging and reproduce the problem. I discovered the error was one of the Slack channel IDs no longer existed, which caused an exception in the Slack messaging module, which then broke things. The underlying problem was a design flaw in my error handling; I was trying to deliver all Slack messages at once and only then updating the database indicating those messages had been processed. The result is if there were 3 messages to be delivered at once and the 2nd one caused an error, the 1st one would get delivered but not marked processed and so would get delivered again.
So I fixed it by refactoring the logic that marks messages processed. I still deliver all the Slack messages at once but now individually flag whether each one worked or not. I also mark a message processed whether there was an error in delivery or not. The underlying problem is basically a distributed transaction. I’d rather err on the side of occasionally losing a message than sending the same message many times.
Rate limiting problem / match commit semantics
A second problem making all this diagnosis difficult was that my system was downloading match objects but they weren’t ending up in the database. I finally figured out my script that downloads all missing matches was crashing before it finished. And I only was calling commit on the database when the script finished, so all the work was getting lost. Derp. I fixed it to now commit after every single match object is downloaded. Also put in some better error handling.
So what’s causing the errors downloading matches? I’m not really sure, but I think it’s Riot’s rate limiter. I have some very high rate limit that I shouldn’t be getting near, but I’m still getting 429 responses for my meagre stream of requests, being told to wait. And this problem has been going on for days. I had chalked it up to a networking problem with their servers, but it turns out it’s my client waiting politely like it’s been asked to. So why am I being throttled?
I don’t know. The thing that triggers it seems to be a few odd matches that are returning 404 errors indicating the match doesn’t exist. (Even though it should, since I saw a reference to it from another API call.) Perhaps they have extra rate limiting for clients that make repeated requests that generate 404s? Part of the problem here is that I treat a 404 as “no meaningful response, try again later”, so I’ve accumulated 10-15 of those over time. I should clear them out, and change the code to stop trying if it gets the 404.
Lessons learned
Man, debug logs are a big help. Fortunately the same time I was having this problem I’d just committed new code to write debug logs more usefully to a file. Couldn’t have figured out what was going on without it.
A broad thing I learned here is be smarter about error recovery logic when working with third party services. I think when interacting with Riot or Slack or whatever, I want to do one small bit of remote API work and then immediately commit that work to the database before trying the next remote thing. And handle errors from remote services robustly, continuing even if it fails.
Unfortunately some of my code is now squelching exceptions, logging them and continuing instead of crashing the program. This is necessary to make my code more robust to errors, but is scary. Anyway I found I was having a hard time logging exceptions properly, here’s the way I’ve settled on:
try:
someFunction(data)
except Exception as e:
logging.error('Something went wrong %s' % data, exc_info=True)
The key thing here is the “exc_info=True”; this gets Python to include a stack trace. Before I was trying to actually log the exception object e itself, but that only gets you the message, not the stack. My use of % is an anti-pattern, I’m really supposed to use a comma and let logging do the substitution, but for some reason I find that error prone. And the worst thing about errors in a logging function like this is unless you are superhuman you often don’t have test coverage for the exception cases, so this line of code only ever executes in production when something else already went wrong and it’s very confusing.
I sat down and wrote my first Django app (in a very long time) yesterday using this tutorial, parts 1-3. Here’s some stuff I thought and learned:
Django has amazingly good documentation. That tutorial is fantastically written, clear and concise and elaborating where necessary. And an actively interesting toy app, it’s not just a dumb toy.
The polish is very good. Everything worked just as described with no weirdness. I particularly like that sqlite was the default database, that’s the right place to start for learning.
The distinction between a “project” and an “application”seems like needless complexity. The theory is that a single Django project instance might contain a mix of several independent applications. I wonder if that’s done in practice? I suppose so right away, the default project has the admin, auth, contenttypes, sessions, messages, and staticfiles projects. I wonder if many Django projects contain multiple third party / homegrown applications?
If you use the wizard to make an application and a project you end up with 12 files and 185 lines of text. I’m not a fan of codegen, it usually betrays an unpleasant complexity, but it’s not too bad in this case. The only big file is settings.py and that’s basically a declarative setting of what’s included in the project. That’s gotta go somewhere.
The good thing about Django is it comes with its own ORM and HTML template system. The bad thing is end up using their ORM and HTML templates. I don’t have enough experience with them to have an opinion other than some initial crankypants reactions.
The data model / migration / database agnostic stuff is pretty slick. I wonder if it works in practice.
I hate choosing between CamelCase and underscore_separation and forcedlowercase. The latter is particularly alarming; my database table names seem to be coerced downcase. Perhaps that’s a compatibility thing?
The auto-reloading of code is nice.
It appears that Django has no favored CSS UI framework. I imagine it’s easy to drop in Bootstrap or whatever, but part of me was hoping for some default styles that would make it easy to make things that look OK.
I ended up having 7 files open in my editor
project/settings.py to register my app
project/urls.py to register my app’s urls,
app/admin.py to register my models
app/models.py to define my data model
app/urls.py to define my webapp URLs
app/views.py to define my webapp views in response to URLs
app/templates/app/index.html as an HTML template for my view
Those first three files feel like make-work but the other four are actual real code I care about. That’s pretty good!
Overall I’m pretty pleased so far. I already know the pitfalls of going down this road, the way an ORM can betray you on performance in heavy traffic situations. But that’s not a road I’m worried about right now, and if I do ever get there I’m guessing there are ways to build special hacks bridges around the ORM overhead.
I store all my timestamps in the Unix epoch, as Thompson and Ritchie decreed. sqlite doesn’t really have a date type, instead it has date functions that can work with text or numbers. Unfortunately the numbers are defined with respect to two different epochs.
sqlite’s preferred date format is “Julian day”. This is a floating point number, the number of days since November 24, 4714 B.C., with hours/minutes/seconds being reported in fractional. Ie right now it’s 2457524.189894016. A single second is roughly .00001 in this time scale. sqlite3 reals are 64 bit, so we get 2^52 days or about 140M years of dates where individual seconds have distinguishable timestamps. No practical maximum :-P
Unix and Javascript’s preferred date format is an integer, seconds since Jan 1 1970. Right now it’s 1463330612. Unix times are generally 32 bits and therefore limited to the range of 1970–2038, although we’re all hoping we’ll see an extension to 64 bits before the apocalypse. sqlite3 already seems to have extended support and notes it will work on Unix dates from 0000 to 5352. The sqlite functions also seem to be OK with real number Unix epoch timestamps, with the fraction naming subseconds.
The thing that’s confusing is the sqlite functions like date and strftime operate on Julian day numbers by default. If you want calculations in the Unix epoch instead, you have to pass the flag ‘unixepoch’ to the function.
That last example is confusing; the time stamp ‘now’ is always the Julian day, even in the context of Unix epoch conversions. So it makes no sense to mix ‘now’ and ‘unixepoch’. I’m sure that’s the source of surprising bugs.
I’m not clear why the year 5352, integer 106750000000 is about the limit of sqlite’s Unix date implementation. That number is about 2^36.635, so it’s not some obvious integer rounding problem. Probably doing calendar arithmetic in floating point somewhere?
My lolslackbot program occasionally hangs forever and I’d like to know what failed when I kill it. Starting with Python 3.3 it’s relatively easy using the faulthandler built-in library. You have to set it up ahead of time (it’s not on by default), but once you do you can send the process a SIGABRT and it will display a slightly spartan stack trace and abort the program.
You can get a stack trace without killing the Python process by registering another signal, like faulthandler.register(signal.SIGUSR1). That signal is not entirely unobtrusive; it interrupts time.sleep() for instance. But the program does seem to keep running after printing the stack trace. All the signals registered by default seem to also kill your program; USR1 won’t. (Unless I’m confused.)
It’s all implemented in C to enable printing useful stack traces even if the Python VM itself is broken. Also you can enable it just by setting an environment variable, before any Python code is run, which I imagine is useful for debugging problems at startup.
There’s also an interesting faulthandler.dump_traceback_later() function which seems to basically be a watchdog. It sets a timeout with a separate thread that results in a stack trace dump and, optionally, your program exiting. It calls _exit() which is the hard exit, which has pluses and minuses.
It’s sure a lot easier than the only other way I knew to do this, which was to attach gdb and inspect the interpreter’s state. But I wish it were enabled by default like Java’s old built-in behavior on SIGQUIT (Ctrl-\). Maybe they were afraid it was too radical a backwards-incompatible change.
I have a script downloading a JSON API once a minute. The data only changes every ~30 minutes or so, so it’s a lot of duplicates. And I left it running for 10+ days out of carelessness, so it’s a whole lot of tiny useless duplicate files. Easy solution:
I just set up lolslackbot for Learning Fives Session 2. Some 180 new users. Kind of an exciting day for me, before I only had 30 or so users.
My test infrastructure continues to pay off in spades. All sorts of firsts today. First time running with users a new region (Latin America). First time where I got a game where all 10 people were in my cohort I was tracking. Etc. And AFAICT it all worked as intended. Really no problems running it other than some scutwork and some unintended consequences.
The scut work is I still have no UI for administering users in my system. I spent half of today writing 150 lines of Python + tests to set up the new users. I have to create entries in five tables: People, Groups, Channels are all primary data entities, I also have “GroupMembership” and “Subscriptions” which are basically tables joining IDs from other tables. And all this crap is injected with command line tools. I do have scripts to at least populate them from CSV and JSON datafiles, it’s not raw SQL, but it’s close.
I really need a proper web GUI for editing these data entities, regrettably in Django, and I’m still dragging my feet on taking that leap. I have an idea for a new product I can do in Django though, a quick spike for something related to the existing code
The unintended consequences is I neglected to account for how unusual this first run would be after the import. Basically I was catching up, getting info on past games those 180 new users played. It took 15 minutes to download 10 match records for each of my 180 new users. And then that generated 177 messages which it immediately delivered, in a few cases spamming 10+ messages to a Slack channel. Those messages were all correct in some sense, but in retrospect it would have been better to suppress the past and only start delivering new messages instead. Oops.
while :; do
wget -q -O `date +%s.json` example.com/data.json
sleep 60
done
Very simple shell hackery to download a URL once a minute and save it in a file named with a timestamp. The only midly subtle thing there is date +%s: that is a date format which is seconds since epoch, which is a conveniently sortable thing for filenames and timestamps and stuff.
(The while : instead of while true is idiosyncratic and anciently historical. In some very bizarre contexts true is the program /bin/true, the : is always a builtin.)
I have a bad habit of leaving scripts like the above running and forgetting about them, only to come back to a directory with 100,000 files in it.
Awhile back I wanted sqlite for JSON, some simple file-based JSON document store with a basic query interface. TinyDB looks promising. It’s a Python library. It lets you stuff a bunch of JSON documents into a file database and then query them. The query language is pretty simple, mostly “documents that have property X”, but that’s fine. The underlying file format looks like one giant JSON blob and may not be very efficient for updates, not sure.
I’ve used the JSON1 support in sqlite now. It’s pretty good.
I sure wish it were easy to marry jq to some simple JSON document store.
I want to build a webapp for my lolslackbot project. What do I use?
Django is the clear consensus choice for large, grownup projects. I used it once a couple years back and thought it was fairly good, if not exciting or lovely. But I have in the back of my head the Django ORM doesn’t play nice with homegrown schemas, that it really wants to control the schema itself. Also I have the impression that Django is kind of big and clunky, although maybe that’s unfair.
The cool kids all use Flask. I like the idea of a microframework, something simple. Flask doesn’t inspire a lot of confidence though. The last release is 0.10.1, released nearly three years ago. And while Python 3 is supported its use is discouraged. That may have made sense in 2013 but it’s a backward opinion in 2016 (IMHO). (The author reiterated that opinion as much as 8 months ago.) OTOH my friends who use Flask say not to worry about it, that it works fine with Python 3 and it’s simple.
Only no one just uses Flask. They combine it with Jinja2 templates, and WTForms, and SQLAlchemy for an ORM. Add in logins, sessions, and some CSS frameworks and you’re looking at a lot of software. Is it better to glue together your own custom assemblage of small components or should you just use a full framework like Django?
My friend Brad G. recommended starting with cookiecutter-flask as a set of components + structure and customize from there. Man, it’s been years since I used a Visual Studio wizard! It looks like a good way to get up and running though.
Thinking for real about a webapp is making me once again consider whether SQLite is a good choice going forward. The lack of fine grained locks is going to make multiple writers unacceptable. I sure wish it had per-table locking, that would probably be good enough for now.
I’m looking for some simple application metrics. I want to track some basic things like “time it takes to make an API call” and maybe “number of interesting events over time”. The big boys awhile back converged on statsd + graphite for this, or now Grafana, and those are great technologies. They’re also too complicated for my little project. I just want something simple that will work. And hopefully nicer than rrdtool+mrtg :-/
Ian D recommended StatHat so I gave it a try. It’s pretty nice. You make REST HTTP calls giving it data and it aggregates the data and makes reports. It’s pretty basic, but then it’s simple to use and requires no extra work on my part.
The biggest drawback is that it requires an HTTP call in your app, which tends to be synchronous. The supplied client libraries don’t even have timeouts! I think this can be worked around with some async or thread implementation, or maybe even an offline stats collector, but there was nothing off the shelf.
I also found posting one stat value at a time with an HTTP call is very slow. I was able to post approximately 8 records a second. And I think that’s using HTTP keepalives! Fortunately there’s a bulk import API using JSON that is much faster; about 999x faster if I insert 1000 records at a time.
Data records have an optional timestamp. Those have to be an integer. If you pass in a floating point with milliseconds like 1460076429.905 it will be silently ignored and the data will be timestamped with the current clock time instead.
The biggest problem I’ve run into is that my data is getting lost. It looks just fine when I import it, then an hour or two later my data is gone. I’ve written asking if this is something I’m doing wrong. Update: my data reappeared. There’s some confusing things that happen around updates, etc, maybe the consistency is just eventual.
Here’s a sample report. The number being measured is the milliseconds it takes for Riot’s Web API to answer a request. This tells me the average time is 320ms and it spiked around 9AM. The reported min, max, 95% and 99% don’t seem correct to me, but maybe those are describing the averages in 15 minute windows instead of individual events. (Which makes it less useful).
It’s a neat product though. I may stick with it if I can figure out the data loss problem. Sure beats setting up some complicated stuff myself.
Update: I’m using stathat in production now and am very happy with it. I just collect all the stats I care about in memory during a run of my job, then post them all at the end with a 10 second HTTP timeout. Seems to work just fine. The disappearing data problem seems to only be a temporary quirk in an initial bulk import, hasn’t been an issue since. And it’s really nice having the charts!
Python 3 has an odd oversight; there’s no function for finding the length of an iterable. You can do len(aList) of course, and len(aTuple). But there’s no len(anIterator). What’s really surprising is there’s no itertools.len(anIterator), some function implementation.
The naive solution is len(tuple(anIterator)). But that’s inefficient because it constructs a tuple in memory. This discussion suggests sum(1 for e in anIterator), which if I understand generators correctly should be pretty efficient and involve no allocation of new collections. Surprised this function isn’t in itertools.
Update 2: I had some yak-shaving time, so I made an iPython notebook timing three different solutions for counting the length of an iterable.
1x: len of tuple of iterable
7x: deque an enumerate of iterable
11x: sum 1 over the iterable
The results are roughly the same for iterables of size 1000 to 1,000,000 to 100,000,000 and hold whether the iterable is a list or an ephemeral itertools iterable.
What’s astonishing is how much faster the len(tuple(iterable)) method is than the others. Naively it should be slower, it’s doing a lot more work building that tuple in memory. But perhaps this is a highly optimized codepath in Python. The tradeoff is it temporarily allocates memory to consume the whole iterable, so it’s using O(n) memory compared to the O(1) memory for the other solutions.
Hooray! I finally finished porting my lolslacktest code over to be a proper Python module, installable with pip, and with a virtual environment. What a pain! Some notes on what I learned. But first, some reflection.
This project has been one of the least fun things I’ve done in a long time. I can tell by the way I’ve been foot dragging. It’s confusing and hard to debug packages. The docs are inconsistent and suffer from years of accretion. Some things are genuinely confusing, like Python’s surprise lack of support for circular imports. And in the end result is my product works just like it did before. No user visible changes. Behind the scenes things are better; the install is cleaner, I have a virtual environment for proper external dependencies, etc. But nothing fun, just slightly less crappy ops.
The state of the art for Python Packaging
As of March 2016 the Python 3 state of the art for package installation is pip, pyvenv, and setuptools. pyvenv and pip comes with Python 3.4 but setuptools is still extra. (On Ubuntu you have to install python3.4-venv with apt.)
The state of the art for managing Python packages keeps changing. This Stack answer explains the landscape as of September 2014. This packaging user guide is updated as of September 2015 and is mostly very good, but even it references things that don’t work such as “python setup.py bdist_wheel”. I also found this guide useful but it was mostly written in 2012 (although occasionally updated).
The pip installed by python 3.4 (Ubuntu) is version 1.5.4, you want version 8.0 or later if you want to do things like install gevent with a precompiled wheel file. setuptools is old too. So first thing you should do after setting up a pyvenv is “pip install -U pip setuptools”.
The setuptools docs are not very good. They assume you know how distutils works. Also they spend a lot of time talking about easy_install and none at all talking about pip.
Honestly all this Python packaging stuff is a big mess, I feel like you have to understand the history to be able to use the current state of the art. It’s a shame Distutils2 didn’t work out for Python 3.3 and rationalize it all. To be fair, packaging in almost every system sucks: npm, rvm, homebrew, they’re all a mess. All but my beloved apt, and that’s because the Ubuntu package management team works super hard.
Some hacks and code things
I had to do a few hacks and other things to make my project work.
The biggest code change was just wholesale replacing absolute imports like “import lib” with relative imports “from . import lib”. I think that’s actually correct, but I was doing it kind of blind for every single file.
I had to modify my code because Python really doesn’t support circular import dependencies. You don’t really notice until you are using relative imports. The accepted solution for circular imports is to break the circularity, refactor code. Screw that. My workaround was to move some of the import statements inside functions, so they execute at run time and not import time. That’s bad and inefficient but expedient.
There’s two similar-looking ways for a Python package to specify dependencies. You can add an install_requires stanza to your setuptools setup() method, or you can use pip to install a bunch of stuff listed in a requirements.txt file. The setup() dependencies are installed automatically when a package is installed, but nothing installs requirements.txt automatically. OTOH the requirements.txt option is more powerful, for instance pip can install things from github URLs whereas setuptools can’t. (The setuptools docs say you can do this with dependency_links, but I couldn’t make it work.) I’ve ended up using a mix of both, preferring setuptools where I can.
I have some shell scripts named in the “scripts” section of my setup.py, so they are installed in the virtualenv bin directory. But I want them to work even if the virtualenv isn’t activated, so those scripts have to source their own virtualenv. Mostly for execution in cron; getting cron to activate a virtualenv is not easy. The hack I did for this was this shim of code at the top of each script:
The bash magic in the first line sets VENVDIR to be the directory where the bash script itself is. Conveniently, that’s the same directory that has the activate script.
I have no idea how to put version numbers on my program. It’s a private thing only I’m installing, so for now I’m going with the dbschema version. Part of me wants to just put the git commit nonce there.
My deploy script used to be rsync from dev to prod. Now it’s sshing into prod and having it do a “git pull” followed by “pip install -U”. I took this approach at migurski’s suggestion. It means I’m not using any of the fancy distribution builds and versioning stuff that setuptools/pip enables. But I don’t really need those right now, they make more sense for public code hosted at PyPI
Note to self: you can’t move a pyvenv environment once its created. They have paths hard coded.
I’m trying to turn my lolslackbot code into a proper set of Python modules, so I can manage the code with pip and venv. That means turning my moduleless code into a bunch of packaged modules. And writing setuptools.
And oh god it’s awful. Python’s handling of module namespaces and imports is confusing, particularly when circular dependencies are involved and/or command line scripts as opposed to Python libraries. I can’t even tell if this caveat applies to me or not
Note that relative imports are based on the name of the current module. Since the name of the main module is always “__main__”, modules intended for use as the main module of a Python application must always use absolute imports.
The other problem is years of cruft that’s accumulated in Python packaging tools. setuptools, disttools, easy_install, pip, wheel, egg, virtualenv, pyvenv.. To some extent this has been rationalized in modern Python: use pip and setuptools and call it a day. But the docs that are out there are hard to follow because they tend to describe the history, not the current practice.
Right now I’m hung up on some code where “from . import lib” works in some contexts but not others. I think it may be related to circular dependencies but am not sure.
Update: turns out Python doesn’t actually support circular imports, despite looking like it does in many circumstances. So now I’m having to refactor all my code that worked just fine to not have module A import module B which imports module A. I feel like I’m programming in C again, only without #ifndef macros. One partial solution is to only do the imports inside the running function code. That avoids the circular imports at import time, at the expense of deferring the import code machinery running in your actual execution path all the time. Maybe I’m misunderstanding how to really make this work. (There’s a bunch of arrogant advice which says “if your code has circular imports you should refactor it.” No, imports are how you manage namespaces in Python, and Python shouldn’t have this limitation.)
I felt guilty complaining about sqlite3’s source distribution, so I went to look at the real source, what the authors work with. It’s not managed by git but rather in Fossil (an SCM written by the sqlite3 author). Happily the web view is quite good.
One of the miraculous things about sqlite3 is its incredible test suite. There are 683,932 lines of test code. Compare to 273,000 lines of C code for the library and all its extensions. sqlite3 has a reputation for being solid and correct. It’s not an accident.
The test size is overcounted a bit because there’s a lot of test data. For instance the test for the Porter Stemmer is 24k lines of code, but almost all of that is a giant list of words and their correct stemming. Still very useful tests! But not quite as much human effort as it looks on first blush.
The tests are written in Tcl! For all I know it is the oldest large large Tcl program still in active development. But other than the string quoting problem Tcl is a pretty good way to script a test. See for example the tests for the JSON module
do_execsql_test json101-1.1.00 {
SELECT json_array(1,2.5,null,'hello');
} {[1,2.5,null,"hello"]}
do_execsql_test json101-1.1.01 {
SELECT json_array(1,'{"abc":2.5,"def":null,"ghi":hello}',99);
-- the second term goes in as a string:
} {[1,"{\\"abc\\":2.5,\\"def\\":null,\\"ghi\\":hello}",99]}
do_execsql_test json101-1.1.02 {
SELECT json_array(1,json('{"abc":2.5,"def":null,"ghi":"hello"}'),99);
-- the second term goes in as JSON
} {[1,{"abc":2.5,"def":null,"ghi":"hello"},99]}
Very readable and compact.
As a software project sqlite3 makes a lot of idiosyncratic choices. Tests written in Tcl. Fossil instead of git. Source code distributed as “the amalgamation”. But sqlite3 is a masterwork of code. It’s fast, it’s reliable, it’s simple, and it works well in embedded systems while also providing a lot of very sophisticated database capabilities. I have nothing but respect for it.
Python 3 has sqlite3 baked in. That’s great! But it has an old version of sqlite3; my Ubuntu 14.04 system with Python 3.4 has sqlite 3.8.2. I want sqlite 3.9, for the new JSON hotness.
There’s a pip-installable package called “pysqlite” that should be installable in a virtualenv. But it only supports python 2 and explicitly says “use the built-in sqlite3 for python 3”. Thanks but no thanks!
This Stack Exchange thread has details on recompiling python3 with your own sqlite3, but that’s more work than I want to do. Also it appears that python3 is just loading libsqlite3.so.0 from my Ubuntu install, so I should be able to upgrade it by either upgrading libsqlite in Ubuntu or building my own shared library. But the Ubuntu upgrade looks impossible without upgrading all of Ubuntu 14.04. (I couldn’t find a PPA from a quick search).
It works! But now I’m nervous. Compiling sqlite3 correctly takes more research than I conducted. It has a whole lot of options! Also I get a bit worried about relying on LD_LIBRARY_PATH to override libraries. It’s totally fine to do of course, but it just seems too easy to forget to do it in some environment and suddenly things aren’t working consistently. If I were serious about doing this I think I’d build my own Ubuntu package for real, using Ubuntu’s Makefile as a starting point.
When debugging database code it’s really handy to have a text log of the actual SQL being executed by the database. This output is remarkably difficult to get in many database drivers. Happily, starting with Python3.3 there is a way
connection.set_trace_callback(print)
The argument is any function, or None to disable the tracing. I think this has no access to the results, nor can you use it to time how long the query took. That requires some more ambitious thing.
I’m wasting more than an hour figuring out the fuckup of building GDAL to run in a virtualenv on Ubuntu 14.04 LTS. This hasn’t worked well in the year+ I’ve been trying, and it’s not working well now.
set up a new virtualenv and activate it
virtualenv -p /usr/bin/python2.7 venv
source venv/bin/activate
Install the openaddresses repo I have
cd ~/src/oa/machine/
pip install -e .
Give up trying to install GDAL with pip. Even after you work through the include path packaging problems, the C compiler starts throwing errors about variable scoping.
Start over with a virtualenv that also uses system packages, which somehow seem to be working.
virtualenv --system-site-packages -p /usr/bin/python2.7 venv
I shouldn’t publish my angry rant. GDAL is great software, and I appreciate all the volunteer open source effort. But something about dealing with packages and software installation is just so maddening. I think it’s because hiding behind “pip install gdal” is about 200,000 lines of complex code in multiple languages from multiple distributers. When it works its awesome. When it fails all you can do is try searching the error message and cargo culting a solution, which only works 1/3 of the time.
I’m about to go on vacation. I just finished a bunch of improvements to lolslackbot. Also I suffered my first real outage since it started as a simple cron job six months ago. So I’m reflective on what I need to do to graduate this service into something more serious and reliable. Some projects towards making the system production quality...
Locking and timeouts. The outage was because I tried grafting lockrun into my cron job to ensure only one update runs at a time. But if the update script hangs (say, because the remote API is down) then it holds the lock forever, or at least until I wake up in the morning. I’ve removed the locking for now, running the update twice at once isn’t too bad. But I’m considering adding back the locking along with some sort of global timeout to the scripts, or at least the network requests, so they can’t hang forever. But that’s a hack on top of a hack. “Run this once and only once, reliably” is a hard problem.
Error recovery. I’m a big believer in throwing exceptions when things go wrong, then fixing the code to handle the error. But at some high level I’d rather the script kept going. I’m processing hundreds of game objects a day; it’d be better to skip a game that’s weird and breaks my code than to have the whole system fail until I can fix it.
Logging. I’ve been using Python’s logging program but I’m not logging to a file anywhere; just stderr. That makes it hard to look back at what happened. Or even notice if I skipped a weird game. I might also benefit from some contextual logging, but that may be overkill.
monitoring. I don’t exactly need a pager for 3am, but I would like some better way of knowing if stuff is working than “did cron email me?” and “have any new messages shown up in awhile?”
virtualenv. I’m naughty and don’t use venv. I should.
make code a module. I’m also naughty and don’t have my own code in a proper module. I should. Would be nice to separate the Python scripts from the precious data files, too.
test suite. A lot of my tests run based on some live data I captured a month or two ago and has baked in it things like “there are exactly 110 game objects”. That makes it hard to add new test cases. I think I’m stuck here and need to just suck it up and hand-edit in new test cases to the JSON blobs I use in my mock framework. And then update all the tests. I also had a hilarious problem yesterday where one of my test cases had enshrined the wrong expected output, basically hiding a bug I sort of knew about. That’s the hazard of starting a test suite with “I think this code is working; let’s assume its current output is correct”. Still that test suite is the single best investment I’ve made in the project, so much value.
indices / SQL performance. I haven’t done any work towards creating indices for common queries other than the implicit indices that primary keys and unique constraints give you. So far my whole database is only 20MB, hardly worth worrying about. But at some point table scans are going to stop being fast. I haven’t seen any evidence of a slow query log in sqlite, I suppose I could build my own wrapper in Python.
Distributed transactions. A closely related problem to locking; I have a sort of distributed transaction problem when I’m delivering messages to Discord. I want to mark the message delivered in my database if the message is successfully delivered to Discord. So I write the “message processed” bit after Discord accepts the message. But sometimes Discord throws an error even though the message got delivered anyway, so the message doesn’t get marked processed and later is delivered a second time. It’s sort of a distributed transaction problem I don’t quite know how to solve.
Web view. Big project, I think I’ve graduated to needing a web view for seeing and editing the objects in my database. Particularly for stuff like “add a player to a team”. I really don’t want to roll this all ad-hoc, way too much work. Currently thinking of doing this as a whole new codebase not reusing much (if any) existing code, to try out Flask and SQLAlchemy. With a plugin to generate the editing UI, maybe WTForms or Flask-Admin.
sqlite3 vs postgres. I continue to have the feeling that I should switch to postgres, but I’m now pretty in love with sqlite’s simplicity. The planned web view will be my first time with simultaneous writers, which previously I assumed was when sqlite may be too limiting. OTOH sqlite does have database-level locking, it’s not going to blow up. As long as the locks are only held for “a few milliseconds” I can live with that. Python’s driver has a 5 second timeout for connections by default. The sqlite3 command tool by default just throws an error if the database is locked, but you can specify a timeout in a somewhat awkward way. (If sqlite3 is compiled wrong, locks can last seconds.)
So that’s a big list of projects. I’m not thrilled to do any of them; they’re not features, and they’re a significant investment for a project that has very few users. OTOH they will make my life better as I work on this.
Confession time: I’ve never personally managed a whole project that involved a complex, changing database. I’ve certainly worked on projects with them, like Google AdWords, but someone else was in charge of the database management. With this LoL Slackbot I’m working on I’m the guy. Which means I’m the one who has to handle migrating a database when the code changes the schema.
Turns out changing database schemas on deploys is complicated. Who knew? It was a blessing in disguise that sqlite’s alter table is so limited, it forced me to take migrations seriously. And since I’m not using a tool like SQLAlchemy I’m writing migration scripts by hand. Here’s what I do:
The database has a table “globals” with a value “dbSchemaVersion” that I manually increment on changes.
My app has a single connect-to-DB function everything uses. It checks the schema version and refuses to run if it’s wrong.
When I write code that changes the schema somehow, I manually increment the version. This step is a bit error prone in that I could forget. I could automate it with a checksum on the output of “.schema”, but I won’t bother until the first time I forget.
When I write code with a new schema change, I keep manual notes on the migration I’ll eventually need. Then I just develop and test my code that uses the new schema in my dev environment ignoring the need for migration. My test scripts start with an empty database.
Once the feature development work is done I then write migration scripts. See a simple example in this gist.
run.sh is the actual migration. It validates the schema version is what’s expected, then runs arbitrary shell code. In this case all it does is run 3to4.sql. Sometimes I also have it run custom Python programs that do more complex data filling.
3to4.sql is sqlite code for the migration. I do as much in SQL as possible. The .bail on pragma at the start is essential; see here for why. This example script adds a column and then fills it with a static value, very simple. Often the migration script has to copy some table over to a new table and then rename it, since alter table in sqlite3 is so limited.
test.sh is my test suite for the migration. I run this on a copy of the live production database (taken out of backup). It runs the migration, then diffs the schema from a dev database. Then it runs some ad hoc queries to validate the new database is as expected, which is totally hokey. I should make that a proper pass/fail test.
One observation I’ve had from this is “schema changes” are more than just changes to the shape of tables. They’re also changes to global values stored in the database, and sometimes changes to the meaning of the data in some column. This single incrementing version number captures all of that just fine, at least with a single developer.
Having now done this work I’m less excited than I used to be about autogenerated schema migrations. I mean, I should try one, but there’s something to be said for hand-crafting a migration when you have to change column values, rerun programs to fill empty data, etc. The automation around testing and version numbers is really valuable though.
I’m terrified with how ad hoc this is. There’s this temptation doing ops work to half-ass stuff, to just type some code in by hand and throw it out, or test it by visual inspection, or... Part of the devops mystique is treating the ops part as real development too, with real testing and repeatability. I’m about 3/4 of the way there with the migration stuff but not fully.
I’m in the habit of recording timestamps as integer seconds. Ie, I’m inserting into my database the result of int(time.time()) from Python. It’s a habit left over from the bad old days where Unix machines didn’t have sub-second clocks. Any modern system has access to at least a millisecond timer, if not a microsecond timer or better, and there’s no reason not to use it.
The only drawback for me with my project is I declared all my timestamp fields as “integer”, and sqlite3 does in fact round them off on storage. It’s harmless enough, at least if you’re not relying on exact timestamp storage, but I should probably do a schema migration at some point for it.
It’s a bit confounding that Javascript’s time precision is integer milliseconds, although it seems like a reasonable practical choice.
Big Success! My League of Legends Slackbot has had two major upgrades in the past two weeks. And both have gone quite well, with no serious bugs. I’m so, so glad I invested in a serious testing regimen. I’ve had automated tests for about a month and it is like night and day for development speed. Even on a small project, even working alone.
First, a quick description of the project. It’s a social monitor for League of Legends players. It watches the Riot API for games played by a select group of people. If someone plays a game, it reports the game result to Slack or Discord. A form of social presence. I built it first for a group of about 6 friends playing together and chatting via Slack. I’m now expanding it to a group of about 500 people on another Slack, which is what necessitated me evolving this from a quick hack to a real thing.
The first big change was 10 days ago. I added the notion of “groups”. Previously the list of players I was watching was hard-coded and I assumed everyone was interested in everyone. Now there’s Person and Group database tables and the game reporting is able to collect stats for all the people in a specific group. I still have a design flaw here I need to fix; currently doesn’t work if people from two different groups play the same game.
The second big change was today. I added message routing and delivery. Previously I had hardcoded a single Slack and Discord channel. Now I have Destinations, Subscriptions, and Messages tables so that the game results from various groups can be delivered to various different Slack and Discord channels. A lot of complexity, made doubly hard to test because the end result is actually writing messages people see on a live service. I ended up using unittest.mock for real to mock out the last bit of message delivery in various places.
I wish I’d thought to abstract out a Messages table earlier. Before I was just generating text messages from game objects, but then the game processing code got too deeply entwined with the message delivery code. Now I place create messages in the DB with one program and deliver them in a separate program. Much simpler.
Next major product feature I need to add is some sort of web interface for managing Groups, People, Subscriptions, etc. That sounds really tedious, but necessary. I think this is the step where I’ll graduate and use some higher level Python frameworks, maybe Flask for the webapp and SQLAlchemy to mediate database access. I don’t want to port all my old code over to SQLAlchemy just yet, but I would like to get my feet wet.
I should also productionize the python code. I’m not using virtualenv, my code isn’t even packaged in a proper module. Time to clean that up and add some logging, monitoring, etc.
May also be time to invest more in the test infrastructure. My automated tests are great but they rely on a test dataset I can’t really augment. I generated test data once and have no way to do it again. Also I’ve been running a separate test system for database migration scripts, much more manual and inspection by eye. I think that may be fine actually, but it’s worth examination.
This Python library I’m using (deliberately left nameless, not well known) has what I think is a security problem. It takes a password and generates a login token. It then writes that login token to a file in /tmp. A world readable file. That token can then be used by anyone with access to the Unix system to impersonate the user. That seems bad.
What’s baffling me is I reported the bug and the author of the code and other users of the library don’t see the problem. “If someone can read files on your computer you’re screwed anyway.” I think they’re wrong, but maybe this is just me being old?
I grew up in the era of shared Unix systems. We regularly had 40 people all logged into one machine, so of course file permissions mattered. But modern Unix systems are generally single user. Single application, for that matter. And the rise of VM and container technology makes that doubly so. So maybe it doesn’t really matter?
Of course it matters. And it’s easy enough to fix; just make the file private. Although.. Doing that correctly in Python is remarkably complicated. You can’t just create the file and then chmod it, because that creates a race condition where the file is briefly world readable. I think setting umask is better, but that’s per-process state so you can’t really do that in a thread safe manner without locking. os.open() with a file mode is also a possibility but complicated because you’re dealing with file descriptors. The tempfile package in Python does this nicely, but unfortunately I can’t use it because I need a persistent file. tempfile’s code is remarkably complex!
I’ve got a lot of code calling sqlite3.connect() in my program now. Particularly in my test suites. In MySQL and Postgres this can be slow and you end up needing connection pooling. I had a feeling it shouldn’t be in sqlite3 given its simplicity, but I wasn’t sure.
A bit of work with timeit later I can report it’s taking about 18usec to open a database. My connection function is more complex too, doing a select into a “globals” table to test the schema version. Even with all that work it’s 170usec, or < 2ms. That’s not super fast but it’s not a problem if my test suite does it 100 times.
$ python3 -m timeit -s 'import sqlite3' "sqlite3.connect('games.sqlite')"
100000 loops, best of 3: 17.6 usec per loop
Python’s JSON module serializes the Python value None as the JSON value null. This is correct. However it causes odd bugs if you are not aware of it.
Specifically, I had code like this:
db.execute('insert into table values(?)', json.dumps(foo.get("bar"))
I was trying to insert a database NULL if foo didn’t have the key “bar”. But foo.get() returns None, which gets turned into the string “null”, which results in the string ‘null’ being inserted into the column. Derp.
>>> json.dumps(None)
'null'
>>> json.loads('null') == None
True
>>> json.dumps('null')
'"null"'
>>> json.loads('"null"')
'null'
>>> json.loads(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'NoneType'
Reflecting on my previous effort to understand asyncio, I think I have a simple summary:
asyncio is a cooperative multitasking system for Python based on generators. You implement your program as generator functions that yield control periodically. The asyncio event loop manages running all of your generators.
That’s it, it’s really simple. This understanding lets me build on my existing knowledge about generators / coroutines and understand what asyncio is doing.
What’s confusing is all the syntactic sugar and extra library stuff in asyncio gets in the way of understanding the simple thing. Also the Python docs are not written from the point of view of “explain the basic idea”. And the API is still in transition; in Python 3.5 they are no longer generators, they are coroutines, but the principals are the same.
Here’s a really simple program:
import asyncio
@asyncio.coroutine
def sleeper(loop):
for i in range(10):
print(i, loop.time())
yield from asyncio.sleep(0.1)
loop = asyncio.get_event_loop()
task = sleeper(loop)
loop.run_until_complete(task)
That’s a toy example. In real work, you have multiple tasks running simultaneously. And instead of yielding on a sleep you yield on something more useful, network IO or something.
The confusing part is the line 10, task = sleeper(loop). Naively you’d expect that to invoke the sleeper function and do the work right then. But because it’s been decorated as a coroutine, really what calling that function does is return a generator object that encapsulates calling the function. We then pass that generator to the event loop to ask that asyncio call it for us. (In Python 3.5 using async def and await, that object is no longer a generator, it’s a member of the new type, coroutine.)
There’s a lot more complexity of course. I’m still confused about the melange of coroutine, Task, and Future, and when to use which. Combining multiple coroutines in various ways can get complex, although once you commit to the model it is easier to reason about than thread locking. And then there’s a lot of auxiliary libraries that make asyncio useful, things that help you yield from network IO or external processes or whatever. Not to mention libraries on top of asyncio like aiohttp.
But the core concept there is really simple. Generator functions that cooperatively multitask. That’s the magic, there’s not too much of it really.
My little lolslackbot project has grown big. 11 different tables! I’m hand-writing ORM code now, silly things like “class Person” which wraps a row for the people table. The meat of the work is still hand-crafted SQL with proper relational queries, but I’m increasingly doing some really basic “get me the row with property X” and writing it all by hand is tedious. And oh boy I added some caching using functools.lru_cache, which I know from experience at Google is the beginning of the end for understandable correctness. And I continue to write increasingly elaborate schema migration scripts as I upgrade stuff.
It’s all kind of a mess. I wish now I’d started using some Python ORM tool. I still think ORMs are kind of evil, but they are a useful evil.
I’m out of date on where Python is but my impression is everyone likes SQLAlchemy. The basic tools are just a really nice upgrade from the basic Python database driver stuff. And the ORM looks like it’s made the right choices, at least based on what I read.
But do I want to port all this code over? Hell no. Hrm... I’m accumulating technical debt. I also need to wrap all my Python code in a proper module structure, and set up a real virtualenv, and...
At least I have a test suite. Although Guido help me if I ever have to regenerate the test dataset.
Working with discord.py has made me realize how I really don’t understand asyncio, the modern way to do asynchronous code in Python. Truthfully I barely understand any sort of async programming at all. I can sort of bash away at NodeJS a little bit. And I once wrote an asyncore program that did some neat network stuff. But mostly I’ve used threads or processes to do concurrency. It doesn’t help that I generally am starting with a single threaded synchronous program and then trying to later shoehorn it into some async context.
But soldiering on, here’s some resources:
Python 3.4 asyncio docs: the core reference. As with all Python docs it is well written, but unlike some Python docs it’s hard to follow. Much more of a reference than a tutorial.
Module of the Week: asyncio: a heroic effort to provide an overview tutorial of the complete module with lots of examples. It’s good, but I’m still confused after reading it.
How the heck does async/await work in Python 3.5?: a more low-level explanation focussed on the await/async keywords in Python, includes an example of implementing your own framework instead of using asyncio
PEP 3156 is the proposal that resulted in asyncio, written in the Python 3.3 era with a reference implementation called “Tulip”. I haven’t read this yet.
PEP 0492 is the proposal that resulted in the “async def” and “await” keywords being added to the language in Python 3.5. Also “async with” and “async for”. To normal coders, this is mostly syntactic sugar for stuff that worked in Python 3.4. But behind the scenes Python added a whole new concept of “coroutines” to the language, to accompany generators.
PEP 255, PEP 342, and PEP 380 are 5+ year old PEPs related to defining generators in Python. (The “yield” keyword.) Generators are the basis of coroutines, and coroutines are the foundation of asyncio.
aiohttp is the popular HTTP library for use with asyncio.
Here’s my understanding of today, with the massive caveat that I’m totally new to this and may have important aspects wrong.
The key concept in Python asyncio is the event loop. When you are writing an async program you no longer are executing functions imperatively. Instead you are creating objects that ask for your functions to be called. (The “async def” keyword or the @asyncio.coroutine decorator do this for you; they wrap your imperative functions with an object, so when you invoke the decorated function it doesn’t actually run but instead returns the callback object). You then supply these objects to the event loop through functions like “call_soon()”. Finally you set the event loop running with run_forever() or run_until_complete(), which gives the event loop control over the CPU where it blocks while it runs your code via all the callback objects you gave it.
The other key concept in Python asyncio is coroutines and/or generators. That’s where the “yield” keyword comes in, and it’s actually the same old yield keyword we’ve had since Python 2.3. It’s the way for a Python function to return CPU control back to the thing that called it, yet also keep its stack state so if that function is called again it picks up where it left off. asyncio in 3.4 is literally implemented just as a bunch of fancy generator functions and lots of yielding everywhere. 3.5 adds the new syntax support with “await”. It also makes async functions into “coroutines” instead of “generators”. But the basic concept is still the same.
So that’s the core async magic. It’s really just a sort of process scheduler for cooperative multitasking. The event loop is the CPU scheduler that invokes tasks in a single Unix process/thread. Tasks politely interrupt themselves by calling yield when they can.
But there’s a lot more in asyncio. A key thing is that there’s convenience functions for places where you are most frequently going to want to yield. Ie: waiting for a socket, or a stream, or a subprocess, there’s convenience code for saying “get me the next bytes from this socket and oh by the way go ahead and yield control until there’s something to read”. There’s also a higher level wrapper for “protocols”.
And beyond that, there’s a lot of building blocks. There are Tasks and Futures to wrap some asynchronous thing in a structure. There’s a “wait()” method for collecting results from multiple asynchronous things. There’s locks and semaphores. Many of these convenience objects seem to basically be wrappers for the basic yield/await syntax.
So I think that’s how it all fits together. Now to translate that theory into actual working code to see if it’s right.
Update: thanks to a reader comment from Luciano Ramalho I read A Web Crawler With asyncio Coroutines and basically have my understanding above confirmed and deepened. Despite the title, the article is really building up a full asyncio implementation from basic Python generators, explaining in detail how everything works. Now that I understand this much better I look forward to forgetting entirely how asyncio works and just embracing and using its abstractions. If it’s well designed, it should be usable without knowing how it was implemented.
My gaming group is switching from Slack to Discord. It’s a nice product. It’s sort of a Slack clone with voice channels as the big added feature. It’s also a product aimed at gamers, not corporate use, so there’s some hope the pricing and features will make more sense for gamers. I like the product, it’s worth a look.
So now I need to make my Slack bot post to Discord, too. Discord currently has no formal API. There is a fantastic group of hackers doing an Unofficial API project, though, and the company seems OK with it. Compared to most hacking projects this one is particularly well documented and organized. I dove in this morning and figured out how to write my own bot that works with the Discord API.
First, some resources:
Unofficial Discord API. They’ve basically documented the REST API and WebSocket stuff the product uses.
Unofficial API Discord server. This is a Discord server that API developers share. It has lots of neat stuff in it, not just chat. The #info channel has great stickies on it with links to libraries, docs, etc.
The Python client is very nicely documented and organized. If you’re starting afresh you want to get version 0.10.0a, the alpha, directly from GitHub. PyPI currently has 0.9. 0.10 has reorganized the API, no reason to use the old one now.
The client itself is entirely based on Python 3.4’s asyncio (with preference for the new 3.5 syntax if available). That means you basically have to do everything through an event loop, which is a bit of a nuisance for simple things but absolutely necessary for building real software that’s going to interact with a Discord server. it also means discord.py only works with Python 3.4 and later. I think that’s all the right choice.
Here is my demo program. It took me a couple of hours in total, half of which was me reminding myself how asyncio works. All in all pretty straightforward, once you figure out the basic paradigm of how it fits together. There’s one choice embedded in my code here, which is I subclassed discord.Client instead of using the function decorator syntax for declaring event handlers. Either works fine.
The unofficial API also makes me understand the Discord product a little better. Unlike Slack, Discord has a notion of a single User that is logged into Discord with an email/password. That user can then be a member of various Servers, each of which has its own Channels. Slack doesn’t really have a cross-Slack notion of User, every Slack is an independent domain. The Discord API’s handling of public/private/DM channels is also a bit more straightforward than Slack’s.
pytest-watch is a fine quick “continuously run my tests” thing for Python in a tty. It’s nothing fancy, and the default UI is not perfect. But with -c and --no-beep and using --runner to run a custom command for your tests, it’s fine. Nice to not have to switch from my editor window to a console just to run the tests.
I’m envious of the NodeJS folks and their hipster test runners, they are very nice. Alternately I wish there were a good way to turn SublimeText into a bit more of an IDE with debugging and test output parsing. But after years of trying IDEs and going back to plain text editors, I think I’m not going to try to board that ship again.
Learned about a nice tool today: sqldiff. It shows differences between two sqlite databases. Particularly nice with the “--schema” flag, so you can just compare schema differences. I’m in the middle of database versioning hell as I keep iterating my lolslackbot project. Beginning to regret rolling all the database stuff by hand instead of using some ORM.
I continue to write my LoL Slack bot with sqlite3. I can live with the primary drawback of sqlite3, which is that writes require a database level lock (ie: no table or row locking). In normal use I should only ever have one writer to the database anyway. But I still have a nagging feeling I should use “a real database”. Ie: Postgres
The nervousness is I’m writing more complex code that’s wedded to sqlite. I’m using sqlite’s upsert equivalent, for which there is no standard syntax. I’m also using sqlite’s Python convenience feature of not using cursor objects. And just now I’m starting to pay attention to Python’s weird transactional semantics, which I suspect might be different in Postgres. In short my code has been dating sqlite for awhile but now things are getting serious and I’m getting commitment anxiety. Also Postgres has some alluring features I could use, like JSON and array types.
The underlying question is whether Postgres is really “better” for my kind of application. I suspect not, and part of why I stick with sqlite is to test that assumption, but the cost of being wrong is getting higher. The flip side is managing a Postgres daemon is still a PITA. Particularly on Ubuntu where upgrading is scary.
One small thing in Python3 that continues to confound me is how dict.values, dict.keys, and zip all don’t return real collections but instead iterables. That means you have to wrap them first in a tuple or list if you want to array index the output. It’s not a huge deal, but it’s a nuisance.
So which is better? Tuple or list? Tuple should be in theory, because it’s immutable it should be a little more efficient. Seems to be that way in practice too.
$ python3 -m timeit 'tuple({"a":1}.values())[0]'
1000000 loops, best of 3: 0.266 usec per loop
$ python3 -m timeit 'list({"a":1}.values())[0]'
1000000 loops, best of 3: 0.331 usec per loop
$ python2 -m timeit 'tuple({"a":1}.values())[0]'
1000000 loops, best of 3: 0.227 usec per loop
$ python2 -m timeit 'list({"a":1}.values())[0]'
1000000 loops, best of 3: 0.256 usec per loop
(You know, every time I do a timeit on python2 vs python3, python3 is measurably slower. Some of that is due to Unicode but I don’t think that’s all of it.)
I need to do a better job mocking out HTTP requests to allow me to test all this web API code I’ve written. Right now I rolled my own bad mocking around a wrapper for all the REST calls, but I think it makes more sense just to mock at the HTTP level.
A quick Google search reveals three modern libraries: requests-mock, responses, and httpretty. After literally tens of minutes I’m left with the opinion any would work. responses-mock looks like the most mature and complete product. I like responses for its simplicity. The main differences between the three are the mechanism they use to intercept HTTP calls. I believe httpretty is the only one that works with an HTTP library other than Requests. OTOH why would you use any other HTTP library in Python?
Update: since doing this exercise I started using requests-mock. I’m quite happy with it.
Some detailed notes below, then my test code.
requests-mock: mocks out Requests by installing a Transport Adapter. (I’m endeared, because I came up with a similar technique on my own for Java back in 2000 or so.) Has detailed support for matching full URLs or parts of URLs or specific query strings or URL regexps. Supports all HTTP methods. Responses can be text, JSON, byte strings, or callbacks. Has a way to inspect which URLs were called. Has great docs.
Responses: mocks out Requests using the unittest.mock library, patching requests’ send function. Supports matching on regex, but no special support for query strings in URLs. Responses can be text or JSON or callbacks. Supports all HTTP methods. Optionally throws an error if not all URLs were accessed. No fancy docs, but the code is easy to read. Motivation in this blog post.
httpretty: works by monkey patching sockets. that’s terrifying, but kinda neat because it can mock out HTTP from sources other than Requests. Oddly they don’t have official Python 3 support (it seems to work though). I didn’t look at all its features in detail.
(BTW, unittest.mock was new to me, a very nice standard library for monkey patching any Python library for unit test mocking. That could come in handy in lots of places.)
Here’s my test / sample code.
#!/usr/bin/env python3
import requests, unittest
import requests_mock, responses, httpretty
def fetch():
"The method we'll be mocking"
r = requests.get('https://www.somebits.com/robots.txt')
return r.text
class TestStuff(unittest.TestCase):
def test_real(self):
self.assertEqual(107, len(fetch()))
def test_requests_mock(self):
with requests_mock.Mocker() as m:
m.get('https://www.somebits.com/robots.txt', text='nelson-requests-mock')
self.assertEqual('nelson-requests-mock', fetch())
def test_responses(self):
with responses.RequestsMock() as r:
r.add(responses.GET, 'https://www.somebits.com/robots.txt', 'nelson-responses-mock')
self.assertEqual('nelson-responses-mock', fetch())
def test_httpretty(self):
httpretty.enable()
httpretty.register_uri(httpretty.GET, "https://www.somebits.com/robots.txt", 'nelson-response-httpretty')
self.assertEqual('nelson-response-httpretty', fetch())
httpretty.disable()
if __name__ == '__main__':
unittest.main(exit=False)
# Verify the environment is left clean
assert 107 == len(fetch())
print("Real requests are working again.")
Ran into a couple of odd problems when doing database schema migrations on my sqlite3 database.
Transactions don’t work like you’d expect in the sqlite3 command line tool! I wrote a few lines of SQL to create a new table and drop an old one, then fed that script to sqlite with the command line tool like this: sqlite3 my.db < script.sql. I was clever and wrapped my script.sql in a “begin transaction... commit” so that if there were any errors, nothing would be committed. Smart, right? Wrong. sqlite3 will gladly execute line n+1 in a script it’s fed even if line n fails. This makes sense for interactive use, but is a disaster for a script that wants a transaction; the commit at the end will always run. The solution is to put .bail on in the top of your script so any errors cause execution to terminate. See also this discussion.
I was using an “insert or replace” command to be sure I only had one row per key in my database, along with a unique constraint to tell the DB what the key was. Only I didn’t actually add the unique constraint during my migration, because it’s a PITA to do schema changes like that in sqlite3. unique constraints are only hints, right, it’s like a type checker! Well not if you rely on the constraint violation enabling an “insert or replace” to work. Oops.
Still working away on my LoL / Slack bot. Today’s project was rejiggering all the code to use a new synthetic “personId” as the primary identifier. Previously I was using “summonerId”, but that’s only unique to a single region (like North America) and now I need to make the thing work for multiple regions.
Scary code change because it touches all the files and a lot of assumptions. But no changed types; it’s swapping one int for another. My simple test suite paid off in spades here, giving me the confidence my changes worked. So far so good!
I even had to do a database migration, adding a column to a couple of tables. That I just hacked up by hand but it seems to have done the job. I need to do another now to drop the superfluous column. Unfortunately sqlite doesn’t really support dropping columns, will have to do some more complicated stuff involving creating a new table and renaming it.
One of my successes in my professional career has been advocating for unit testing. I helped lead the charge for automated unit test suites inside Google, particularly for our Java code, and that ended up being hugely useful.
I’m nowhere near as disciplined when I’m working alone on my little hacks. It’s still just too much effort to write tests! It feels like twice the work. For a long lived software project with many users, sure, it’s worth the investment. But a one-off hack you’re not going to ever pick up again? Is it even worth the bother of remembering Python’s baroque unittest syntax to set up a test framework? (I have to look that up every... single... time...)
But small hacks have a way of becoming bigger things, vital projects. I’m continuing to work on my Slack / League of Legends integration. I may even get a bunch of new users, I found a community of a few hundred people who could use it! Yay! But I’ve gotten to a point of paralysis where I was afraid to make changes because I couldn’t tell if I would break things other than pushing it to the live system and then see if cron mailed me any errors. Derp.
Unfortunately this project is particularly thorny to test. I’m integrating with two different online APIs (Riot and Slack). I’m also storing data in a database, and I’ve still never seen a good solution for mocking out a stateful database. For now I’m just going with ugly hacks. I’ve put wrappers around the Riot API calls that will load canned data from a pickle, a sort of persistent memoization. And I’m just accepting the test script needs to create a fresh test database and populate it from scratch. That’s not the ideal of unit tests, but it is still some form of useful automated testing.
I already feel relief and confidence from having even something very basic in place. Now I can type “./test.sh” before deploying and at least know if the scripts are going to blow up on some really stupid error. And I have a place now to add more sophisticated tests for correctness.
Update boy what a difference that simple test suite has made. I’ve felt free to make way more aggressive changes to my code now. Without fear.
I’m writing a fancy Slack bot to post messages in a Slack for 500+ users. Fun!
There are at least three different kinds of things a Slack bot can post to:
Channels. These are the public channels like #general. Find them with channels.list. Bots can’t call channels.join; I think they’re de facto members of all public channels.
Groups. These are private channels. The bot has to be invited via /invite, then it can see the group IDs with channels.list.
IMs. These are direct messages. You can see all of a bot’s IMs with im.list. I think someone has to message a bot first before the IM channel is created, not sure how a bot can initiate an IM (if at all).
I mostly like the Slack API but it’s a bit warty for things like this. My impression is it’s grown organically and they’ve never gone through and deprecated old stuff. It’s nice that old code keeps working, but it’s a bit confusing if you’re starting now. I’m also really confused about the various kinds of integrations, bots, applications, etc.
I wrote about wanting a better Python object for JSON. Now I’ve tried out a bunch of options, all inadequate, and am clearer what I want.
The best of the libraries I found was addict. Or maybe easydict because it is slightly less magic. dotmap is also OK but has one wrinkle. attrdict was the only one I couldn’t make work well.
I’ve put sample code exercising various libraries in this gist.
Here are the things I want, in order of priority:
Dot access to fields instead of []
Sensible default value for missing keys instead of an exception
Ease of adding new nested values
Ease of serializing to JSON
Small performance hit
All the libraries provide #1, dot syntax for reading keys. The challenge is #2, what happens if the field is missing (like d.noObj in my code). dotmap and addict both return an empty dict {} for missing keys. That’s not a terrible default although I’d prefer None. attrdict.AttrDefault() lets you choose a different default value but has other problems. easydict just throws exceptions for missing keys; making the dot syntax of questionable usefulness.
The tricky thing is #3 and it ties to what happens if you then assign to an empty dict for a missing key. That’s required for convenient syntax for setting a deeply nested value, the ideal syntax of “d.other.nested.thing = 6”. Both dotmap and addict actually create an empty dict value in the data structure the moment you try to read an empty key. That lets nested assignment work, but leaves litter in your data structure. addict edges out dotmap here because it provides a .prune() method to remove them. easydict doesn’t create empty dict values, so nested assignment isn’t convenient but then it’s less magic.
#4, JSON serialization,is not too hard in any system. addict, easydict, and attrdict just let you pass the thing to json.dump(); their objects are subtypes of dict. dotmap requires you explicitly call .toDict().
I did not measure #5, performance. Each library has a different approach to when it copies data, would be worth examining.
I mentioned above I couldn’t make attrdict work for me. That may be my error, not the library’s. It’s neat in that there’s actually two options; AttrDefault, which provides alternate default values, and AttrDict, which is a bit simpler. But AttrDict has a mysterious / confusing design wrinkle for “Recursive attribute access” that’s a n00b trap. And I couldn’t figure out how to JSON serialize an AttrDefault, nor even how to turn it into a normal dict. Maybe I missed something.
Doing this exercise made me wonder about the wisdom of #2, sensible default values. The problem is there’s not a one-size-fits-all default. Often you want it to be None, for simple primitives. But sometimes you might want [] for an empty list or {} for an empty object. If you want to let the programmer choose those values, you might as well go fully verbose and use the dict.get() method with its default value.
I could see using EasyDict in the future if I only wanted to read JSON and weren’t worried about #2, missing values. It’s the least magic. Or else Addict if I also wanted to construct JSON and get empty dicts returned for missing keys.
Update: it strikes me that a lightweight use of JSON schema would be helpful here. If you know what types to expect, you can fill in any missing keys with appropriate empty values. Not sure anyone uses JSON schema in the wild though. I’d want to start with something that auto-infers schema from examples. And I don’t care about validation, just using type expectations as hints on what to do with ambiguity.
Update Nov 2019: see FlexDict. It has solutions for the creating-objects-for-keys problem.
Python’s default JSON package encodes and decodes to a dict. This works well enough, but I’ve never much loved the dict type in Python. I’d rather it were an Object with attributes. dicts are verbose: data[“foo”] instead of data.foo. Also dicts throw exceptions on unknown keys, when often what I want is it just to return None. So I’m left with data.get(“foo”, None) which is awfully wordy. Basically I want something that’s as convenient and sloppy as Javascript objects.
I asked on Twitter and got some suggestions, none awesome.
Not sure if these imply overhead from copying, etc. Also they may not serialize well in the JSON module, although I imagine you can copy out a dict view on at least one of these. (More overhead!)
sqlite has a nifty feature; “on conflict”, aka “insert or”. You apply it to insert and update operators to tell sqlite what to do if the operation would violate a constraint like unique or not null.
I’m working on a Slack integration that marries the Riot games API to the Slack API, for a group of League of Legends gamers I play with. I’ve been doing simple message posting from a cron job for 6 months now and it works great. Now doing fancier stuff.
I’m not a fan of the message formatting options. There’s the basic markup which they call “markdown” even though it’s not markdown. Then you can add attachments which has a bit of a tabular layout to them but it’s not very flexible. I can’t make it look like what I want, so I’m reduced to doing fixed-width formatting of plain text. Ugly. I wish they’d let me do free form HTML but I guess they’re aiming for display consistency so don’t want that.
I am impressed with how easy it is to add basic slash commands though. You can just create a “Configuration” that causes /foo to fire off a POST to the URL of your choice. Done! There’s fancier stuff for installable commands, too.
Last comment; the slackclient.py that looks official is not awesome. There’s no proper release schedule so what’s on PyPI is out of date. And it seems to rely on an odd websockets implementation. I may want to look into alternative Python wrappers if I do anything too complicated. I’ve only been using the REST Web API so far, not any streams.
I want to write a Slack bot that sends IM Direct Messages. It’s a bit indirect in Slack. You have to first call im.list to get a list of all the “DM channels” the bot can write to. Then you have to look up the user info for each channel to figure out which person it actually is. Here’s some throwaway code that does that.
Bonus wrapper for the official Python slackclient library to decode the response and throw appropriate exceptions. That library has gotten little love from Slack, it could use some help.
from pprint import pprint
from slackclient import SlackClient
import json
_slack = SlackClient("SECRET")
def slack(*args, **kwargs):
"Wrapper for Slack API. Manages stub, also decodes responses and raises exceptions"
rb = _slack.api_call(*args, **kwargs)
r = json.loads(rb.decode("utf-8"))
if r.get("ok", False) != True:
raise Exception("Error making Slack call", r)
else:
return r
imList = slack("im.list")
for user in imList['ims']:
pprint(user)
info = slack("users.info", user=user['user'])
pprint(info)
I decided to try something naïve and put big JSON blobs in a sqlite3 database. About 1700 of them, 150k each, data from League of Legends matches. I knew this was dumb but I did it anyway. And it was dumb, like 300MB of dumb. To be fair sqlite3 handles this just fine, but the single big file makes backups and caching awkward. And I wasn’t even using the column!
I rewrote the code to store the JSON blobs as gzip files instead. 36MB instead of 300MB, and each file doesn’t ever change once written. Just nicer all around. Kind of a pain to remove the data though. sqlite3 doesn’t let you drop columns so you have to make a temporary table to remove it. And even then the file didn’t get smaller on disk; I ended up doing a dump / restore to reclaim the space.
I still want sqlite-for-JSON, a simple JSON datastore. I see the JSON1 module made it into sqlite3 3.9, no longer draft. I should try it out. It’s not compiled in by default. Also I assume it’s not compressed. sqlite3 does have compressed database support, but only as a paid extension.
JSON is stored as type text. No binary encoding, the docs say the improvement isn’t worth the trouble. JSON arrays are used as a container type in parts of the query language, for things that return N JSON blobs. There’s also some SQLite virtual tables that are created by advanced query methods.
There’s the basic functions you’d expect for manipulating JSON, mostly setting and changing properties on a JSON object.
For basic query, json_extract() is the basic function that pulls out pieces of a document based on a query path. (Ie: $.title means “give me the title property”, $.authors[2] means “give me the 3rd element of the array that is the value of the authors property”)
For advanced query, json_each() and json_tree() turn a single JSON blob into a virtual table you can then query. The table has a schema with one JSON column per property queried, as well as some other data related to the query like integer IDs and the path. json_each() only queries the top level properties, json_tree() is a recursive search.
I like it, it looks really promising. Maybe not quite ready for civilian use yet, but soon? The discussion a month ago advises we “check back soon”.
My one mild concern is that JSON data tends to be really big. Like I have 1000 LoL matches in a SQLite database, each one a 200kb JSON blob. And no surprise, it’s a 200MB file! That starts to get awkward for backups, etc, and is kinda dumb since the JSON is immutable. It’d be better to store them as read-only files but that’s not compatible with SQLite’s design.
JSONlite
JSONlite is the topic of the HN post that let me to JSON1. It’s a valiant effort, a set of bash scripts to store JSON as files and retrieve them with UUIDs. It’s not a bad little wrapper but it’s very simple. And no query interface, which to me is the interesting part, although one could probably just use jq on the backend store.
UnQLite
UnQLite also came up, in this description. “UnQLite is to MongoDB what SQLite is to Postgres”, which sounds good to me! It uses Jx9 for query. I didn’t look any further; it seems promising, but my general rule with tech like this is wait for critical mass before investing any time.
IPython notebooks (ie: Jupyter) seem like an important innovation for me. A really nice web-native REPL for exploratory programming, including decent visualization of data. Plot data in particular, graphing with matplotlib. It’s quite capable, I think approaching what people do with R.
So I’ve been asking around about adding geodata capability to Jupyter. My first thought was a visualizer for GeoJSON, but I’ve learned now there are other approaches. I asked SeanG and he pointed me to a couple of things, which lead to some other things.
Summary: there are several geodata visualization packages that work with IPython. Some integrate with matplotlib and some are standalone geographic tools. None of them quite worked right for me after just a few minutes tinkering, but several seem worth the effort to get working.
folium is closest to what I’m looking for. It’s a Leaflet wrapper for Python with baked in support for geojson, various Stamen tilesets, etc. It seems to support inline plots in IPython notebooks but I couldn’t figure it out, there’s been some discussion that it should work. It doesn’t use matplotlib.
leafletwidget is another Leaflet-based map making tool, here’s an example notebook screenshot. It’s not packaged on PyPI and hasn’t been updated in awhile, looks like it’d take some effort to figure out how to use. But it might be a good basis for building my own thing.
mpleaflet lets you visualize matplotlib plots using Leaflet to add a geographical basemap. It looks very promising but I had some trouble using it out of the box. The key thing here is adding map capability to matplotlib, the primary charting visualization library IPython users use already. Seems good for data visualization but less map-specific.
matplotlib basemap toolkit is a more low-level tool for making maps with matplotlib. No Leaflet or otherwise fancy slippy map, it’s just helping you do map projections and draw geographic data in a single static image. Might be nice for one off visualizations!
cartopy is another non-leaflet map maker in python using matplotlib. It has support for using GoogleTiles. IPython support is not mentioned in the docs but it seems to work.
mpld3 has nothing to do with maps but is neat. It adds D3 rendering for matplotlib plots in your notebook, so you have fancy interactive javascript instead of a static image. Works great right out of the box. I want something that works like this for geodata. See also mplexporter, which seems to handle getting the data out of matplotlib.
GeoPandas is a bridge between Pandas and geographic data, including shapeley/fiona support. It uses descartes too, which is a bridge from geodata to matplotlib plots.
I do a lot of work with CSV files, and up to now I’ve been mostly doing clumsy stuff with standard text tools like “awk -F,” and the like. Here’s a roundup of some Unix command line tools for working with CSV files, lifted from One Thing Well
xsv: slice, split, summary stats, etc. also supports creating a quick index to accelerate things. Seems pretty solid. Rust program, which is awfully weird, but he provides a Linux binary.
csvkit: suite of programs for manipulating CSV. Includes import/export to JSON, Postgres, Excel, etc. Also has a SQL query via in-memory sqlite3. Python program.
Miller: “like sed, awk, cut, join, and sort for name-indexed data such as CSV”. More limited queries than xsv or csvkit. But it embraces more input file types, including CSV files that change schema and arbitrary keyword/value data. Seems perfect for the “long list of JSON object” files I often work with. (Although no JSON support?!)
csvfix: thin docs, another xsv-style tool. Has more operations than other tools.
q: SQL queries on CSV files via sqlite. Python program.
fsql: SQL queries via some Perl SQL implementation. Supports JSON and YAML.
I just tried xsv and it’s quite nice, may be the closest to what I need day to day. I’ve used q before and remember it working nicely, albeit a bit slowly. Arbitrary SQL is appealing.
A Twitter friend proposed an idiom for doing something N times in Python I hadn’t seen before, Using itertools.repeat instead of range. I was curious if it was better.
$ python3 -V
Python 3.4.3
$ python2 -V
Python 2.7.10
$ python3 -m timeit 'for _ in range(10000): pass'
1000 loops, best of 3: 275 usec per loop
$ python3 -m timeit 'for _ in itertools.repeat(None, 10000): pass'
10000 loops, best of 3: 133 usec per loop
$ python3 -m timeit 'for _ in itertools.repeat(1, 10000): pass'
10000 loops, best of 3: 130 usec per loop
$ python2 -m timeit 'for _ in range(10000): pass'
1000 loops, best of 3: 218 usec per loop
$ python2 -m timeit 'for _ in xrange(10000): pass'
1000 loops, best of 3: 179 usec per loop
$ python2 -m timeit 'for _ in itertools.repeat(None, 10000): pass'
10000 loops, best of 3: 122 usec per loop
So huh, itertools.repeat is about 50% the cost of using range. We’re only talking 13ns per iteration, or roughly 50 CPU cycles. If you’re doing meaningful work in that loop it won’t matter. Still it’s neat that itertools.repeat is more efficient. Perhaps this shouldn’t surprise me, it doesn’t have to do the work of generating increasing integers. But I’d assumed no one had optimized itertools this carefully.
Note that in Python3 range is an actual type and doesn’t create a list, tuple, iterator, or generator. Also interesting that repeating an integer is 3% more efficient than repeating None; that’s a reproducible result.
Python2 is faster across the board. I see that a lot in Python and it makes me wonder. But the itertools vs. range/xrange difference is still about 50%, or meaningful.
Having now understood all this I’ll go right back to using range() like my grandpappy did.
Following up on an earlier post, a roundup of some systems for querying JSON documents. I’m looking for small data extraction languages that make it very easy to extract bits of data from a bunch of JSON blobs. Kind of like regular expressions or XPath or CSS Selectors. A key thing here is being able to do stuff like “find me the parts of this JSON document that have a property foo with value bar”. Also dealing with arrays intelligently.
jq. It’s the most popular JSON query language, and quite powerful. I also find it really terse and confusing but maybe that’s because I don’t use it enough. But it’s definitely the tool to compare everything else to. There’s also been some work on a usable libjq so you can use it inside other languages, like these Python bindings.
OboeJS. It’s a streaming JSON parser but also has an XPath-like language for pulling out chunks of a document. I like the look of it.
jsonfilter is a very simple grep-like tool that works with hierarchical input. It looks good and simple for doing simple things. The author is someone I trust to think a tool like this through.
Postgres. It has native support for JSON types and a pretty decent set of functions for working with it. It also has functions for converting JSON to Postgres’ array and recordset types, which you can then further query. And the JSONB type has a few extra query options. I don’t think I’d load data into Postgres just for JSON queries, but if you have JSON there already it’s pretty powerful.
MongoDB’s JSON query language is surprisingly limited for a system that’s all about searching JSON documents. Maybe that’s just my ignorance, but I can’t find any operators for diving into the document structure other than basically walking the JSON document tree manually.
Other options I didn’t explore. #1 question is whether these have momentum and/or a future. A bunch of them look active on first glance. Will update as I read about them and find anything interesting. There’s a bunch of other things not on this list, too.
Update: in further discussion, pvg notes it’s helpful to split JSON query systems into two groups: “QLs that do selection/filtering and QLs that do that and also processing and sorting and munging and aggregation and summing and map/reduce and ...”.
I really want a system that does all the processing and sorting and munging too. But SQL is very good at that already. So really I just want to do some simple extraction with jq or whatever and then feed it to a SQL system for aggregate reporting. Or else maybe just use Postgres to do everything? I need to get my hands dirty with some feature extraction examples to see how jq / postgres / etc feel.
It always bugged me that standard databases use integers as IDs. Not just databases: all sorts of systems, anything with a notion of identity ends up with an “id” token, and the type of that token is almost always “integer”.
The problem is that “integer” has a lot of baggage. An integer is something you can do arithmetic on. It makes no sense to divide one id by another, or add two ids together, or do almost any other arithmetic operation on. The one exception is adding one to an id, as in an autoincrement column for the primary key. But even that’s really a mistake a lot of the time, because those IDs have a way of leaking to the public in URLs and JSON blobs. I can’t tell you how many sites you can estimate growth on by just looking at message IDs or customer IDs or whatever.
My ideal world would be to have a separate “id” type in SQL which has very few operations defined on it. That’s boiling the ocean though. A close second is just to use “text” or maybe “blob” as the ID type. But in practice that doesn’t really work very well. It ends up using more storage even if it shouldn’t have to. And I have to believe indexing and searching text columns is in practice more expensive than integer columns.
I like SQLite. It’s such a nice simple data store. It’s fast for small data (< 100 MB), it requires no separate daemon process, it has great support in every language I work in.
I like JSON and the idea of schemaless databases. I want to be able to download JSON blobs from an API or create some new JSON blobs and store them away with a minimum of effort. Typeless. Then I want to be able to query them somehow.
Now I want to mix the two together. I want to take a bunch of JSON objects and store them in somewhere simple, then query them.
MongoDB was the first big “store a bunch of JSON”. It sort of fits the bill for what I want, but it’s way overengineered for my needs. I don’t want a separate database process. I definitely don’t want a separate cluster of database processes. Also MongoDB is fundamentally untrustworthy and should not be used by anyone for anything serious. It might be OK for my casual hacking, particularly without clustering, but then you run into the way the query language is so awkward.
Postgres has decent JSON support with some queries. I will probably try that for my next hack. Unfortunately it requires a separate database process and I prefer the simplicity of sqlite’s “just open the file” design. But I have a Postgres instance lying around already so what’s one more database?
I’m trying out IPython. I’m also playing around with machine learning which means I need some simple data visualization, so I’m playing around with matplotlib. Here’s how to display generated plots inline (as opposed to in a popup window); the docs are inconsistent.
QT: ipython qtconsole --matplotlib inline
Notebook: launch with “ipython notebook”, then run “%matplotlib inline” in a notebook.
Here’s a sample program that generates and shows a plot:
from matplotlib import pyplot as plt
years = range(1950, 2020, 10)
gdp = [300, 543, 1075, 2862, 5979, 10289, 14958]
plt.plot(years, gdp, color='green', marker='o', linestyle='solid')
plt.show()
Dusting off some old Javascript, I’d forgotten how to run my Mocha / Chai test suite. Running “mocha” in the main directory is the basic thing, it finds tests in a subdirectory named “test”. The nice way to run it continuously is
Brad Fitz’s tweet about how bash treats $@ vs “$@” had me curious. The man page explanation is confusing but indicates these are different.
When the expansion occurs within double quotes, each parameter expands to a separate word. That is, “$@” is equivalent to “$1” “$2”
So what does this mean in practice? Some code:
#!/usr/bin/python
"Print out how many command line arguments there are"
import sys
print "%d %r" % (len(sys.argv)-1, sys.argv[1:])
#!/bin/bash
echo With Quotes
./printargs.py "$@"
echo Without Quotes
./printargs.py $@
$ ./quote.sh foo "bar baz"
With Quotes
2 ['foo', 'bar baz']
Without Quotes
3 ['foo', 'bar', 'baz']
To me the quoted “$@” does what I expect; do its best to pass the arguments along verbatim, as the shell script was invoked. That rewards some advice I learned 20 years ago to just always quote “$@” in shell scripts and the right thing would happen. But if I think about it harder I get confused. For matters of shell quoting and expansion, best not to think too hard.
I wanted to give a CGI script access to one specific postgres database, both read and write. This is remarkably complicated. I ended up creating a password protected role named “oarunone” and gave it access to a database named “oarunone” (yes, confusing) and one table named “queue”. Something like:
create role oarunone with password ‘secret’;
grant all privileges on database oarunone to oarunone
grant all privileges on table queue to oarunone
But that’s not good enough. Ubuntu’s default postgres only identifies users via the Unix UID. So you also have to add a line like this to pg_hba.conf. and it has to occur before the catch-all “all” rule.
local oarunone oarunone md5
That says allow the role “oarunone” to authenticate with a password (MD5ed), but only from a local Unix domain socket and only to the database “oarunone”.
Update 2017: psycopg2 now has fast execution helpers. Not sure why they didn’t just improve executemany.
I’m using a Postgres server in AWS in the us-east zone. My database client is running in California, so it’s about 150ms away. I do not expect this to be fast. However I don’t expect it to be super-slow either. Inserting 700 rows in a single transaction was taking 60 seconds. That’s absurd! (Rows are ~100 bytes each, this is not a lot of data).
Thanks to StackExchange I found a solution. Here’s some untested code that illustrates the idea:
# Clearly slow to insert one row at a time
for row in myData:
cur.execute('insert into data values (%s,%s,%s)', row)
# Should be much faster, but isn't
cur.executemany('insert into data values (%s,%s,%s)', myData)
# This hack is much faster
dataText = ','.join(cur.mogrify('(%s,%s,%s)', row) for row in myData)
cur.execute('insert into data values ' + dataText)
That funky last idiom basically expands all of myData into one giant SQL string with multiple values. For my use case, that 60 second operation went down to 1.5 seconds. This hack works, but you’re going to bump into a query size limit at some point.
Note that mogrify() isn’t doing anything clever, it’s just doing safe expansion of SQL query strings to avoid Little Bobby Tables. (There’s a Unicode error lurking here; I switched to Python2 just to make this work.) Also note that transactions don’t seem to be to blame here. psycopg2 by default runs a transaction for every connection; nothing commits until you call commit().
I think what’s going on is that psycopg2 doesn’t optimize the implementation of executemany(). Internally it’s just doing something like a loop calling execute() for each row. I don’t have proof of that, but my research turned up other people saying that was the problem. (See here)
(As an aside, what is it with database adapters for various languages that make them so universally bad? psycopg2 isn’t terrible, but it’s hardly joyful Python software. At least it’s better than the mess we had with mysql for so many years. Back in the Java days we used to have a terrible time trying to talk to MySQL as well.)
I’m looking at buying a hosted/managed Postgres in a cloud server. Amazon or Heroku.
Amazon RDS has a confusing array of pricing options. The smallest instance (db.t2.micro) is $0.018 / hour, or $13 / month if it’s always on. Data costs $0.115 / GB-month, so a 64GB database would be $7 / mo. Total cost for a smallish database: $20 / month.
Heroku Postgres has a very limited free tier. The hobbyist tier is $9 / month and gives you “10M rows” with who knows what performance. The basic standard tier starts at $50 / month for a 64 GB database. Hard to say for sure, but I think that’s roughly comparable to our $20 / month database on Amazon.
Of course what really matters for a service like this is price scaling, how easily you can add more performance and what you pay for it. I’m not worried about that for my small project, just good to have some ballpark numbers.
More and more web pages have broken the page down key. Fixed-height headers and footers on top of web content don’t bother me, but the article underneath them never pages correctly. Because it’s paging the full window height and the header/footer has hidden part of the document, so you never see it.
This used to only be a problem on shitty websites that had all sorts of bad layout. But now even high design websites like the In Focus photojournalism gallery have broken the paging behavior with a header. Medium was a holdout for a long time, it even had a fancy thing where the header hid itself when you scrolled down a page. It still does that but now there’s a fixed 20px footer that obscures text that disappears when you page down.
What I’m wondering is why no one fixes this with Javascript. Maybe overriding paging behavior is difficult? I asked Marcin Wichary once about Medium and he said it was hard to make it work consistently in all browsers. There’s certainly ways to scroll the window and I imagine you can trap the page down key to invoke your custom scrolling code. Would be worth tinkering if it could be turned into an extension that worked for sites that don’t work right now.
A Python3 annoyance; zip() now returns an Iterable, not a list. That means you can’t easily slice it.
In Python 2, this idiom for getting back the first column of a database query was useful:
cur.execute('select ...')
r = cur.fetchall()
firstColumn = zip(*r)[0]
In Python 3, this gives you an error
TypeError: 'zip' object is not subscriptable
The workaround is to wrap the zip in a tuple or list
r = cur.fetchall()
firstColumn = tuple(zip(*r))[0]
Annoying, but it doesn’t actually run any slower. I imagine you could use slice() or itertools.islice() to produce an iterator view of a slice of the zip iterator.
I want to draw a time series graph in Javascript. This is one of the simplest kinds of regular data visualizations and all of the libraries I find to do it suck. I looked at this a year ago, is anything better now?
What I want is a library that will automatically assign axes and draw correct time series graphs. The time intervals are not regular. Also sometimes data is missing. Not zero, null. Remarkably, very few charting libraries seem to be able to handle these common requirements. Here is some very quick evaluation, I spent ~3 minutes on each library so may have mischaracterized something or overlooked some greatness.
Charts.js: too low level, really a graphics library for drawing colors in canvas
Flot: good ol’ flot, just seems too old. Maybe that’s foolish and it’s solid?
D3.js: great library but too low level. I don’t want to build my own axis and don’t really want to program at all, just declare data.
Metricsgraphics: promising library at the right level, but seemed buggy. I spent about 90 minutes trying to get a time series to render and depending on my Date range, either got a decent graph or got confusing SVG rendering errors involving NaN.
Rickshaw, xCharts, Ember, and d3.chart look to all have very slow or no development. Rickshaw was promising, I wonder if it’s just “mature”.
NVD3 has been around a long time and is still active. It’s kind of a sloppy project though. The example code on the site doesn’t match what’s live. Some of the examples kill Google Chrome when run. There are no reference docs. I give up.
Vega looks too toolkitty and not enough libraryish. It frames itself as an analog to Protovis or D3, and I already know one of those. Also no time series example.
I need to investigate Highcharts. It’s not free software, but is free for non-commercial use.
dygraphs is sort of promising. It actually plots my data correctly but the default style is ugly. Also I’m not wild about canvas. It does a lot of fancy time series stuff out of the box though.
I’m now using Python3 by default for all new projects. Almost entirely because I prefer sane Unicode handling. But really because Py3 has turned the corner and is now useful for most things. Probably it turned that corner a year or more ago, but it was the OpenAddresses work that made me start using Python 3 regularly. It helps that Homebrew and Debian both make it very easy to install ‘python3’ and ‘pip3’. And of course that most packages I care about are now ported over.
It took Python five years longer than I expected for the Py3 transition to get to this point. Let’s hope we don’t have to do it again.
Trying to get a server up running OpenAddresses in a controlled environment. I’m normally very sloppy and install everything as root in /usr, but I figured I should use virtualenv this time. Machine actually has a very nice Chef setup and bootstraps itself regularly in EC2 and Travis contexts, but I’m stubborn and doing it my own way.
Install openaddresses-machine and it’s simple dependencies
Prepare a virtualenv directory and activate it
pip install Openaddresses-Machine
Install cairocffi. This required a C library I didn’t have
sudo apt-get install libffi-dev
pip install cairocffi
Install Python GDAL. This is a mess; I’m not sure why the simple “pip install GDAL” doesn’t work from inside the virtualenv. And I’m not sure the instructions below are correct; it’s probably installing python-gdal globally on the system via and then again in the virtualenv via pip. But that gets all the C dependencies we need somewhere on the system. There’s extra rigamarole to get the bleeding edge GDAL instead of the stock Ubuntu GDAL. Also building GDAL requires a C++ compiler.
PSYCH! That won’t work. Follow the instructions in this gist for how to manually configure and install gdal. Apparently its packaging is not compatible with pip?
My little Python csv parsing benchmark had one really nice effect; someone contributed a patch to remove some unnecessary calls to isinstance in certain circumstances. He claims a 2x speedup. That patch was just released in 0.11.0, so I tested it. These are the same benchmarks and data file I ran and reported before as “Python 2 results”
Not quite a 2x speedup, but runs in 0.7x or 0.8x the time it used to. That’s quite good for a simple change, and a nice example of open source working well.
I should really stop using the csv DictReader. Or maybe make a new one that’s smarter. The current Python module seems to actually create a real dict object for every row. I think you could make something faster that used a class wrapper for the tuple that emulated dict-style retrieval by looking up column offsets in the row header. At least there’d be less data copied, but maybe the wrapper overhead would negate that. Have to try it to see.
After doing my CSV benchmarks yesterday I decided to do something simpler and just compare how long it takes to read files with and without Unicode decoding. My test file input is a 1.8G UTF-8 text file, the actual data is dk.csv, Danish street names. It’s exactly 1,852,070,317 bytes or 1,838,573,679 characters. The file has DOS newlines, so there’s both a 0x13 and a 0x10 at the end of every line. 33,445,793 lines total.
I didn’t use timeit for a proper microbenchmark, but I did warm the cache and make sure the times were repeatable. Some weirdness; sometimes the job takes 2x as long to run. Cannot explain that, maybe some L2 cache contention in a shared CPU? I took the faster timings.
Reading the whole file at once
Python 2, reading bytes: 0.5s
Python 2, reading unicode via codecs: 5.9s
Python 3, reading bytes: 0.5s
Python 3, reading unicode via codecs: 1.6s
Python 3, reading unicode via open(): 3.7s
Python 3, reading unicode via open with no newline conversion: 2.2s
Conclusions
Python 2 and Python 3 read bytes at the same speed
In Python 2, decoding Unicode is 10x slower than reading bytes
In Python 3, decoding Unicode is 3–7x slower than reading bytes
In Python 3, universal newline conversion is ~1.5x slower than skipping it, at least if the file has DOS newlines
In Python 3, codecs.open() is faster than open().
That last one about codecs.open is really weird. Codecs isn’t doing newline conversion, but even so it’s still 1.6s vs 2.2s. Maybe open() also does some other processing?
Reading the file a line at a time
Python 2, reading bytes: 0.6s
Python 2, reading unicode via codecs: 43s
Python 3, reading bytes: 1.0s
Python 3, reading unicode via codecs: 58s
Python 3, reading unicode via open(): 3.5s
Python 3, reading unicode via open with no newline conversion: 3.3s
Conclusions
Python 3 is ~1.7x little slower reading bytes line by line than Python 2
In Python 2, reading lines with Unicode is hella slow. About 7x slower than reading Unicode all at once. And Unicode lines are 70x slower than byte lines!
In Python 3, reading lines with Unicode is quite fast. About as fast as reading the file all at once. But only if you use the built-in open, not codecs.
In Python 3, codecs is really slow for reading line by line. Avoid.
Overall conclusion
Python 3 UTF-8 decoding is significantly faster than Python 2. And it’s probably best to stick with the stock open() call in Py3, not codecs. It may be slower in some circumstances but it’s the recommended option going further and the difference isn’t enormous.
Some of these benchmark numbers are surprising. My guess is that someone optimized Python 3 UTF-8 decoding very intensely, which explains why it’s better than Python 2. And the really terrible times like 40-50s are because some Python code (ie: not C) is manipulating the data, or else data structures are being mutated and it’s breaking CPU caches.
The code
"""Simple benchmark of reading data in Python 2 and Python 3,
comparing overhead of string decoding"""
import sys, time, codecs
fn = sys.argv[1]
def run(f):
"Run a function, return time to execute it."
# timeit is complex overkill
s = time.time()
f()
e = time.time()
return e-s
def readBytesAtOnce():
fp = open(fn, 'rb')
fp.read()
def codecsUnicodeAtOnce():
fp = codecs.open(fn, encoding='utf-8')
fp.read()
def py3UnicodeAtOnce():
fp = open(fn, encoding='utf-8')
fp.read()
def py3UnicodeAtOnceNoNewlineConversion():
fp = open(fn, encoding='utf-8', newline = '')
fp.read()
def readBytesByLine():
for l in open(fn, 'rb'):
pass
def codecsUnicodeByLine():
for l in codecs.open(fn, encoding='utf-8'):
pass
def py3UnicodeByLine():
for l in open(fn, encoding='utf-8'):
pass
def py3UnicodeNoNewlineConversionByLine():
for l in open(fn, encoding='utf-8', newline = ''):
pass
atOnce = [readBytesAtOnce, codecsUnicodeAtOnce]
if sys.version_info.major == 3:
atOnce.append(py3UnicodeAtOnce)
atOnce.append(py3UnicodeAtOnceNoNewlineConversion)
byLine = [readBytesByLine, codecsUnicodeByLine]
if sys.version_info.major == 3:
byLine.append(py3UnicodeByLine)
byLine.append(py3UnicodeNoNewlineConversionByLine)
open(fn).read() # warm cache
for f in byLine:
t = run(f)
print('%7.2fs %s' % (t, f.__name__))
I tested various ways of reading a CSV file in python, from simply reading the file line by line to using the full unicodecsv DictReader. Here’s what I discovered. Test data is dk.csv, a 3.4M row CSV file with 46 columns. (See also: file reading benchmarks.)
The Python2 csv module takes 2x longer than a naive split(‘,’) on every line
Python2 DictReader takes 2-3x longer than the simple csv reader that returns tuples
Python2 unicodecsv takes 5.5x longer than csv
Python3 csv takes 2-3x longer than Python2 csv. However it is Unicode-correct
Pandas in Python2 is about the same speed as DictReader, but is Unicode-correct.
I’m not sure why unicodecsv is so slow. I did a quick look in cProfile and all the time is being spent in next() where you’d expect. All those isinstance tests add significant time (20% or so) but that’s not the majority of the 5.5x slowdown. I guess string decoding is just a lot of overhead in Python2? It’s not trivial in Python3 either; I hadn’t realized how much slower string IO was in Py3. I wonder if there’s more going on. Anyway I filed an issue on unicodecsv asking about performance.
I’ve never used Pandas before. I ran into someone else saying unicodecsv is slow who switched to Pandas. It sure is fast! I think it’s a lot of optimized C code. But Pandas is a big package and has its own model of data and I don’t know that I want to buy into all of that. Its CSV module is nicely feature-rich though.
Not sure what conclusion to draw for OpenAddresses. I think we spend ~50% of our time just parsing CSV (for a CSV source like dk or nl). Switching from DictReader to regular reader() is the least pain. Concretely, for a 60 minute job that’d bring the time down to about 40–45 minutes. A nice improvement, but not life altering. Switching to Python3 so we no longer need unicodecsv would also save about the same amount of time.
S3 is an easy way to serve data on the web. It’s also pretty limited. One problem is the S3 web servers don’t do gzip compression on the fly. They don’t parse Accept-Encoding from clients and they don’t opportunistically gzip encode responses. Some details in this blog post.
So if you want to serve content gzipped, your only option is to serve it under two URLs; one with gzip, one without. You’re on your own for figuring out how to tell clients which URL they should use. The Amazon docs talk about how to set this up. In particular you want to hack in a Content-Encoding: gzip in the compressed version so the client knows to decompress it.
There is a hack some folks recommend, which is to only serve a gzip encoded version of your file at the URL. This will work with any modern web browser, but it’s not correct. You’re not supposed to serve gzip to clients that don’t ask for it. This actually matters in practice; curl and wget both don’t know how to handle gzip output. So if you do this hack, those clients will see compressed gibberish.
Note also there’s no way to upload to S3 with compression and create an uncompressed file when it gets there. You have to upload the uncompressed thing. Even uploading the gzip file is a bit tricky because you need to know the full file size to do a simple upload. This StackExchange question discusses how you can do a multi-part upload to sort of stream while you compress.
OpenAddresses wants to serve giant CSV files via gzip. I think the right way to do that is to serve the files explicitly as “foo.csv.gz” and serve a gzip binary blob. No Content-Encoding. That will require the client downloader know to decompress it.
For a business that’s all about charging people for storing and serving bytes, it’s kind of surprising they don’t do the simple obvious thing to give you a 75% reduction in the number of bytes you store and serve. I’m not suggesting any nefarious plot here, but I do wonder what it is about Amazon’s serving infrastructure that makes them unable to do gzip encoding.
Update: Amazon CloudFront started supporting gzip in Dec 2015. Not S3 itself though.
Python’s multiprocessing.Pool has a design wrinkle that’s a bit awkward. If you have a pool with N tasks and one of those task subprocesses dies unexpectedly (say, to a SIGTERM or something) then the pool hangs. It looks like N-1 tasks have finished and there’s still one waiting. But it will never complete and your parent process will effectively be stuck. Note that normal termination doesn’t do that, including random exceptions, SIGINT from Ctrl-C, etc. A normal “kill” triggers this though, as certainly does a “kill -9”. Probably a segfault in the Python interpreter will too.
Personally I think this is a bad design choice, but it’s not by accident. There was a huge discussion about this behavior three years ago. I haven’t read it all, but most of the comments seem to be about the wisdom and difficulty of recovering from a bad state. The ticket got closed after someone committed some changes to concurrent.futures (Python 3’s preferred new library). Nothing changed in multiprocessing.Pool.
Recently this issue was revisited for multiprocessing.Pool with a new bug filed that includes a patch. The approach there (and concurrent.futures) is if a child dies unexpectedly, you want to kill the whole Pool immediately with a BrokenProcessPool exception. I’m not wild about this choice, but it’s definitely better than hanging.
None of this applies to the Python distribution we’re running today. The pool will hang. For OpenAddresses I suggest we work around the issue by simply not killing workers. If you want to abort a worker early, try SIGALRM. We could also install a SIGTERM handler to catch the simple “kill” case from an operator, but I’m not sure that’s wise.
In addition, OpenAddresses also has a SIGUSR1 handler that allows someone externally to shut down the whole pool. It’s good for recovering from this state.
Update: we hit this bug again in a new way. Some of the worker processes were getting killed by the Linux OOM Killer. The Python code doesn’t see any exception, it’s just a SIGTERM or something. Only way you know is a record in the syslog. (And the multiprocessing debug logs show a new worker started.)
I’ve never really done much with S3 and now I am. Here are some tools I’ve tried to manage files on S3. None are very good, maybe someone can recommend better?
s3cmd is the common command line tool. It works fine. Despite it looking like an official Amazon product it’s not, it’s “Copyright (C) 2014 TGRMN Software” and seems to be by Matt Domsch.
s4cmd claims to be a better s3cmd. Note that “pip install” installs the program as s4cmd.py. My one attempt to use it (“du”) did not work; said “1 task completed” but printed nothing.
s3 FUSE lets you mount an S3 bucket as a filesystem using userfs. The project comes with a lot of caveats, most notably that S3 doesn’t really have a notion of directories and while everyone mostly uses the same object naming convention to create a hierarchical namespace, it’s not entirely consistent. I didn’t try this one.
Cyberduck is a venerable graphical FTP client for MacOS that has S3 support. It works pretty well, it’s the main tool I’m using. You have to keep pressing “Refresh” if you want to see any updates to the bucket state. Also it complains about certificate names not matching when you run it.
Boto is the Python library everyone uses to write code to talk to S3. Here’s the docs. It does a lot more than S3, it’s a general AWS library.
Credential management is a nuisance. Two big opaque strings for keys and no standard on how to find them.
s3cmd uses $HOME/.s3cfg
boto uses $HOME/.boto
Cyberduck uses the MacOS keychain
The OpenAddresses tools I’m using take -a and -s command line flags.
Environment variables are popular, different tools use different ones. Sadly, environment variables are not private on shared Unix systems. Neither are command line arguments.
One happy side-effect of being so careful working on OpenAddresses is I’ve been finding what look like bugs (or usability difficulties) in other libraries. It’s so easy to just shrug if something doesn’t work and hack around it. I’m trying to dig in and understand failures.
Python issue #23278: multiprocessing maxtasksperchild=1 + logging = task loss. Really nasty, hard to reproduce occasional problem with multiple processes and a task queue losing jobs. Finally pinned it down to a problem using logging from new processes.
Gdal issue #5811: Py3 Unicode problem. Near as I can tell, the Python 3 GDAL bindings simply don’t work with shapefiles that aren’t in UTF-8. I’ve had a hard time narrowing down a small test because the bug is only triggered if OGR doesn’t decide to convert encodings itself and I have no idea when or why it does that.
I managed to get multiprocessing working for OpenAddress job processing. Looks like it’s working pretty well. We use multiprocessing.Pool to manage worker processes, then set up a SIGALRM to abort jobs that run too long. (Using a nifty decorator to add the timeout). I also added a SIGUSR1 handler in the master job process that lets us abort the run. At least once I’ve had the pool fail where there was work being done but none of the worker processes was trying to do it.
Here’s a happy screenshot of htop showing a run going. Note the nifty custom process names courtesy of setproctitle.
I spent a few hours today learning about the Python multiprocessing module. It’s pretty slick, including pickling data structure to pass them around and stuff. I did some fancy work of my own to use SIGALRM to implement a per-job timeout. I think it works., see my sample code here.
Our OpenAddresses system wants to run N jobs at once while downloading and processing our ~1000 sources. Mostly to do a bunch of network requests to various servers in parallel, but also for some CPU parallelism in multi-core systems. Normal jobs use very little RAM (100M?) but occasionally a big GeoJSON file blows up to 2G or 4G. Here’s 4 options for job management.
Unix processes. I’ve been running stuff in GNU parallel, forking off a new Python process for each job. 8 simultaneous processes on a 8 CPU system. That’s worked pretty well, see previous blog posts for notes. CPU usage around 250%, memory usage all over the place but generally under 2G. Full job finishes in 3, 4 hours.
Python threads. I just tried openaddr-process for the first time to run a full go (on the same Linux box). That code works by spawning 16 threads. So one big Python process. That’s not working quite so well. Running at a steady 120% CPU; because of Python’s GIL we can’t get more parallelism. The process also has 11G resident. I suspect much of that could be reclaimed, probably left over from when 2 or 3 big GeoJSON jobs ran at once. But that stresses the garbage collector; there’s something to be said about killing a process. (Update: the resident set size got as big as 17G at one point, enough to force swapping. It didn’t seem to thrash though. Also Python is releasing the memory again later, the RSS has gotten as small as 9G again.)
Python multiprocessing. I want to try this. It should be a relatively easy change from threading, but I am hoping gives some CPU parallelism and memory housekeeping. Also we need a way to kill jobs asynchronously and Python’s threading module is designed to make that possible. With multiprocessing you just send a SIGTERM and are done.
Decoupled task architecture. openaddr-process is structured to do the job as one big long-lived Python process. Even with multiprocessing, when an individual job finishes it’s passing Python objects back to the task manager, which waits 3+ hours to collect them all before formatting the crucial report. This is brittle. Long term I’d like to redesign the system to be more decoupled, so that individual jobs run as completely separate processes and autonomously store state in some persistent storage; files and maybe a row or two in a database. Then the overall Machine monitor can just fork off jobs as it needs and collect data off the database. That’s much more like a task queue architecture, a robust thing. I know how to build this with my own servers, less clear how to match it to the EC2 model of cloud computing.
Following on my OGR/Python vs Unicode work, I took a look at what Fiona is doing. Fiona is a nice Pythonic interface to OGR with a fair amount of Cython code to bridge the gap from the OGR C library to Python idioms. Fiona explicitly returns all strings as u’Unicode Strings’ in both Python 2 and 3 and has code to handle encodings.
Fiona tries to guess encodings. In theory you can override the guess with an encoding=’foo’ parameter when you open a source, but in practice that seems to do nothing. I tried passing in obviously wrong encodings like ‘ascii’ or ‘shift-jis’ and didn’t see any of the expected errors.
Below is the repr of the string Cassiopée as it comes through from the Shapefile in Fiona, with its own guessing. These all appear correct to me. Note that Python 2 encodes Unicode string reprs as ASCII using Python \x escaping, hence the \xe9 in the output. That’s a single character, the expected Unicode codepoint U+00e9 or é.
Good file (ca-qc-gatineau)
Python2. Fiona: u’Cassiop\xe9e’ OGR: b’76 Rue de Cassiop\xc3\xa9e’
Python3: ‘Cassiopée’ OGR: u’Cassiopée’.
Fiona seems to be doing the right thing with both my inputs, returning proper Unicode strings in both Python 2 and Python 3. In Python 2 OGR seems to basically not be decoding at all, just returning byte strings that I’m supposed to decode myself. In Python 3 OGR is trying to return Unicode strings but throws an exception on my bad file.
I think from here, for our OGR code I should add something to explicitly decode strings to Unicode in Python 2 and file a bug in Python 3.
Fiona code
'Extract fields from shapefiles using Fiona, a Unicode test'
import sys, fiona, logging
from pprint import pprint
logging.getLogger().setLevel(logging.DEBUG)
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
enc = sys.argv[2] if len(sys.argv) > 2 else None
with fiona.open(sys.argv[1], 'r', encoding=enc) as source:
for f in source:
for field in f['properties'].values():
sys.stdout.write('%s %r ' % (type(field), field))
sys.stdout.write('\n')
I’ve been trying to figure out how OGR deals with Unicode, particularly in shapefiles, to solve this issue with OpenAddress conversion. I haven’t found clear docs. There’s something about a SHAPE_ENCODING environment variable and something else about OGR trying to guess. More details in that linked GitHub issue. Anyway, here’s what I discovered.
When OGR/Python opens the file, the capability OLCStringsAsUTF8 is set to True.
In Python 2, GetField() is returning Python strings of type str, which means “bytes”. Those strings appear to be sequences of UTF-8 code points, the repr() of that non-ascii street name is ’76 Rue de Cassiop\xc3\xa9e’. Basically OGR isn’t trying to handle Unicode at all for us, or rather if it is it’s returning UTF-8 encoded byte strings and all is well.
In Python 3, GetField() is also returning Python strings of type ‘str’, which now means ‘unicode’. Their repr in Py3 is a Unicode string, ‘Rue de Cassiopée’, which makes sense.
In both cases OGR/Python is doing the right thing, or at least something consistent and sensible.
When OGR/Python opens the file, the capability OLCStringsAsUTF8 is set to False.
In Python 2, GetField still returns ‘str’. And the repr for that street is ‘Now\xe9lei (Jean Baptiste)’. That’s actually not awful; if I know to expect that behavior, I can decode that myself with ISO-8859-1 and get the Unicode string.
In Python 3, GetField() throws an exception.
Traceback (most recent call last):
File /home/nelson/src/oa/shpenc.py, line 17, in &amp;lt;module&amp;gt;
field = in_feature.GetField(i)
File /usr/lib/python3/dist-packages/osgeo/ogr.py, line 3033, in GetField
return self.GetFieldAsString(fld_index)
File /usr/lib/python3/dist-packages/osgeo/ogr.py, line 2362, in GetFieldAsString
return _ogr.Feature_GetFieldAsString(self, *args)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte
I don’t quite understand what is happening here, but I guess something inside the OGR code is trying to decode that sequence assuming it’s UTF-8 and failing. Note my code is not really in the stack trace here, I”m just asking for the field contents. I think this is an OGR bug. Or else I think the Shapefile is corrupt. Setting SHAPE_ENCODING before invoking my code doesn’t help.
Worth noting QGIS displays the string as Nowlei, skipping the non-ascii character.
Summary
It appears that what OGR is doing is trying to guess and cope with the source encoding, presenting UTF-8 byte strings to Python 2 code and Unicode strings to Python 3 code. Which is great! Only things go wrong with the be-flanders file. OGR presents an ISO-8859-1 byte string to Python 2, which you can cope with. OGR crashes in Python 3.
Test code
Here’s the little OGR/Python program I’m using to examine shapefiles. It runs in both Python2 and Python3.
import sys
from osgeo import ogr, osr
ogr.UseExceptions()
in_datasource = ogr.Open(sys.argv[1], 0)
in_layer = in_datasource.GetLayer()
inSpatialRef = in_layer.GetSpatialRef()
in_layer_defn = in_layer.GetLayerDefn()
in_feature = in_layer.GetNextFeature()
print('OLCStringsAsUTF8? %r' % in_layer.TestCapability(ogr.OLCStringsAsUTF8))
while in_feature:
row = dict()
for i in range(0, in_layer_defn.GetFieldCount()):
field = in_feature.GetField(i)
sys.stdout.write('%s %r ' % (type(field), field))
in_feature = in_layer.GetNextFeature()
sys.stdout.write('\n')
The OpenAddresses code includes a Python task manager thats spins off a lot of Python threads, one per input file describing a job. We’d like to capture the debug log records for each thread to a separate file, for presentation in a dashboard. How to do that?
This demo program I wrote shows how. The key concept here is a Python logging.Handler() object that uses some per-Thread state to decide where to write the message. In this case I use the Thread name itself, but you could also use some state stored in Thread.local().
Also this feels related.. log4j had a way to store information in ThreadLocal variables that you could then write out to log files. Ie: you could add a special per-thread variable like “job name” or “HTTP session ID” and have the formatter print it out where appropriate. It was quite handy in some use cases. Python doesn’t exactly have that, but the cookbook has notes on doing something similar with Filters.
Update: see also Mike’s alternate approach. He creates a new Handler for every thread, then uses a Filter to only show messages from the thread he cares about. I like how the approach makes more use of logging’s machinery, it is a bit weird how I had to make a whole Handler that did something odd with the output. I think Mike’s approach means for N threads we’ll end up with N Handlers seeing every log message. That’d be inefficient but if there’s not 100+ threads I doubt it matters.
One of my favorite examples of git’s inhumane tool design is the warning
You are in ‘detached HEAD’ state.
WTF does that even mean? I do something as simple as wanting to look at a version of the code three revisions back and suddenly I’m decapitated? It’s an alarming bit of language, not to mention completely opaque.
Really the concept is pretty simple. The message could read “you checked out a version of the repo that doesn’t match the head of any named branch”. That would explain the state you’re in and be much less alarming. “Detached HEAD” is a shorter way of saying that, but is a bit of jargon that only makes sense to experts. The experts who don’t need that warning anyway.
The problem is git is designed by people who don’t see opacity as a problem. It’s like the Unix philosophy where “cat” mean “show file” and “rm” means “delete” and “grep” means “search”. I’ve internalized all those words 20+ years ago, but I’ve never forgotten how they are barriers to learning.
I’ve been using the recommended idiom of getLogger(__name__) to log stuff in Python code. That’s supposed to turn into your module name so you get nice names like “openaddr.conform” for the file openaddr/conform.py.
Only it totally breaks if you invoke conform.py as a main function via python -m or the like. Because of course __name__ is set to __main__ in that condition.
Wonder why none of the logging tutorials mention that gotcha?
Python 3 changes something subtle in the core dict data type.
$ python2 -c 'print(type({}.items()))'
type 'list'
$ python3 -c 'print(type({}.items()))'
class 'dict_items'
The return type of dict.keys(), values(), and items() is no longer a simple list, it’s some fancy iterable. Unfortunately that iterable type doesn’t support other list methods like sorted. I guess the new type is more efficient, but it sure is a nuisance.
The simple workaround is to turn the result into a list.
sorted(list(myDict.items()))
But it’s more complicated than that, in fact there’s a whole PEP 469 about it.
Update: derp, I made a mistake. There’s no need to make the list, sorted(myDict.items()) works fine. However there are still other cases where you need to turn the dict_items type in to a real list.
I’m mostly having a good experience with Python 3 but run into weird little changes like this that bite you from time to time.
I’ve been running batches of OpenAddress conversion jobs for bulk testing with a simple shell for loop
for f in us-ca-*.json; do
openaddr-process-one "$f" /tmp/oa
done
But it’s better to do this in parallel, particularly since the work is a nice mix of CPU, network, and disk IO. Below is my first ever GNU parallel script to do that.
How much parallel? My system has 16 gigs of RAM and 4 honest CPUs (looks like 8 cores because of hyperthreading). I originally tried running “--jobs 200%” but because of the hyperthreading that results in 16 jobs which feels like a lot. So I’m keeping it at 8.
With 8 jobs in parallel we process 29 files in about 14 minutes. Running that in serial took 48 minutes. Los Angeles County alone takes 11 minutes and Solano County takes 10, so a total of 14 minutes to run 29 files sounds pretty good to me.
us-ca-los_angeles_county downloads fast, all its time is being spent in my Python conform code. There’s 3M rows so it’s no wonder it’s slow, but that seems too slow. Good place to focus some code optimization effort.
Solano county takes 10 minutes to download. It’s one of those ESRI webservice things, 391 requests for 500 records at a time and each one takes 1 or 2 seconds. I’ve been thinking we ought to have a separate pre-caching process for the ESRI combining, store the GeoJSON ripped data in S3 somewhere. There’s no way to test for data changes on the ESRI services so we can’t cache if we go direct, this way we could insulate the rest of the machine from the slowness of the services and the caching problems.
We wrote the code to be careful about RAM, processing everything as streams. Most jobs only take a polite 70M to run, but us-ca-kern, us-ca-marin_county, and us-ca-solano all mapped 1G+. Those are all ESRI type services, maybe the code is buffering all the data in RAM? Need to look more closely.
I suspect the main point of contention for running in parallel is disk IO. There’s a lot of file writing and copying; my own conform code basically writes the whole dataset twice. In theory I could get that down to once but it makes the code significantly more complicated.
Running this in parallel like this makes me realize there’s still work to do on the logging configuration. I want to be able to say “log only to a file named on the command line with a configuration specified in a file named here”; my logging config code doesn’t allow that. I can use the command line config to log to a file, then we just shove all of stderr to /dev/null. It’d be nicer to ask parallel drop stderr from the jobs its running but I couldn’t figure out how to do that. Even better would be to make it so I can configure the Python logging the way I want.
#!/bin/bash
# Quickie script to run a bunch of openaddr-process-one jobs in parallel
srcdir=/home/nelson/src/oa/openaddresses-me/sources
out=/tmp/oa
sources='us-ca-*.json'
# Only try to process sources with a conform
sources=$(cd "$srcdir"; grep -l 'conform' $sources)
sources=$(echo "$sources" | sed s/\.json$//g)
mkdir -p "$out"
# Echo a bunch of commands to run; these could be piped in to shell to run sequentially
#for s in $sources; do
# echo openaddr-process-one -v -l "$out/$s.log" "$srcdir/$s.json" "$out"
#done
start=`date +%s`
parallel -u --jobs 8 openaddr-process-one -v -l "$out/{}.log" "$srcdir/{}.json" "$out" ::: $sources 2> /dev/null
end=`date +%s`
echo `echo $sources | wc -w` jobs run in $[end-start] seconds
Using this while yak-shaving, improving my Python logging formatting by truncating the log level name from a string like WARNING to a single character W
%(levelname).1s %(module)s:%(lineno)-4d %(message)s
W process_one:40 Nothing processed
I process_one:103 Wrote to state: /tmp/testOA-tJZweo/us-ca-oakland/index.json
In my previous post I jumped through some hoops to do a “git fetch; git rebase” instead of a “git pull” so that I ended up without a merge commit in my timeline. (See explanation here). Those two commands are very manual, what else can we do?
One simple option is to do git pull --rebase, which rebases instead of merges. However that can apparently cause problems depending on what’s in your local repo. I have no idea what rebase does if there would be a merge conflict.
The git up user-contributed command is another solution. I think at its heart it’s a wrapper for fetch + rebase, but it has some other smarts in it. No idea if it can cause problems.
This StackExchange answer has a much more thorough investigation. He recommends doing a git update followed by git merge --ff-only. I guess fast forwards are “safe”; using this flag prevents git from automatically creating a merge commit if it can’t fast forward. There’s a lot more detail there, worth a close read.
I’m going to follow the StackExchange recommendation of setting git config --global pull.ff only and see where that gets me. I think it’s entirely safe; if I do a pull the worst that will happen is I’m on my own to do a manual merge. I may still keep using that git up Ruby command, too.
And now my rant. Fuck git. It’s insane to me that you have to do this kind of contortion. The default obvious tool should be the right one. I hate the neckbeardy attitude you read in most git discussions where the Superior Nerd gets to say “actually, it’s complicated because it needs to be blah blah”. That’s crap; it’s complicated because git has a bad UI and a bit too many exposed sharp corners for civilian use. (I particularly like the StackExchange guy’s observation “Note that the purpose of Git is to make it easy to share and consume the evolution of a codebase, not to precisely record history exactly as it unfolded.”) Git is amazing in many ways and has enabled a lot of things, but I sure wish a more humane alternative were the popular one.
After my whining about pull requests Mike gave me commit access to the repo. Here’s some quick notes on some simple git stuff he helped me do. The setup is we both started working in on separate projects. He made a private branch, made a bunch of changes, then pushed them to the ditch-node branch. Meanwhile I had made my own pyconform branch off of ditch-node before his changes and wanted to bring mine in with his. We could have just merged, but Mike asked me to rebase so that my changes came after his to keep the history tidy. That was easy because there were no conflicts. Here’s how it went.
# Push my pyconform branch up to GitHub
506 git push -u origin pyconform
# Fetch Mike's changes in ditch-node
507 git fetch origin ditch-node
# In my pyconform banch, rebase with the changes in ditch-node.
# This happened automatically without extra work on my part, no conflicts
# No commit necessary.
510 git rebase origin/ditch-node
# Try to push my newly altered pyconform branch to GitHub
513 git push
# That didn't work because we've altered history and Git is confused.
# So now we have to force the push to rewrite GitHub's version of things
514 git push -f origin pyconform
# At this point my pyconform branch is done and looks as if I'd forked it off
# of Mike's changed, even though really we were working in parallel. Now it's
# time to merge my changes back to ditch-node and get rid of the pyconform branch
# Switch to ditch-node
515 git checkout ditch-node
# Pull in the changes that are on GitHub
516 git pull
# Merge from my pyconform branch
517 git merge pyconform
# Push the merged commits back up to GitHub
519 git push
# Delete my branch locally
520 git branch -d pyconform
# Delete the branch on GitHub.
521 git push origin pyconform
# Ooops, that didn't work, so do this magic to remotely delete the branch
522 git push origin :pyconform
I regret not being more comfortable with this kind of git usage. I am sort of OK with git by myself but it’s a lot more complicated when collaborating.
I’m working on portingopenaddresses-conform from NodeJS to Python. First time I really sat down and read the code from start to finish. It’s remarkably clean and easy to follow, once you read past all the async-back-bending.
The basic flow of the tool is to take arbitrary source files, convert them to CSV files in a schema similar to the source, then convert that source CSV schema to the out.csv schema of OpenAddresses, the one with LON,LAT,NUMBER,STREET. It works by creating a lot of files on disk to hold intermediate results of transformations.
Drop columns: prepare a new CSV file with just the core LON,LAT,NUMBER,STREET fields picked out of the processed source CSV.
Reproject to EPSG:4326. Only for CSV and GeoJSON files, creates a VRT file pointing at the processed source CSV and uses ogr2ogr to convert it to WGS 84.
Expand abbreviations: Fix Capitalization & drop null rows. This code is a bit woolly; it has a comment “I haven’t touched it because it’s magic” and there are no tests.
convert.js has five separate functions for converting different source types to a CSV file in the source schema.
shp2csv(): uses OGR2OGR to convert a shapefile to a CSV file. Also reprojects to EPSG:4326. Quite simple code.
polyshp2csv(): very similar to shp2csv(), but handles polygons.
json2csv(): uses geojson-stream to convert a GeoJSON file to a CSV file. Figure out headers from the first object’s properties. Converts polygons to points with a very simple average.
csv(): uses Node CSV modules to read the source CSV file and transform it into a cleaner CSV for further processing. Implements source.conform.headers and source.conform.skiplines.
xml(): uses ogr2ogr to convert an XML input to CSV, with reprojection. Very simple code, may not be used yet?
openaddresses-conform has a small test suite. I believe it works on full source files, it’s more like functional tests than unit tests, running big chunks like conform or download and verifying the output is reasonable.
Existing Python port
Machine has its own Python code for doing the equivalent of downloadCache() and updateCache(). It’s quite different from the Node code strategy and is extra complicated because of the way Machine was a wrapper for invoking the Node code.
Very little of the extract and transform logic of conformCache() has been ported to Python but @iandees did some back in November. That code lives mostly in conform.py:ConvertToCsvTask. It works differently from the Node code. It basically takes whatever input file has been downloaded and uses Python OGR bindings to convert it to a CSV file in the schema of the source, plus an extra computed centroid. There’s no code yet to extract attributes or merge columns or anything. It’s streaming code, never loads the whole thing in to RAM.
I’m considering this choice to lean so heavily on OGR to process source files, it’s different from how the Node code is designed. I asked Ian and he said at the time all sources could be processed with ogr2ogr, so no need to write extra code for source CSV parsing, etc.
Check the type is .shp, .json, .csv, or .kml
Open source with OGR and figure out what field names are in it.
Set up OGR to transform the source SRS to EPSG:4326
Create a CSV file using csv.DictWriter with headers from the field name.
Iterate over features in the open OGR
For each feature, write a row to a CSV file with columns set to all fields from the feature. Also compute a centroid column.
I’ve never used the Python OGR bindings before. It’s pretty un-Pythonic and now I understand why Fiona exists. This list of Python Gotchas in GDAL will be a useful reference going forward. Apparently all the calls to Destroy() are unnecessary, but you do need to take care to manually dereference data sources.
New version of an old rant. The GitHub pull request model makes sense if you plan to submit one giant PR a week. It’s terrible for rapid collaboration. Today I wanted to submit a 5 line patch to openaddresses/machine, in the branch ditch-node. I already have a fork NelsonMinar/machine. I had to:
Switch to master branch in my clone of NelsonMinar/machine
In my clone, manually set up an upstream remote for master
Pull changes from upstream merge them with a fast forard.
Push the merge result back to GitHub
Repeat steps 1-4 manually for the ditch-node branch. I guess you’re expected to do this manually for every branch you care about.
Create a new branch in my clone. I branched off the ditch-node branch
Make my changes and commit them.
Push my new branch back to GitHub with “--set-upstream origin”
Fix the pull request so it’s a diff against ditch-node, not master. Note the branch I’m creating the PR in was branched off of ditch-node; no idea why GitHub didn’t respect that.
Submit the pull request. Never ever touch that branch again until it’s accepted.
As a bonus, the project maintainer warns me he has to rebase my pull request so it’s going to break my fork until I update.
It’s too much work on GitHub to follow along some repo and make occasional friendly improvements to it. I could use some simplified workflow which is just “keep my forked repo updated at all times with upstream unless it would clobber some work I did”. I imagine I could write a script to do that.
Maybe GitHub expects frequent committers to have write access and not go through pull requests. I like the review and auditing of pull requests, though.
Update: John Firebaugh recommends git-up and git hub to help make this better.
Ubuntu has a bug with pyvenv in Python 3.4. I think this is still relevant, despite being 8 months old and a fix having been prepared but not released to Ubuntu 14.04. Not sure.
I’m trying to help with the OpenAddress project, particularly Mike Migurski’s “machine” code for running a full analysis of the data. Particularly particularly the ditch-node branch. Managed to get the tests running after some version hassle.
Now I’m taking inventory of what all code is in the repo to understand where to work. These notes are probably only useful right about now (December 2014) and only for the ditch-node branch.
openaddr/*.py
This is the big thing, about 1700 lines of Python code. The architecture is a bit confusing. I don’t really understand how it’s managing threads / processes for parallelism. Also the actual ETL code is a bit convolved with the download and cache code, including S3.
__init.py__: grab bag of top level stuff. Key methods:
cache() and conform() are wrappers around Python code to download and process data from sources. This code wraps Python modules and uses multiprocessing.Process to run them as separate jobs. (see also jobs.py) The comments say these are Node wrappers, but they no longer are in this branch.
excerpt() pulls bits of data out of source files for user presentation. Contains some logic for parsing CSV, Shapefiles, etc to get a few rows out of them. See also sample.py. Excerpt does not use Process.
cache.py: Download from HTTP, FTP, and ESRI sources. I believe this code entirely writes to local disk and does not use S3. The ESRI code has logic about doing database-like queries on URLs and rewriting the ESRI proprietary JSON to GeoJSON
conform.py: python code to translate source data to the OpenAddress CSV output schema. Uses the OGR Python bindings, etc. I believe this is not complete.
jobs.py: script code to run a bunch of cache jobs, conform jobs, etc as separate threads. I’m not clear how this multithreading interacts with the multiprocessing code in __init.py__
process.py: a main program. this invokes all the work described in jobs.py, then does some processing to extract report-like information (like the map). This is doing I/O via S3 and caches, not so much local disk.
render.py: Cairo and geo code to draw the map of data sources
run.py: a wrapper for running stuff on EC2
sample.py: extract some sample features from a GeoJSON file, used for excerpts?
summarize.py: produce a report about the job run using an HTML template.
template/state.html: the actual HTML file that is visible at http://data.openaddresses.io/. Or rather a Jinja2 template.
template/user-data.sh; not sure what this is. It seems to be a templatized “run” script that installs everything from scratch on a new machine. I imagine this is what Mike runs first on a fresh EC2 instance.
geodata/*: shape files. I think this is used by render.py to draw pictures of FIPS codes.
openaddr-*
Not part of the Machine repo, these are four small Node projects that contain code for managing OpenAddresses data. This is the code that’s being “ditched” in the branch, and in fact I think it’s no longer used outside the tests.
openaddr-source: this is the openaddresses project itself. The main thing is sources/*.json, a bunch of JSON files that describe data sources and their conforms.
openaddr-download: code that takes a source URL as input and downloads it. lib/connectors.js has the actual code to do FTP and HTTP requests. Also is able to get data out of ESRI services using esri-dump, another program by Ian Dees that has both Python and Node versions.
openaddr-cache: another downloading program, this one is focussed on caching source data in S3.
openaddr-conform: the big program, glues together all the other scripts into a single thing that takes a source JSON as input, emits a processed CSV as output. So it has a little download and cache logic in it as well as a bunch of ETL code for extracting data out of source files and emitting it in the simple CSV schema OpenAddresses publishes. it in turn relies on ogr2ogr and other tools for extraction.
test.py, tests/
Test suite for The Machine. All the code is currently in test.py, just 11 tests. tests/ is test data files.
chef/
Scripts to set up an Ubuntu server to run The Machine. I haven’t actually run these on my dev box, just copied out bits of it as necessary. Some of the things it does:
run.sh: install Ruby and chef, the invoke chef-solo
role-ubuntu.json: spec for The Machine. Installs Python, Node, and four openaddr-* Node modules.
**/default.rb: specs for each package. There aren’t many interesting bits here. Node is wired to version 0.10.33. Python installs Cairo, GDAL, and PIP. The openaddr-* modules get installed in /var/opt. Only openaddr-conform is now needed for the tests to run in ditch-node, although I’m not sure about the full machine loop.
Running pip on my Ubuntu 14.04 box gives the error “ImportError: cannot import name IncompleteRead” when trying to import the requests module. Turns out this is a known bug going back to at least April. It’s subtle though; a different Ubuntu box with the same versions of python-pip and python-requests is fine. It’s apparently a bug in python-requests, see also Migurski’s workaround.
A quick workaround is to remove Ubuntu’s python-pip and install pip manually.
I’m running into a baffling problem where the straightforward way to use prepared statements in the MapBox sqlite3 Node.js code is super slow. Like inserting 100 rows in a table takes 16 seconds!
Update: found the problem, I wasn’t using transactions right. See bottom. Simple solution for faster bulk inserts in sqlite3: do them with a transaction.
The API docs have a strange note for Statement.finalize() which says “if you experience long delays before the next query is executed, explicitly finalizing your statement might be necessary”. I’m seeing exactly that. But after you’ve finalized it you can’t reuse the prepared statement; what’s the point of using statements at all then?
There’s notes online that naive bulk inserts in sqlite3 are slow, nothing to do with Node. See StackOverflow and Blog::Quibb. The quick fix I learned from both of those is to wrap the insert block in a transaction, because without that sqlite3 treats each insert as a separate transaction and is understandably slow. OK, so we’ll use a transaction.
But even with transactions using prepared statements is still slow in the Node version. I don’t know if this is a bug, me not understanding sqlite3 right, or me not understanding Node right. I am using serialized mode and trying to do simple nonconcurrent programming. The delay only occurs when the database is closed, btw, sqlite3 is accumulating the changes in a journal before committing them.
Three approaches:
Call db.run(‘INSERT...’) a bunch of times. This is fast, but only if I wrap the inserts in a transaction.
Prepare a statement once, then call stmt.run(‘INSERT...’) a bunch of times. This is slow whether I use a transaction or not.
Prepare a separate statement for each row, then call stmt.run(‘INSERT...’) on it and then stmt.finalize(). This is fast.
Sample code is in this gist. “db” and “finalize” both take about 400ms on my Linux box. “reuse” takes 16 seconds to insert the 100 rows.
Update:the problem was I was creating the prepared statement before I did the “begin transaction”. Apparently that means the prepared statement is executed without the transaction context. Beginning the transaction and then preparing the statement, the three methods all run fast. I suspect the call to finalize has nothing to do with it, but I’m not sure.
Here’s the revision view: version one had the begin transaction too late.
This post is an exercise in trying to learn how to debug errors in Node.js programs.
Trying to write some sqlite3 code in Node.js. MapBox has a lovely Node module, but the docs are a bit thin and assume Node expertise I do not yet have. This morning’s challenge is trying to gracefully handle an error if database.run(“DROP TABLE”) fails. All work is running after database.serialize, so no concurrency.
By default with no error handling code, an error will cause an Unhandled ‘error’ event that kills the process. But you can’t just catch an exception because this is Node.js and exceptions don’t really work. So instead you need to specify a callback to database.run(), to get the Error (or else inspect the results of a successful statement.) Fair enough.
But what is the Error object in the callback? The sqlite3 docs don’t document this anywhere. In Chrome I’d just console.log() the object and use the lovely inspector. Node’s equivalent to the inspector is util.inspect, and you want to set showHidden to 1 to really see it. And voila:
{ [Error: SQLITE_ERROR: no such table: logs]
[stack]: [Getter/Setter],
[arguments]: undefined,
[type]: undefined,
[message]: 'SQLITE_ERROR: no such table: logs',
errno: 1,
code: 'SQLITE_ERROR' }
So this object looks like an ordinary Error object, with the message property. In addition it has errno and code properties. And now I know.
Another way to have learned all this would be to use the Node debugger. It’s pretty primitive, but you can set breakpoints in your code with the “debugger;” statement or from the debugger command line with “sb(lineno)”. Once it breaks you want to run “repl” to switch to the scope of your running script, then you can inspect objects. It all works but is a bit awkward without a GUI. I miss Chrome’s beautiful debugger; should try out node-inspector or something similar.
The irony of all this is I don’t even need too handle this error; sqlite supports “DROP TABLE IF EXISTS”. But oh well, now I know more about sqlite3 error handling and how to debug Node programs.
I’m a big fan of open source and have been for at least 24 years. Today is the first time I ever un-open-sourced something. Logs of Lag, my League of Legends analysis tool.
It wasn’t a good candidate for open source. It’s a free web service I run, not software people install locally. And I don’t expect any useful contributions from drive-by programmers. Also I’m a little worried someone could take all my code and legally clone the site entirely, maybe in Chinese or Korean. That’d make me sad; I’d rather be the one running that service. Why give away my work without any expectation of getting something in return?
I did get a little help once, another LoL developer named Masch helped me figure out a scroll overflow problem. Then again he could have done that just viewing the page source. I’m happy sharing how the thing works with people if they can learn from it, but don’t see any need to give a blanket license to use all the code to set up a competing service.
There’s some reusable / shareable library code in the middle of my thing, the actual netlog parser, I’d be glad to make that open source if anyone asks.
My little Logs of Lag project is doing pretty well, I need to create some sort of more serious datastore for it. It’s a small service, at most 1000 logfiles uploaded a day (each about 20k per file), but over time that adds up. Right now my data store is “put a file with a random name in a directory”. And I have no database or analysis of all the files.
The high-end solution would be to start putting data files in AWS and create a local Postgres database for aggregate statistics. I know how to build this. But that adds two big moving parts, one of which I have to maintain myself. And it’s kind of overkill for the relatively small amount of traffic I have (and am likely to ever have).
So I’m thinking now just to keep storing the files themselves on the filesystem, but spread it out over a bunch of directories so I don’t have a single giant directory. The Linux kernel no longer chokes on lots of files but shell tools are still a PITA. File names are base 64 encoded things so maybe hash by the first two characters, for 4096 directories. That’ll carry me to about 16M log files (4096 files per directory), good enough. The file system only has 60M inodes available anyway. (Unfortunately - is a valid leading character in the filenames. Oops.)
I definitely want a database, I’m curious about aggregate stats. I’m thinking of keeping this all asynchronous. When a user uploads a log it doesn’t go straight to the database, just written to a file. Then a cron job picks up the files and does the postprocessing. That works fine as long as the database data still isn’t needed by the user application. It’s not right now, in fact the server isn’t needed at all, the user gets 95% of the value solely in client side javascript.
What database? I should probably bite the bullet and just use Postgres, but I hate having to manage daemons. I wonder if SQLite is sufficient? It supports concurrent read access but only one writer at a time, and the writer blocks readers “for a few milliseconds”. I think that constraint isn’t a problem for me. Right now I’m tempted to go for that, just for the fun of doing something new.
Another problem to solve is the log parsing code. Right now logs are parsed by the client browser, in Javascript, and the client sends both the raw log text file and the parsed data (as JSON) to my server. (The server is a Python CGI which just writes the files to disk.) I’d like to retain that client-only capability, but also start parsing logs on my server. I don’t really want to maintain a second parser in Python.
So maybe I write the server parser / database stuff in Node to reuse the Javascript parser. Here’s MapBox’s node-sqlite. There’s zero need for me to make these scripts asynchronous, so the Node paradigm is not a great match, but I can certainly make it work.
(Naively I’d thought Node startup times would be bad, like Java, but that’s not true. From Node v0.10 on Ubuntu: “NODE_PATH=/tmp time node -e 1” is about 27ms, compare Python 15ms. Not enough difference to matter. strace shows Node makes about 230 system calls for an empty script (it’s nondeterministic!), compare Python’s 883.
I’m working on a data exploration tool. Sort of a simplified version of GGobi, for web usage. Give it a CSV file and it lets you explore scatterplots of various columns. I did a custom version for Battlefield 4 a few months ago, now working on a generic tool.
So here’s “first light”, taking the HYG Database of stars and trying to recreate the Main Sequence diagram. It’s visibly at least a little right, once you realize the Y axis (magnitude) is inverted.
Pie charts are bad; they’re hard to read, particularly for small percentages. This Pornhub Insights report (SFW) has an interesting alternate type of pie chart.
The angle of each wedge is constant, 360°/5 = 72° in this graph. It’s the radius of each wedge that conveys the data. In other words it’s basically a bar chart, but turned into a circle. That’s a nice compact layout. And it visually conveys that the numbers sum to 100%. If I measure this right the wedge radius is proportional to the square root of the value, so that the wedge area is proportional to the value. That’s more correct for visual perception. It also works well for showing a 40:1 ratio like the data above; in a linear bar chart the 1% data would only be a couple of pixels high.
I’m sure Pornhub didn’t invent this, but it’s a neat technique I haven’t picked up on before.
Update: Mike B tells me this is called a Polar Bar Chart. Or a Coxcomb chart, after no less than Florence Nightengale.
It took me three hours, but I added a mouseover tooltip to my LoL netlog graphs. It turns out there’s three ways to do this.
Use svg:title or svg:text and rely on the default browser hover action to show it. Totally ghetto, but it does work.
Catch mouseover events on your actual chart elements. If you bound your data sensibly, the event handler gets the datum that was bound to the element that got the event passed right to it. This works great for bar charts as long as you don’t mind the popups only showing up on the bars, not the whitespace. Not so good for line charts or other things.
Add an overlay to the entire chart area you want to capture events in. Unfortunately no useful data is bound if you do this. So you have to use d3.mouse() to get the relative X,Y in pixels of the mouse position, then shove that through scale.invert() to map that back to data space. Here’s a demo of that technique. It’s a lot more work, but now you have mouse events for the whole chart area, not just the marks.
I went for option #3 and really it looks pretty great. The other tricky part is I was reading the timestamp from the X axis of my time series chart, but then finding the specific row of timeseries data that corresponds to that timestamp is not so easy. I ended up doing a linear search in my data array; not awesome, but will work OK for me.
The other half of the problem is displaying the tooltips. I ended up going with a div element with visiblity toggled by mouseenter/mouseleave. The tooltip is positioned absolutely with CSS, and the mousemove handler positions the tooltip relative to the event pageX and pageY. Important to make sure the tooltip div doesn’t grab the mouse events. I did that with positioning, but probably better to use the pointer-events CSS option.
So much code is worried about using “safe” delimiters, and quoting, and the like. I’m probably getting myself in trouble, but I just used a very old school ASCII delimiters in my code.
In particular I’m using ASCII 28 (File Separator), aka U+001c (Information Separator Four). This is one of the ASCII control codes for separators that’s mostly a forgotten thing. I’ve often wondered why we have CSV and TSV files instead of files delimited by ASCII 30 (Record Separator), too. That character is way, way less likely to occur in source input than a comma or a tab.
I hope I’m not getting myself into trouble somehow. My use case is the LoL netlog files, in particular I want to concatenate a JSON blob and the raw text logfile together to POST to a web server. The source data is very, very unlikely to contain any non-printable characters, including U+001c. If it does I’m screwed.
Javascript code to emit this
var uploadText = [JSON.stringify(parsedLog),
'\n\u001c',
rawLog.substring(0, 1000000)].join('');
Having done a bit of work deploying a Node server I may not use it afterall. Things I don’t like:
Lack of standard production scripts
Lack of blanket error handling for servers; exceptions kill servers
Difficulty preventing memory leaks in servers. Closures capture memory in complex ways and V8 isn’t always able to GC it.
These are all solvable problems, but I’m not sure I want or need to solve them for my very simple server. The main advantage I get from Node is that I can share some Javascript parsing code between the browser and the server. But I’m not sure I really need that.
Truthfully I don’t need much if any custom server code at all. Just a bucket to post data to and be able to retrieve it again. I wonder if I can do that entirely with client-side Javascript and some basic S3 API.
My Node server sort of works and I’m ready to put it into production. I need some sort of start script. What to do? Naturally, the Node world has to reinvent everything and there’s no standard way to do this. But most docs talk about using Upstart (the Ubuntu variant of init scripts), plus monit or forever to keep the Node process running when it inevitably crashes. (Because of course, this is new tech, it’s gonna crash!).
Also some scary notes about catching exceptions globally so your server doesn’t fail simply because of a bug in one user request, but I think Express takes care of that me. Update haha joke’s on me, by default the whole server crashes if you have an unhandled error because “By the very nature of how throw works in JavaScript, there is almost never any way to safely pick up where you left off, without leaking references, or creating some other sort of undefined brittle state.” Apparenly Node domains are the way to deal with this, some notes here.
I ended up just using a trash shell script for /etc/rc.local because it’s too much bother to do it right. I wish that here in 2014 we finally had a basic simple standard way to deploy and run server scripts in production. So many solutions that are either too ad hoc (upstart) or too complex (Puppet and friends)
I rewrote this Python CGI server in to a Node.js server, or most of one. The main thing it does is accept POST content, writing it to a file and returning a generated filename. (Yes, that’s really a PUT. I know.) The Python CGI is 39 lines, the Node.js is 52 with 12 lines of NPM configuration. But then the Node version is a full server and has fancier message handling. Things I learned:
The Node community and docs are good but nowhere near as mature as Python. Also the Node philosophy is one small stable core, then you download add-on modules. Batteries not included. The core Node API is well documented. Beyond that you’re hunting through npmjs or maybe node.js modules for more.
NPM isn’t so scary. Grab a template, put your dependencies in a packages.json, run “npm install” and it will build a node_modules directory for you with all the dependencies. It’s good that’s a default tool deep in the Node chain. More info on npm.
express is a reasonable webapp framework and has a nice tutorial guide. I like the router style of specifying handlers.
node by default doesn’t do anything with POST body content, you have to install middleware to handle the input bytes. senchalabs / connect seems to be the default choice for doing fancy things like parsing JSON, etc. I just want the plain message text so the raw-body middleware middle is for me. It’s an awful lot of boilerplate to set up.
I’m gonna need a content hash; here’s a pure Javascript implementation of Murmur 128 that’s in npm as “murmurhash3js”. Hard to come by; it’s tricky doing true bit twiddling in Javascript without proper bit types. NPM turns up 10 different Murmur implentations, many of which either require native code or only implement the 32 bit hash.
I’m trying to do an Ajax thing where I’m swapping views of a page based on user clicks and dropping files and stuff, but without any page navigation. A single HTML page webapp. I’ve got it sort of working just using old school manipulation of location.hash, but the back button doesn’t work.
To get the back button working, you need to listen to “popstate” events on the window. One of those fires when the user clicks back or presumably navigates their history in other ways. I’m guessing this event only exists if the browser supports pushState() and popState() functions. Ie: everything but IE 9 and older. But I’m not sure.
Apparently window.history is inconsistent across browsers. History.js is a compatibility library to try to bridge the gap. I’m trying to avoid those, but it may end up being useful.
I’ve got the tools to code up state now, but I’m still tripped up by what my application logic needs to be. Need to sit down and sketch out the control flow. Life sure was easier when the server did all this work :-)
OK I’m writing tests in Mocha now! Yay! But what a lot of boilerplate. I want to test a javascript file that works great in a browser. It’s named “lol-netlog-parse.js” and contains a single top level function named parseLolNetlog. Let’s just do a fake test for now.
require('chai').should();
var parse = require("../webapp/lol-netlog-parse")
describe('lol-netlog-parse', function() {
describe('parseLolNetlog', function() {
it('Should throw an error', function() {
"foo".should.equal("bar");
});
})});
This actually works. But only if I wrap my browser code in some require.js boilerplate to set exports. But then the exports object doesn’t exist in browsers, so I have to do extra work to provide a stub exports object in the browser so that it will still run.
It’s also 7 lines of code for a 1 line test. All test frameworks have their boilerplate, and I understand why this all helps with more complex text harnesses. Still sometimes I think Python doctest had the write idea.. The relative path in the require is a pretty ugly wart too, maybe if I knew more about Node and include paths I wouldn’t have to do that.
I’ve written this in the BDD style, where the function “suite” is named “describe” in some vague attempt at literate programming. I did this because it’s the default style Mocha wants and I don’t want to have to add the “-u” command line flag to use the TDD style. It’s very clever that the code supports 4+ different ways to write unit tests but that’s 3+ more than is necessary. One way to do things; it’s a virtue.
I’m fully embracing the BDD style and using chai’s scary Object prototype manipulation to see if I like it.
I want to write some Javascript unit tests. I’d hoped Node.js would be mature enough there was one clear answer from that community, but there’s not. This article was useful but two years old. Here’s some options:
I’ll probably use Mocha unless it seems too hard to do simple things. It seems particularly crazy that there’s not even a consensus assert module. “There’s more than one way to do things” is usually not a virtue.
Just cooked up this demo HTML file showing how to build a web page that does something to the contents of a file that’s dropped on to it. There’s lots of approaches and tutorials for how to do this, this one is mine.
The challenge is that most of the docs I found dated back to 2010 when drag-and-drop was a bold new idea and was fraught with peril. Now it’s pretty simple and just writing the obvious code works in Chrome, Firefox, and Safari. (I hear there’s another browser but I’m unable to run it, so who cares?)
The most useful document I found while figuring this out was this MDN article. The key concept is that there’s a “drop” event in the DOM. By default that causes the browser to navigate; you override that to provide your own behavior. The FileReader API is also useful, beware that it does not work in IE 9. If I cared I’d probably stop writing my own raw code and use some jQuery plugin or other library to provide compatibility.
Can’t believe I’m doing something this mundane, but here’s a template for a new HTML 5 web document with spots already set up for CSS and Javascript in the body. Way back in 1994 I wrote an emacs mode with one major feature being starting you with a template HTML document. And here I am 20 years later still doing it. At least the doctype string got simpler.
Since the Heartbleed bug, I’ve been pondering what language a library OpenSSL should be written in. C is a disaster and C++ is no better. But a component like OpenSSL needs to be buildable into a linkable library, into a .so or .a file that other projects like Apache, Python, etc can then incorporate. And most modern programming languages really don’t work well with the C linker. Javascript, Python, Ruby, Lua, Java, Go ... none of these are suitable langauges for building reusable object code libraries because they either have massive runtime libraries or else toolchains that don’t work with the linker.
Enter Haskell. My friend K.K. recommended looking at it because it’s a modern safe language and is good at linking libraries. I’m not actually going to learn Haskell now, but I did want to collect some of the links and notes he shared with me.
I’m very, very skeptical of bringing new languages into practical software engineering. But the community desperately needs a C replacement, something with safe memory access. Rust is a new effort for this but there’s a lot of work to do. D seems to stand for dead-end.
I love D3.js, it’s amazing. But one thing that bugs me is the style it encourages is to write new chart types inline in Javascript. There’s not much in the way for reusable charts, D3’s focus is on making it easier to build your own charts in Javascript. So I find myself painfully rewriting basic histograms and time series and the like. In some sense this is by design; Mike’s style is to parsimonious Javascript and making it easy to actually build charts by hand. And it’s good in that it encourages a diversity of visualizations. But sometimes you just want a simple timeseries, you know?
Of course nothing prevents people from building a chart component suite on top of D3. And lots of people have. Here’s a very quick review of looking at the project web sites for a bunch of efforts. I’m only looking at their ability to produce static visualizations. An API supporting interactions and transitions is significantly more subtle to get right.
The libraries group into two categories. Declarative libraries let you specify a chart simply with a bunch of configuration parameters, no real executable Javascript code. In general, my guess is these are great for doing simple things and hard to customize to go beyond what the library was designed to do. Programmable libraries are more like toolkits on top of D3 that still require some real programming to get results. But then they may give you more access to do complex customizations and interactions.
Ember Charts by Addepar has some basic chart types. It’s tied to the Ember.js framework and needs Node to develop, also not a lot of activity on GitHub, so I didn’t investigate further.
Tenxer xCharts is declarative but with some programmatic customization. Examples feature using closures inside the chart definitions. Also has notes on customization and extension. Drawbacks are relatively few chart types and that there’s been no code development in eight months.
Programmable libraries
Towards Reusable Charts: Mike’s own opinion on reusability in D3. Advocates encapsulating a chart type in a closure. Doesn’t go much beyond establishing a design pattern. Some of the D3 plugins like Sankey and Horizon are good examples.
NVD3 is a reusable component library that works hard to respect access to underlying D3 design. It’s been around for awhile and seems pretty mature, not many commits in the past few months. The Discrete Bar example is appealingly simple.
Dimple adds chart types on top of D3 that you configure with simple declarative code. But then the advanced examples show you dropping in to the underlying D3 to extend the charts beyond what Dimple provides, which is great.
Bocoup d3.chart is a framework for creating charts, not a chart library itself. Its design is informed by a very thoughtful critique on reusable chart approaches. But it’s pretty early days and it’s aimed more at people writing chart libraries than folks just wanting to draw some charts. Also, I’m bummed the examples aren’t rendering right in JSFiddle. Overall my impression is these guys are pushing on solving the problem I want solved right now.
Summary
I’d use Vega or maybe Rickshaw if I just want some simple graphs. Dimple looks to be the most promising programmable system worth a closer look. I’m stubborn and foolish and like shaving yaks so I’m going to write my own little histogram thing using Mike’s suggested pattern just for the experience. Maybe I’ll end up using Dimple for future projects.
dc.js is an interesting option. It takes too much programming to really just be reusable chart templates, but it has a nice way of packaging in crossfilter and aiding making basic data charts instead of arbitrary D3 SVG marks.
Chosen is neat; it’s a Javascript library that replaces the usual browser form select dropdown with a much more capable version. Check the demo. The only drawback is it requires jQuery or Prototype.
But not anymore! There’s a version that works natively; here’s a pull request for it based on this fork. I’ve built it and it seems to work. 30k JS + 10k CSS after minification. The jQuery version is only 26k JS, but then you also need 80k of jQuery to run it. So big win.
I had a heck of a time building this. Not because it’s complicated, it’s just a few files. But “native” in this case actually means “Coffeescript and Sass with a Grunt build and btw that implies a Ruby dependency”. Bah, kids these days. Here’s a copy of my build, the “public” directory, which contains the minified Javascript, CSS, and a demo that seems to work. I might have built this wrong so better to get it from official sources.
I’ve complained a bunch about how MacOS doesn’t let you compile static binaries; you absolutely must dynamically link libc.
go doesn’t have that problem. go doesn’t use libc. The binaries “go build” creates appear to be truly statically linked, at least according to “otool -L”. Although apparently there’s another compiler “gccgo” that does link with glibc, or else I misunderstand.
Bonus fact: if you strip a Mac go binary, it segfaults when you run it.
D3 has two main ways to load data; JSON files or CSV files. JSON is generally better but bloated for long repeated rows of data, for which CSV is better because it only prints the key names once. But CSV has a drawback which is that it’s untyped. So D3 just lamely loads everything as strings. Most of the time Javascript’s automatic string to float conversion lets you ignore that but it fails in some places, like sorting with d3.ascending.
Fortunately D3’s CSV library lets you create an accessor function which manipulates the data as you load it. Here’s a function which will load every row and try to convert things to numbers. I wrote it in very verbose Javascript to make it clear what’s going on. I don’t care about the number of lines, but I do wonder if this is less efficient than possible.
// convert strings to numbers in CSV
function convertNumbers(row) {
var r = {};
for (var k in row) {
r[k] = +row[k];
if (isNaN(r[k])) {
r[k] = row[k];
}
}
return r;
}
d3.csv("data.csv", convertNumbers, function(error, inputData) {
// do work on the data here
}
Note that the accessor function has to create a new object; you can’t just return the one the accessor passes you.
I’m exploring a multivariate data set. Battlefield 4 data, to be exact, I have a dataset for thousands of players with such statistics as “time played”, “kill/death ratio”, “win/loss ratio”, etc. Fun stuff. Now I’m exploring it looking for intresting patterns, clusters, etc. And doing it by hand-writing Javascript code with D3.
I wish there were a solid consensus tool for exploring datasets and showing graphics. Excel and R seem to be the two most popular. But Excel is too primitive and R is too much like programming already.
Doing yet another HTML scraping project, contemplating the slowness and desolation that is BeautifulSoup or spend hours learning scrapy or surely there’s something better by now?
There is, my web browser, with DOM CSS queries. Just load the page and do querySelector and you’re done. Most modern HTML is quite nicely scrapable in browser Javascript. The problem is you can’t effectively script a browser to process thousands of pages. I’d hoped node.js would offer a solution but they don’t have some battle-hardened HTML parser like a browser has. There are some options, wonder if any are worth the time to learn about.
Working along on my Chrome extension, generally impressed with how well thought out and thoroughly documented the extension support is. That being said, some wrinkles...
There’s no support for reloading extension code when it’s changed during development. There’s some hacks, I’m using Extensions Reloader which gives me a button to press to reload the Javascript code. But it won’t reload the manifest, so it’s not a complete solution. And even then I have to hit the extension reload the button then refresh the page to debug stuff, it’s awkward.
Chrome has adopted an awkward API for signaling errors in the extension API, the variable chrome.runtime.lastError is set. This makes checking for errors a huge nuisance, but maybe it’s the only way to do this given the weird lifecycle of extensions? Good thing Javascript is single threaded :-P. It’s a shame Javascript’s built in exceptions are not very useful. I like the D3 pattern of setting an error object on the callback function, at least it makes the error variable a bit more explicit.
The Chrome extension storage API is fairly capable, I particularly like that it lets you store data in a place that Chrome synchronizes between the user’s browsers. But the API is just enough different from DOM localStorage to be a bit obnoxious. Also the get() method is incredibly slow, like 500ms to retrieve my 10 bytes of state. That means I can’t just store stuff there and fetch it from my content script, too slow for something whose purpose is to modify a page’s presentation. So I have to create a background page and move the config fetching there, an unwelcome complication. Update: it’s not always so slow. Sometimes it’s only 40ms. Sometimes its 200ms. I’m running a bunch of other extensions, should test it more cleanly.
I found the perfect way to encourage myself to work on this Chrome extension. Install a version whose UI is so eye-bleedingly awful I can’t help but fix it.
I wrote a Chrome Extension today. Or the start of one. Want to modify the content of some pages on Metafilter in order to try out a UI idea. I started with the diediedead userscript, that runs just fine by itself if you manually load it. But I want a proper Chrome extension so I can make it configurable (and easily usable) so I read up on how to build Chrome extensions. It’s easy, at least for this easy thing I’ve done so far, although there’s a lot more complexity for a more complex extension.
The one hassle is Chrome doesn’t auto-reload extensions under development. It does reload userscripts though, weird. Anyway the Chrome Extensions Reloader Extension helps, at least there’s a single button to press.
A recurring theme for me: I need something like make, but good at managing data. Make is all about compiling files and testing filestamps. I need something that’s about download data, and inserting into databases, and testing whether data needs to be regenerated. It’s possible to coerce make into doing this with lots of touching sentinel files but it’s kind of a mess.
Ugh, I was grooving along with a solution for my vector merging when suddenly a ordinary-working query threw the most bizarre error:
ERROR: could not open file “base/16384/24738_fsm”: Invalid argument
Googling around was useless, but I managed to get some help on IRC from anders and RhodiumToad on #postgres. Long story short, our guess is a call to free() is following a call to open(), and the free() is clobbering errno before Postgres checks on the errno from open(). Good ol’ C error reporting, have to love it :-(
This is the first time I’ve used dtruss in anger. Worked nicely. In my psql repl I did “select pg_backend_pid();” to find the PID, then did “dtruss -p > /tmp/out 2>&1” to capture the output.
Weirdest behavior I’ve seen in a Unix server in the longest time. Here’s what happens when I’m running a GUnicorn server (with Tilestache) and resize the iTerm2 it’s attached to.
I thought this was some sort of sick joke, but it’s for real. GUnicorn interprets SIGWINCH to mean “gracefully stops workers but keep the master running”. Which is absolutely terrible in an interactive environment where I might deliberately resize a window while debugging. Particularly with tabbed terminal windows. UI actions in the controlling terminal = kill server, how intuitive!
I can’t even figure out when I’d actually want the documented behavior. The workers don’t restart; is there some way to manually start them? What’s left in a GUnicorn server after you shut down the workers?
Update: this was fixed in GUnicorn, see issue 500. SIGWINCH now only shuts stuff down if in daemon mode. Which seems reasonably safe. Still seems an odd choice of signal to me, but I see there’s precedent with Nginx and maybe they were running out of signals.
Wow, Python startup time is worse than I thought. Here’s some data from a fast Ubuntu box. I ran all commands a bunch of times to warm caches.
$ time python2.7 -c 1
real 0m0.015s
user 0m0.012s
sys 0m0.000s
$ time python3.2 -c 1
real 0m0.026s
user 0m0.024s
sys 0m0.000s
$ strace python2.7 -c 1 2>&1 | wc -l
856
$ strace python3.2 -c 1 2>&1 | wc -l
1429
$ echo >| /tmp/empty.py
$ time python2.7 -O /tmp/empty.py
real 0m0.042s
user 0m0.032s
sys 0m0.008s
$ time python2.7 -O /tmp/empty.py
real 0m0.044s
user 0m0.032s
sys 0m0.008s
$ time python2.7 -S empty.py
real 0m0.004s
user 0m0.004s
sys 0m0.000s
$ strace python2.7 -S -c 1 2>&1 | wc -l
301
That last one’s a bit of a winner; -S means “don’t load site modules” and comes from this ExpertsExchange discussion. I lose /usr/local/lib; if I manually add that in my script I get my minimal libgit2 program down to 6ms.
Was curious if I really need to use C to write this fast git prompt thing. libgit2 has bindings for many languages, but scripting startup time can really suck. Here’s a quick test of how fast a program can be that does nothing but open the repo (on Linux, local disk).
C: 1ms
Python 2.7: 17ms
Python 2.7 with -S flag: 4ms
Lua 5.1: 2ms
No surprise Python is so slow; even the null program is 14ms or so, a weakness of stock Python. Surprisingly there is no Perl binding listed; that’d be another option for fast startup. There is one for Parrot. Also Go, which could be a suitable modern upgrade for C.
Lua’s a fun little language, I should switch my development efforts there just so I have humane strings. Can always port back to C later.
All this testing is a huge PITA because the last stable release of libgit2 is 11 months old (0.17.0) and since then they’ve changed the API in all sorts of places. My C and Python tests area against the HEAD of the github repo. Lua is against 0.17.0. This lack of stability makes me question whether libgit2 is really the right choice for something as ubiquitous and lowlevel as a shell prompt. They aren’t kidding when they say it’s alpha software, I guess.
Doesn’t help that I was in dynamic linker hell, btw. On Linux it seems to cache things pretty aggressively; I had to manually run “ldconfig” as root to get it to switch from one version of libgit to another. I used to be good at this sort of nonsense but it’s been years since I’ve worked in such primitive environments.
So, quick conclusion: Lua would work for development.
Following on my dorking around with bash prompts yesterday, I was wondering how fast one could write a program to query state from git for the command prompt. The minimal __git_ps1 function I set up there takes about 75ms to run; takes longer if I add more to my prompt. That function works by invoking git a bunch of times, maybe a custom C binary could do better?
I took a quick crack at it using libgit2. It’s been years since I wrote any C code and it was rough going. No exceptions, no useful string type, manually allocated and typed memory, ugh. Maybe I should break down and do C++. Anyway, I managed to scratch together something that prints out the branch name and hash for the current commit. With caches warm my program takes just about 30ms to run; compare 23ms for __git_ps1 if it’s only printing branch name, nothing else. Ouch, I’m slower!
Using set -x I can see what __git_ps1 is doing. The main command its forking is git symbolic-ref HEAD, which takes 10ms if I run it by itself. I wonder why my libgit2 based code is so much slower?
I still feel a custom C binary should be faster, particularly to support fancier output info. But it’s an awful lot of pain writing libgit2 code in C, I may not have the patience to press on.
Update: derp, my program isn’t slow because it’s slow. It’s slow because I was running it on my Mac off of an SMB mounted volume. If I copy my binary to local disk it’s faster than stock git as expected: 6ms vs. 10ms for git symbolic-ref HEAD. Duh.
One other note; I started playing with dtruss/dtrace to figure out what system calls the two programs were running. My code makes 135 system calls, stock git makes 178. My code opens 8 files, 3 of them from the repo (which is still SMB and therefore slow). git opens 14 files, 6 from the repo. It seems to be doing all the work on the repo files twice, not sure why. Anyway now I’m reassured my libgit2 approach could be more efficient.
#include <stdio.h>
#include <stdlib.h>
#include <git2.h>
void check_return(int rc, char * msg) {
if (rc != 0) {
fprintf(stderr, "%s. Code: %d\n", msg, rc);
exit(1);
}
}
int main(int argc, char ** args) {
int rc;
git_repository *repo;
git_reference *head;
// open the repository
rc = git_repository_open_ext(&repo, ".", 0, NULL);
if (rc == GIT_ENOTFOUND) {
// No git repo; that's OK.
exit(0);
}
check_return(rc, "opening repository");
// find HEAD
rc = git_repository_head(&head, repo);
check_return(rc, "finding HEAD");
int ref_type = git_reference_type(head);
if (ref_type == GIT_REF_SYMBOLIC) {
check_return(-999, "Cant handle symbolic targets");
// git_reference_symbolic_target() or git_reference_resolve()??
} else if (ref_type == GIT_REF_OID) {
// Get the name
const char * name = git_reference_name(head);
// Get the hash
const git_oid * oid = git_reference_target(head);
char hash[7];
git_oid_tostr(hash, 7, oid);
// Print out what we've learned
printf("%s %s", name, hash);
}
return 0;
}
I’m trying to learn more about git. I thought it’d help me to modify my bash prompt to include git status. Turns out theres lots of ways to do that. I want something simple and minimal, but maybe using color. For years my prompt has been a simple “(hostname) = “; don’t want to go crazy. (Why =? Because it doesn’t look like $ or # or %, the standard characters. I know it’s mine.) Here’s some options.
Here’s a blog post with some minimal git additions to the prompt. It just invokes git symbolic-ref to figure out the branch name. Simple, easy to understand, there’s a zillion hacks like this. Here’s another.
git-prompt.shis a bash addon distributed with git that adds a shell function __git_ps1 that can be invoked from inside the shell to print state. This is as close as it gets to a “standard”. This blog post does a good job explaining it. The configuration is a mess. The code is quite complex and handles a lot of strange git situations I wouldn’t have realized were important.
bash-git-promptis a different approach that has a bit more info on the state of the repo. As nice as it looks, I’m not going to use something that invokes a Python script every time bash needs to print a prompt.
GIT Promptuses colors to convey repo state, sets the terminal title, etc. It’s a very fancy prompt, but it’s overkill for my purposes. I do like how it displays non-zero exit codes though, and it’s got a nice configuration mode.
I settled on option #2, the “stock” git-prompt.sh. It seems to work pretty well. The biggest problem is that Ubuntu 12.04 has an old version that doesn’t support working via PROMPT_COMMAND, so there’s an ugly workaround. Also gotta love the quoting. Anyway, screenshot and configuration.
GIT_PROMPT_VERSION=`sha1sum /etc/bash_completion.d/git`
if [ "$GIT_PROMPT_VERSION" = 'c52dd44066a21660c8830f8e6bd700893e2f7569 /etc/bash_completion.d/git' ]; then
BAD_GIT_PROMPT=1
fi
if [ -n "$PS1" ]; then
# Figure out what prompt character to use
P='='
if [ $UID == 0 ]; then
P='#'
fi
# Set traditional prompt
PS1="(\h) $P ";
PS2="> "
# Set up git prompting if available
declare -f -F __git_ps1 > /dev/null
if [ $? -a \! $BAD_GIT_PROMPT ]; then
PROMPT_COMMAND='__git_ps1 "(\h" \)\ '$P'\ " %s"'
GIT_PS1_SHOWCOLORHINTS=1
GIT_PS1_SHOWDIRTYSTATE=1
GIT_PS1_SHOWUNTRACKEDFILES=1
fi
fi
I have some concerns about running any commands at all from inside a bash prompt. First it’s notably slow, particularly on a cold cache. Even warm it’s a few hundred milliseconds, and every extra GIT_ status thing I enable makes it slower. Worse, prompt commands do bad things if the command fails. Particularly a problem if you’re inside a remotely mounted filesystem that’s hung. I don’t know if bash is smart enough to timeout commands called when printing the prompt.
Update: this prompt setup is intolerably slow for big repos like libgit2 on a network filesystem mounted via SMB from a Linux server to a mac client. I’m talking 1000-1300ms per prompt, a noticeable pause. With no GIT_PS1 environment variables (just showing branch), the git prompt takes 25ms. Adding GIT_PS1_SHOWDIRTYSTATE adds an extra 100ms. GIT_PS1_SHOWUNTRACKEDFILES is the big culprit, adding an extra 1200ms or so. No surprise, the underlying command git ls-files --others --exclude-standard is making calls to getdirentries64() for every directory, also processing .gitignore files all up and down the tree. Not sure there’s any way to make that fast on a network file system. Maybe that’s why they went through the trouble to let you override the environment variable in the local git config.
Unrelated, but also useful; git-completion.bash which adds smart completion support for the git command. Seems to rely on the bash-completion addon to bash, although the script itself is distributed with git. In Mac Homebrew it’s a separate file; on Ubuntu it’s rolled together with git-prompt.sh. Apparently that’s an upstream change from a year ago.
GitHub is a marvel. But it’s a PITA to submit pull requests. It’s too heavyweight; in particular you’re required to log in to GitHub and make a fork. Here’s what you have to do:
Log in or sign up to GitHub
Fork the project
Check out your fork
Manually “git remote add upstream”
Create a branch
Make your changes and commit them to the branch
Push your changes back to GitHub
Submit a pull request
(time passes, you want to submit another patch)
Pull changes from upstream to your local repo
Push your merging of those changes back to GitHub
Go back to step 5 for next patch.
The thing that really gets me is if I want to make a one line patch to a repo, I’m committing to creating and maintaining a fork. The necessity that I remember to pull changes from upstream and commit them if I ever revisit that project is particularly onerous. In practice I find myself deleting my forks after my pull request is done.
I’d really like to be able to do all this without GitHub, just using git’s native pull request support. Ie, let me just check out a copy of the master project (read-only), then make my changes locally and use some combination of git pull-request and git format-patch to upload my pull request to GitHub. But now that I look at it, maybe those tools aren’t robust enough. Not sure.
D3 3.1 includes support for SMASH, a way to make subset builds of D3. One thing I use D3 a lot for is the XmlHttpRequest support, particularly d3.json(). Most people use JQuery for AJAX, but I like D3’s version, but in either case I don’t want a 100k library just for a wrapper for XHR. Anyway..
Just JSON support is only 1464 bytes compressed, but it’s nice to bring in the CSV/TSV parsing. It’s 12k unminimized. Nice way to build a minimal XHR library. Didn’t test that it actually works ;-P
In a previous blog post I discovered that using .style(“fill”, ...) to set colors was way, way slower than using .attr(“class”, ...) to just switch the class. Which is all well and good, but what if I want to animate the color change? Ie: not just switch from white to black but use D3 transitions to show the grey between? Here are some options.
Class hackery: create a bunch of CSS classes “grey0”, “grey1”, “grey2”, ... that are a ramp from black to white. Then set .attr(“class”, greyN) with a tweening function that uses the classes. Seems awfully inelegant and hard to get right, particularly when you consider nonlinear easing functions.
Stylesheet manipulation. You can grab the CSS stylesheet itself and modify it. I found one D3 example. I have read lots of admonishments that modifying the CSS is hacky, flaky, and works differently in different browsers. No idea if this would be suitably fast; I can’t imagine browsers optimize this usage.
CSS transitions. Nominal support is pretty good, although I’m breaking my rule not to use vendor prefix CSS in my projects (stupid WebKit). Something as simple as rect { -webkit-transition: fill 0.4s } looks pretty good in Chrome. It does not look good in Firefox: it doesn’t seem to actually tween the color so really all you get is a 0.4s delay. No idea how it looks in Opera or IE. Oh well, I design for WebKit anyway.
CSS transitions have nice control over the easing function. However I don’t see any control over the interpolation, something that’s quite important and subtle when tweening colors. The spec says it interpolates in RGBA space which is just about the worst possible choice. Fortunately my example is tweening white and bright yellow, so I can get away with it, but a red to blue tween probably looks awful using CSS.
Are there any good tools for profiling rich D3 webapps, testing the changes in Javascript, CSS, and SVG design for how much time it saves? The best I’ve come up with so far is inserting calls to Date.now() in my code and using console.log() to print numbers. It works, but it’s primitive.
Chrome’s Profile tool doesn’t help me much. The Javascript profiler does, actually, giving me detailed analysis of why something is taking so long. But that’s a forensics tool, what I need is a benchmark wrapper around what I’m doing, something like Python’s timeit. But I don’t want to measure just Javascript code; I’m more worried about the CSS selection time, the DOM manipulation time, the browser render time.
Anyway, my Zipdecode thing is too slow. I’d like to optimize it, in particular so the interaction on the user typing a zip code is faster (and ideally, animateable). My original code is intentionally naive: select all 40,000 dots and set their “fill” CSS style to a specific color. It’s bad:
This take 140ms to do the update (and 650ms for the initial render).
Short circuiting the logic test about d.zip.substr() reveals that very little time is spent doing that. Replacing the call to .style() with a call to .each() that doesn’t manipulate the style drops the time down to 6ms; all my time is spent modifying the style, not creating the selection and iterating through it.
So the problem is mutating the .style(); no big surprise, but I can measure it! Let’s see how I can change the code to be better.
The obvious thing to try is to set the CSS class instead of a style property. The drawback with classes is there’s no way to interpolate the color easily. More on this in another blog post. But it works great, dropping the update time from 140ms to 25-30ms. Feels much faster. I tried this two ways
The first way using .attr() is 25-30ms; the second way calling .classed() twice is about 40ms, probably all from the overhead of that extra iterative function. I don’t think there’s anything particularly wrong about using .attr() to set classes, and since it’s simpler and faster I’ll stick with it.
A whole different optimization is treating to be smarter about the selection, not select all 40,000 dots every time. The code is not efficient in one important way; if I change the selection from “94” to “941” only 30 dots really need to be updated, but I go ahead and modify all 40,000 dots. But I don’t much care about fixing that because the case I’m most worried about is going from “” to “9”, where a lot of dots need to be touch (at most 1/10th of all zip codes, about 4000 dots).
But apparently I’m wrong. A version of this pull request from Ziggy Jonsson drops my interaction time from 140ms to 20ms, even less if the user is selecting a very narrow range of zips like “9414”. The key improvement is he’s only modifying the dots that are affected. (In addition he’s avoiding some calls to d3.select(), but I think that’s a smaller effect). Works well, but for my tutorial purposes I don’t like how it maintains this giant cached list of all possible zip selections.
Another way to achieve the same effect would be to use the hierarchy of the DOM to model the hierarchy of zip codes. Ie: instead of all the dots being top level <rect> elements, have a <g id=”9″> that contains all the 9xxxx zip codes (and in turn a <g id=”94″> inside that, etc. This would allow me to select with precision just the dots that need addressing, and might make the slower .style() method acceptable. But it significantly complicates the code and I don’t feel like doing that now that I’ve got stuff running pretty well. If I do it might be worth not going for the full hierarchical thing, just break zip code dots into the 10 top level categories.
In the HTML5 era programming in Javascript with browser APIs is mostly a joy. But sometimes you find a rough edge, in particular keyboard events. My zipdecode example had a simple problem: ordinary number keys worked, but not the numeric keypad. Because I was using the event.keyCode field, this ancient bit of savagery that tells me what button was pressed as opposed to what the user typed and both 48 and 96 mean 0. So I thought I’d try to update my code to the modern HTML5 way. Some things I learned:
keypress is the synthetic event fired off indicating “a user meant to type this thing”. If you can use it, use it. However it’s not always fired off, depending on the browser. (Ie: no left arrow in chrome). Also you can’t use it to suppress default behavior like backspace navigation.
keydown is the low level event fired when the switch is depressed. if you preventDefault() the event, in Chrome it means keypress is never fired but in Firefox it is fired anyway. (I think; didn’t test carefully.)
Any of the following fields of the event object may contain what button was pressed: char, charCode, key, keyCode, which. Most docs say “which” is the reliable choice (except for IE), but MDN notes it’s deprecated and says you should use key instead. Only “key” is not implemented in Firefox. Ha ha! Also while these fields are likely to be fileld out in a keypress event, they’re less likely to be present in a keydown event.
I was going to finish this blog post with a summary of the right modern way to do things, but I don’t think there is one yet. Then I was going to say this is a temporary state of affairs, but most of the HTML5-era questions I’m reading date back to 2010 so, um, not new.
I suspect the browser API mavens are scared to touch keyboard events. Partly it’s hard to specify because of internationalization, and partly it’s hard to implement because of cross-OS compatibility issues. I’ll note that jQuery apparently doesn’t have a library to solve this once and for all, either.
Update consider the d3.keybinding.js library from MapBox, for the iD editor.
I had no idea that neither curl nor wget will accept gzip encoding. They’re totally ignorant of it! You can set an Accept-Encoding header manually to tell the server to compress, but then you’re on your own to decompress.
I wanted to bind backspace on a web page, for a special UI. Had a hell of a time; the default behavior of backspace is to navigate the browser back a page in the history and it’s not easy to override. but long story short:
// Interaction: handle keyboard events (keydown to capture backspace)
d3.select("body").on("keydown", key);
function key() {
if (code == 8) {
// Prevent the browser from going back in the URL history
d3.event.preventDefault();
// Do your thing here.
}
}
Some things that don’t work: returning false in the event listener (it’s ignored), calling stopPropagation(), or binding keypress instead of keydown. Browser keyboard events are a total mess.
Wrote my first Python 3 program. I was trying to get a Python 2 program to read a CSV file and write it to sqlite3. Difficulty level: Unicode. After reading all the nonsense about how the Python 2 CSV module doesn’t really do Unicode but hey it’s OK it’s bytes and here’s a wrapper you can paste in your code, I got fed up and installed Python 3.
So far so good. My 20 lines of code ran exactly fine in Python 3 first try, with the benefit that Unicode didn’t suck. The only thing that really tripped me up doing things is that print is a function, not a statement, and that’s a very good change. I even tried out the new string formatting system, here’s an idiom for using locals() for quick debug printing:
My one concern is Python 3 co-existing with Python 2. The Homebrew install seems to name things “python3” and “pip3” and the like, so all is well? But the recommended “pip3 install --upgrade distribute” didn’t work; that fetched some version of distribute that’s not Python 3 compatible.
Now that I’m over this hump I hope to use Python 3 for more things.
Oh, the shame, look at the mojibake that showed up in the Atom feed for my real blog:
In detail, what happened… I get
From⎵ SMTP envelope
As opposed to
In detail, what happened… I get
From⎵ SMTP envelope
A quick wget -S ‘http://www.somebits.com/weblog/index.atom’ and I found the Atom feed was setting “Content-Type: application/atom+xml; charset=ISO-8859-1”. Like some cretin.
I have no idea why this charset was getting set. My ancient blog software (Blosxom, with a third party Atom plugin) doesn’t seem to be setting the charset explicitly. My best guess is that either Perl or Apache’s CGI helpfully inserts ISO-8859-1 as a default if nothing was explicitly said. Anyway I kludged the problem away by creating blosxom/entries/content_type.atom with the contents “application/atom+xml; charset=UTF-8”.
The Atom document itself specifies <?xml version=”1.0″ encoding=”utf-8″?>. Annoyingly Google Reader seems to believe the HTTP transport charset over the document itself. I have no idea what the spec says you’re supposed to do in this scenario, but I bet 9 times out of 10 the document is more correct than the server.
I’m often making D3 pages, or Leaflet maps, or some fancy Javascript thing. I always start with a blank editor and then have to remember all the HTML 5 boilerplate. So here’s some boilerplate, a template for starting a D3 + Leaflet project. The browser window is filled with the map.
This validates HTML 5. I’m not confident I’m setting the viewport correctly but this looks right in Chrome, Firefox, and Mobile Safari so good enough for me. I hate that HTML has so much boilerplate associated with it. Update: Mike points out HTML 5 doesn’t require so much boilerplate; tags like head and body are now optional. I don’t know what that means for old browser compatibility though so I’ll stick with the extra words. (Useful reference.)
I’ve never used the WebSockets API, so thought I’d try it. My goal: try to get arbitrary binary data chunks from a server as an ArrayBuffer. XMLHttpRequest can do this with the newish responseType property but I’m told it’s awkward, particularly if the data is gzip encoded. Also WebSockets sound like fun.
WebSocket support is sketchy: it’s supported in some modern browsers but not Microsoft’s; IE10 may support it. (To be fair, MS isn’t just dragging their feet, there’s security issues they were concerned about.) Also the Mozilla docs talk about things being prefixed like MozWebSocket; not sure if that’s still the case and if I need an API wrapper. I’m only using Chrome as a client for now.
Docs
Doc quality is a bit frustrating; the MDN docs are incomplete and the W3C Browser API is hard to read and takes a lot of filling in the gaps to understand. Feels like an incomplete spec to me.
Lots of options for implementing the server. All the cool kids are doing Node.js no doubt. I decided to stick with Python and try ws4py (github) on top of gevent.
brew install libevent # MacOS: it’s half a Unix!
pip install gevent
pip install ws4py
The ws4py docs have a trivial EchoServer implementation in gevent. I started there and added some basic message handling for a couple of commands (Echo and bytes).
from gevent import monkey; monkey.patch_all()
import gevent
from ws4py.server.geventserver import WebSocketServer
from ws4py.websocket import WebSocket
# Construct an array of 256 bytes, 0x00 to 0xff
bytes = b""
for i in range(256):
bytes += chr(i)
class MyWebSocket(WebSocket):
def opened(self):
print "Socket opened"
def received_message(self, message):
"Handle requests. Echo is echoed, bytes is a request for binary data"
print "Received message of length %d" % len(message)
if message.data.startswith("Echo"):
self.send(message.data, message.is_binary)
if message.data == "bytes":
self.send(bytes, True)
def closed(self, code, reason):
print "Socket closed %s %s" % (code, reason)
server = WebSocketServer(('127.0.0.1', 9001), websocket_class=MyWebSocket)
server.serve_forever()
Client
The HTML5Rocks docs have some very simple client Javascript that talks to the server they host. I started there and added some special message logic. Basically the client requests a special byte array consisting of 0x00 .. 0xff and then verifies it
actually received those numbers in an ArrayBuffer.
var connection = new WebSocket('ws://127.0.0.1:9001');
connection.binaryType = "arraybuffer";
connection.onopen = function () {
// When the socket opens, log it and send two messages"
console.log("socket opened, sending echo request");
connection.send('Echo this');
connection.send('bytes');
};
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onmessage = function (e) {
console.log('Message from server');
if (e.data instanceof ArrayBuffer) {
// If it's ArrayBuffer it must be the binary array 0x00 .. 0xff we're expecting
var byteArray = new Uint8Array(e.data);
if (byteArray.length != 256) {
console.log("Error; didn't get expected length 256");
return;
}
for (var i = 0; i < byteArray.length; i++) {
if (byteArray[i] != i) {
console.log("Error; got " + byteArray[i] + " at position " + i);
return;
}
}
console.log("Received expected 256 byte array");
} else {
// Print out any other message from the server
console.log(e.data);
}
};
Followup
I’d take a long hard look at browser compatibility and the future of WebSockets before building a serious product on it. The docs and sample code don’t give me a warm fuzzy feeling, and there’s been definite issues with IE support, etc in the past.
I have no idea what the state of the art is with respect to gzip encoding on WebSockets. There’s nothing in the spec I can find; maybe it’s up to the server? That’d be fine except AFAIK there’s still no browser-friendly zlib.decompress implementation, no way to decompress standard gzip data. It’s baked in to the browser but not exposed in a Javascript API, unless something’s changed since I last looked.
Apparently WebSocket is not subject to same origin policy. Yay! My Javascript client file at http://192.168.0.5:8989/ is happily getting data from ws://127.0.0.1:9001 and Chrome isn’t complaining. I haven’t done any sort of CORS thing and I don’t think any is baked in to ws4py. Worth investigating more later, particularly in the context of all the WebSocket security tsurris.
For basic hacking it’d be nice if the same server can serve ordinary resources via HTTP and special stuff with a WebSocket server. I think the protocol can do it and there’s a way to get ws4py to allow it (see UpgradableWSGIHandler) but I haven’t tried. For a serious deployment there’s an argument for keeping the two kinds of serving separate, particularly if you’re using WebSocket for long lived persistent connections.
Helping a friend think through a memory leak on his Heroku / Node.js server, he had a problem where nothing was being garbage collected. Big ol’ memory leak. Because NodeJS / V8 is so new as a server environment there’s not a lot of understanding of memory tuning, instrumentation, etc. Java has a lot of sins but after 10 years we all know how to make the JVM perform well; Javascript, not so much.
Anyway, long story short, my friend did some measurement and thinking and realized the problem. His server makes API calls that get a big JSON response from some other server. He extracts some data from that JSON and then throws the rest of the response away. Only it looks like the responses were never getting GCed. Best guess; the data he kept is a substring of the original JSON response, and V8 implements substrings as pointers into memory for the original interned string. So that original string can’t be collected.
His solution was to gzip the data he needed. Which is smaller in memory, but even better means that it’s a real new string and not a copy. It seems to have fixed the problem.
Update: this may not have been the problem or a correct diagnosis at all. He’d been setting --max_old_space_size incorrectly; fixing that may have fixed everything.
The connoisseurs of fine artisinal integers discovered my blog post about Cantor pairing and asked some questions. Apparently there’s a sudden interest in creating more foundries and my proposal for allowing an infinite number of sequences thanks to the magic of infinity got some reading. However, taking advantage of that infinity requires an O(n^2) generator algorithm, a bit impractical. How impractical?
One reasonable question is “when do we generate integers bigger than 2^64?”, since that’s such an awkward number for our 64-fingered CPUs. With the current simple even/odd split for two foundries, we can generate 2^63 integers before running out of room, so many it’s hard to call them artisinal really. But with the Cantor numbering we hit 2^64 much sooner: it will be site #3,327,948,883 generating its 2,746,052,116th number that is 2^64. Or to put it in plain English, every foundry gets to generate about two billion integers before hitting the limit.
2^53 is another practical limit, since that’s the biggest integer Javascript can handle (and then, only if you’re lucky). Sites can only generate about two million integers before hitting 2^53. That’s low enough to cause a real crisis in artisinal integers, particularly for the Node.js hipsters.
I submit the practical solution is to pick a large fixed number of integer foundries, say 1000, and simply have each foundry agree to generate numbers in the sequence (eg) 1003, 2003, 3003, 4003. It lacks elegance but is probably sufficient to meet demand. It also sets up a perfect excuse for a hipster sellout should the demand for artisinal foundries explode and the number boffins need to start paying for their fixed gear bicycles and ironic bottled beers; simply start charging for those last few valuable foundry IDs. Scarcity is the business model’s best friend.
#!/usr/bin/env python
# Cantor pairing function, a bijection from Z*Z to Z.
# http://nelsonslog.wordpress.com/2012/07/29/artisinal-integers/
# http://en.wikipedia.org/wiki/Cantor_pairing_function#Cantor_pairing_function
import math
def cantor(x, y):
return (x + y) * (x + y + 1) / 2 + y
# could cache calculations for efficiency
def _w(z):
n = math.sqrt(8*z + 1)
return int(math.floor((n-1)/2))
def _t(z):
w = _w(z)
return (w*w + w) / 2
def invCantor(z):
t = _t(z)
w = _w(z)
y = z - t
x = w - y
return (x, y)
for i in range(0,10):
print cantor(0, i),
print
for i in "0 2 5 9 14 20 27 35 44 54".split():
print invCantor(int(i)),
print
print cantor(18225714/2, 1)
print invCantor(41522085907653)
for power in 64, 43:
biggy = 2L ** power
x, y = invCantor(biggy)
print biggy, (x, y), (math.log(x, 2), math.log(y, 2))
As near as I can tell, Javascript lacks a function to load more Javascript from a URL. There’s eval(), but that takes strings so it’s a bit of work. The usual hack is to add a <script> tag dynamically to the document which as a side effect causes the page to load the referenced script. Here’s a wrapper function for that, courtesy of this July 2009 writeup:
It’s overkill, but it’s cut and paste.I needed this to add jQuery to a page so I could then dump the URLs out of it with $("a").each(console.log(this.href))
Mike tells me he uses this bookmarklet to add D3 to pages. Node.js has the require() function. If you’re serious about dynamic code loading in browsers then requirejs looks good.
Mission Integers and Brooklyn Integers are hipster web services that generate unique integers. Cleverly, they cooperate so the integers are unique across both sites. They did it the easy way; Mission returns even numbers, Brooklyn returns odd ones. I wanted to add a third site but there’s no way to do that, they’ve claimed all of the integers already.
So... can you generate integer sequences such that there can be an infinite number of generators with no collision? Supporting any predetermined number N of sites is easy; have site S generate s + n, s + 2n, s + 3n, s + 4n. But what if you don’t know N ahead of time? Yes, with maths!
Let’s say the Nth number that site S generates is the pair (S, N). We need an algorithm that creates a bijective mapping between (S, N) and the integers. Ie, for the current setup, Mission, even numbers, is site 0. Brooklyn, odd numbers, is site 1. The algorithm for number (S, N) is currently return n*2 + s
The trick is creating a bijection from the set of all integers to the set of all pairs of integers. I remember from college math this is possible (the cardinality of the set of all integers Z is the same as the cardinality of the cross product ZxZ) but I’d forgotten the constructive proof. Happily, Wikipedia remembers: something like the Cantor pairing function. http://en.wikipedia.org/wiki/Cantor_pairing_function
And the function for (s, n) is...
return ((s + n) * (s + n + 1))/2 + n
The picture is the useful intuition; basically you’re laying the tuples down on a square, then counting off cells.<
This kind of bijection comes in handy as a way to code large 2d spaces into 1d. I feel certain there’s an application for maps.
The drawback to this approach is the size of the Nth integer is O(N²). Mission integer 18,225,714 is 41,522,085,907,653 or about 2⁴⁵ in the cantor numbering.
I’ve never written my own XMLHttpRequest; I’ve always used jQuery or D3’s libraries. I had some sneaking suspicion one could do better than those wrappers in a modern HTML 5 setting, particularly for error handling, so for this project I wrote my own XHR code.
And turns out, nope, I’m not doing anything clever that those other libraries doesn’t. I’m doing less, really, my error handling is just as bad and there’s some clumsy stuff. Also this code only handles a really well behaved service; hasn’t been battle hardened against perverse replies or old browser versions. It does work for me though.
// Make AJAX calls, assuming JSON replies
function jsonRequest(url, callback) {
console.log(url);
var req = new XMLHttpRequest;
req.open("GET", url, true);
req.onreadystatechange = function() {
if (req.readyState === 4) {
if ((req.status >= 200 && req.status < 300) || req.status == 304) {
var d = JSON.parse(req.responseText);
callback(d);
} else {
// Bogus error handling
callback(req);
}
}
}
req.send();
}
Cross-platform Javascript has gotten a whole lot better in the HTML5 era. I developed all of Tweetchive without testing it at all in anything other than Chrome. It just worked in Firefox and Safari and Mobile Safari. IE9 still takes a bit of work, had to make two changes:
Added <!DOCTYPE html>. Other browsers don’t care, but IE9 runs in quirks mode without this and leaves out useful things like the JSON functions.
Dropped in Moment.js to parse dates. new Date(“some random localized string”) does a good job of parsing dates in most browsers, but not in IE.
moment(fullTweet.created_at, “ddd MMM DD HH:mm:ss Z YYYY”).valueOf()
I’m using the Twitter API for a project. The results it returns are.. awkward. In particular you often get errors for legitimate requests, but if you try the exact same request again a few seconds later it will work. Presumably their internal caching / timeouts.
Anyway, I need a good way to do error handling of AJAX calls in Javascript. But because I’m doing cross-origin stuff (and Twitter doesn’t set the CORS header) I’m stuck using JSONP. And JSONP error handling sucks, presumably because the crazy <script> eval hack that makes JSONP work doesn’t let Javascript code handle errors.
Options:
jQuery Timeouts. Since version 1.5, jQuery will throw a timeout after N seconds if the JSONP call did not succeed. This gives you limited error notification, albeit asynchronously.
suppress_response_codes. This is a special hack to the Twitter API to always have them return HTTP 200 OK, even on errors, and let you figure out the error in the body. Using this lets you bypass the browser’s own handling of, say, a 400 error and let your Javascript code handle it. Ie when I’m rate limited I get a “400 (Bad Request)” from the API which Chrome intercepts and all I see is a timeout. Presumably with this Twitter API setting, I’ll get a 200 reply immediately that contains info on the error I can parse.
Try Zepto. Their JSONP code is different from jQuery and a preliminary look suggests it might have a better error handling strategy. Seems unlikely, but worth a look?
JSONP is such a horrible hack. I wish Twitter would just set the CORS header and I could use a proper JSON call with XmlHttpRequest with proper error handling. I could do that myself if I proxy the traffic on my server, but then it’s my bandwidth and my IP address being rate limited.
A few weeks back I wrote up a trick for making a div fill the remaining browser height using Javascript to calculate a pixel height for the div on resize events. That seemed clunky to me and I just stumbled on a StackExchange question with an alternate method that’s CSS only using absolute positioning. Basically you create a box with top/left/right/bottom set to 0, then save a fixed amount of space at the top. The example uses padding-top, but I found I had to use margin-top instead, at least for a Leaflet map.
In retrospect I should have thought about this absolute positioning idea before! it makes much more sense. And it’s simpler not running any event code.
I’m doing a lot of AJAX development lately so I have to serve my HTML via HTTP, because AJAX just won’t work with file: URLs. There’s a lot of ways to launch a simple HTTP server in your current directory, here’s a handy bash function to do it (using Python)
There’s a bogus bit here, using “ifconfig en0” to try to guess the right IP address to show. On a Linux box that’d be “eth0”, and in general it’s hard to know which of a machine’s IP addresses you really should use.
Update: I’ve tinkered with this script a little bit. It’ll supply a random port number if one isn’t given. And it’s a bit smarter about figuring out a likely IP address.
The confusing thing is that Date is both a Javascript class that returns Date objects and a convenience function that returns strings. Most of my Javascript programming is in D3’s style which never uses constructors or the “new” keyword; instead its “classes” are functions that return objects. But a lot of core Javascript isn’t like that. Neither is Leaflet; I keep forgetting to say “new” there too.
msgpack sounds like it could be useful: a binary format alternative to JSON that promises to be “like JSON but it’s faster and smaller”. Is it really? Not significantly; on a sample of 175 JSON files I had lying around the msgpack files were on average 75% the size of the JSON files. Better, but not significantly so. And if you’re a bit careful with JSON formatting and float precision, it’s not clear msgpack has anything to offer.
The big winner (ukiah.json, msgpack is 12% the original) is a GeoJSON file with a few thousand lat/lon coordinates in it, all pretty-printed with spaces. Some files actually get bigger with msgpack; a quick look suggests those are files with short floats in them like “32.17”, and it may be the Python encoder is giving those a full 8 bytes for an IEEE double.
For a file I actually care about, my WindHistory stations-md.json database, the 1 meg JSON files goes to 500k. That’s a big win for me in a deployed webapp, I think msgpack may do a particularly good job with the arrays of small numbers that file contains, e.g. [0,5,6,4,4,15,18,14,9,5,7,7,6]. I’d considered doing a custom format for that, dropping in msgpack would sure be easier.
Update: I did a quick extra comparison, passing the data through zlib.compress() after encoding, before comparing lengths. Compressed msgpack is worse than compressed json! For my sample, the msgpack/gzip data was on average 106% the size of the json/gzip data. For the WindHistory database the msgpack was still smaller, but only a little; 90%. gzip must be good at removing the text redundancy in json files full of numbers. OTOH I don’t understand why msgpack would ever be worse.
I took a quick look at the format spec: I think all msgpack is doing is storing numbers in binary instead of ASCII. That’s an improvement, particularly for codec speed, but it doesn’t seem to make all that big a difference in size. Here’s the msgpack author’s own opinion on comparison to other formats. The most useful link is the StackExchange answer.
What I’m really hoping for is an encoding that divines the structure of the stored data and builds compressed representations based on an ad hoc schema. It’s not crazy, folks were doing this with XML in Java webapps 10 years ago. But it’s not easy either. First step; a lookup dictionary for key names in object maps.
import json, sys, msgpack, os
pcts = []
for fn in sys.argv[1:]:
try:
jsonData = file(fn).read()
data = json.loads(jsonData)
except: continue
msgData = msgpack.packb(data)
pct = 100.0*len(msgData)/len(jsonData)
print "%d%% %s json %d msgpack %d" % (pct, os.path.basename(fn), len(jsonData), len(msgData))
pcts.append(pct)
print "%d%% average size" % (sum(pcts) / len(pcts))
Python’s date and time APIs are awful. Actually they’re awful in most languages, Java’s were sure terrible. But Python is worse because it has several ways to do things and none of them are really correct. The newish datetime module is better than the old time module and its bizarre “tuple that may or may not be timezone aware” type. But even datetime is stupid about time zones, only supporting UTC or the local computer’s time. You need the add-on pytz to bring in the Olson timezone database to start doing real work, and even then it’s complex.
I have some timestamps, seconds-since-Unix-epoch, which is intrinsically UTC. Unambiguous integers. Now I want to print them in Florida’s timezone, no matter what my computer’s time zone is. Here’s one way:
This seems to work, but the pytz docs admonish “Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones. It is safe for timezones without daylight savings trasitions though, such as UTC” The docs recommend this instead:
I’m not positive, but I think my simpler code actually will work as long as I don’t try to do anything fancy with floridaDatetime like arithmetic. The problem is described in detail in the pytz docs: it’s some combination of datetime being limited and that certain timestamps are ambiguous because of DST. So really pytz is encouraging us to always always always only ever do math with UTC time and defer conversion to local timezone to the last possible moment before string output. Which is imminently sensible, if frustratingly verbose.
I think the right library would be a datetime type whose internal representation is always only ever seconds-since-epoch plus desired timezone. That way all the library code can do arithmetic without worrying about DST. I wonder if any other languages do it that way. Python’s got some unfortunate legacy hanging around and I don’t think Python3k tried to fix up the mess.
A little sketch inspired by Eyeo Festival, redoing Jared Tarbell’s invaders in D3. Image is 2560x1440 and needs to be viewed without zoom for proper effect.
When putting maps on pages I often want the map to take the full browser height, not some fixed pixel height. That’s easy, just set height: 100% and the map fills the browser. But what if you want to reserve some space at the bottom, say for a text display? I don’t think any flavor of CSS lets you set height to “100% - 100px”, and I don’t know of a way to trick the box model of CSS alone to say “reserve 100px and then fill the rest with this thing”. It may be doable in pure CSS, but I don’t know how.
However it is doable with a bit of Javascript. In this case we have a map that fills all of the window but the last 150px, then a time series graph in that last 150px.
<!-- The map itself. Height set by Javascript. -->
<div id="map" style="width: 100%;"></div>
<!-- Divider -->
<div id="divider" style="background-color: black; height: 1px; width: 100%"></div>
<!-- Time series graph at the bottom -->
<div id="graph" style="width: 100%; height: 150px; background-color: white"></div>
// Resize the map so that it's the height of the window minus the graph
function setMapHeight() {
var graph = document.getElementById("graph");
var divider = document.getElementById("divider");
document.getElementById("map").style.height = window.innerHeight - (graph.offsetHeight + divider.offsetHeight);
}
window.addEventListener("load", setMapHeight, false);
window.addEventListener("resize", setMapHeight, false);
I’m storing 500k blobs in localStorage. I’d like to make them smaller. In any sane platform there’s some compression function in the library: gzip(data) and it’s 30% the original size. But no, not in Javascript. And there’s no clear third party library that everyone agrees is great.
I found a good roundup of compression options from October 2011, it’s a series of 4 blog posts. It has a lot of detail on speed and compression of 11 different libraries. Hilariously, about half of them simply don’t work or are only capable of doing half the compression / decompression. This StackExchange question is good because it’s specific to localStorage.
Part of the problem is just like Javascript doesn’t have an integer type, it also doesn’t have a byte array type. The basic String (DOMString?) is close, but really it’s a sequence of Unicode characters. So to be efficient you really want to use all 16 bits for each character in the String, although that StackExchange question recommends only using 15 bits to avoid issues with UTF-16. And suddenly we’re at awkward storage. And even storing only 8 bits per word in the String, a lot of these compression libraries seem to have problems storing various “special characters”; apparently getting encoding and decoding right is not easy. You see a lot of base64 encoded data in Javascript strings out there, yuck.
Javascript typed arrays look to be the standard solution for binary data; you create a byte array and then get views into it treating each word as an Int8 or Int32 or whatever. I’ve never worked with them and am unsure about compatibility in current implementations. Also I haven’t found an existing Javascript library that compresses using them.
Related: see this discussion of byte array objects. He discards Strings early because they’re immutable and so modifying a single byte requires a full String copy. He compares ordinary Javascript Arrays, typed arrays ArrayBuffer, and (clever), ImageData. He finds the APIs for the fancy array types are unreasonably slow. No evaluation of size efficiency or ease of use, things I care about.
I think my solution is to use some very simple LZW compression or the like, combined with an encoder that uses 15 bits per word in a String. It’s be nice to wrap this up in a simple API, something that takes an Object, stringifies it with JSON, compresses it, and returns a safe String that can later be unpickled back into the Object. Not sure I need it enough to bother.
I played around with HTML5 localStorage today, a way for Javascript on a web site to store persistent data client-side in the browser with a simple key/value store. It’s pretty neat, works well in modern browsers (IE8+, everything else), but is kind of slow. Here’s what I learned.
Storage size: can count on 2.5 megs in most browsers.
The API is really simple. Boils down to
setItem(key, value)
getItem(key)
removeItem(key)
clear()
key(index)
length
key and value are both strings. If you want to store Object values, as is sensible, you have to serialize them yourself to JSON like this.
length and key(index) let you iterate over the collection in an undefined order. Also it’s undefined what happens if someone asynchronously modifies localStorage while you’re iterating. localStorage is not an Array, so you can’t use modern methods like forEach() on them. Back to the old school for loop.
It all works pretty well and is straightforward. My one complaint is it seems pretty slow, at least in Chrome. I’ve put about 3200 objects in localStorage, about 200 bytes each. That’s not much data, but with it even just iterating over all the keys (doing nothing with the values) is slow, like 400ms. Here’s my code that is so slow:
function getLocalKeys() {
var localKeys = [];
var n = localStorage.length;
for (var i = 0; i < n; i++) {
localKeys.push(localStorage.key(i));
}
return localKeys;
}
Surprisingly, doing real work on the values isn’t much slower. I can parse all the value strings back into Javascript objects and then sort an array of all 3000 objects and it doesn’t add appreciable time to the work. That suggests all the time is spent in the localStorage implementation itself. I wonder if it’s actually going to disk? Need to dig in more.
I could optimize by storing my collection of all keys itself as a value in localStorage, sort of my own index. But that’s brittle if I forget to update it in the code.
Update: some performance notes here and here confirm it’s not just me seeing bad performance. One issue is that localStorage needs to be synchronous across multiple browser tabs, so localStorage may be implemented as purely on-disk to do that easily. Both benchmarks suggest Chrome is uniquely slow and indeed my code runs visibly faster in Safari.
Update 2: I rewrote my code to simply have one object in localStorage, itself a stringified Javascript Object operating as a hash table. That works much, much faster; the storage time is negligible. My data is 500k stringified, btw, uncomfortably close to the 2.5MB limit!
HTTP/1.1 200 OK
X-RateLimit-Limit: 150
X-RateLimit-Remaining: 112
X-RateLimit-Reset: 1337888547
X-RateLimit-Class: api
Content-Type: application/json;charset=utf-8
Last-Modified: Thu, 24 May 2012 19:26:16 GMT
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Pragma: no-cache
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Set-Cookie: guest_id="v1:133788757695829242";Expires=Sat, 24-May-14 19:26:16 GMT;Path=/;Domain=.twitter.com
Status: 200 OK
X-Transaction: a990ed040a2ffcdd
X-Frame-Options: SAMEORIGIN
Date: Thu, 24 May 2012 19:26:16 GMT
Server: tfe
Content-Length: 86940
Sadly, there’s no Access-Control-Allow-Origin header there to allow CORS. The Twitter API does support an optional callback= paramter to get them to emit JSONP instead. I was trying to use D3’s AJAX library to make the calls, but it only supports CORS and not JSONP.
Quick thought.. Mongo is awesome for quickly hacking up a persistent data store where you’re not quite sure what data you’re storing. Schemaless = fast storage coding. But then Mongo is bad at letting you do complex queries, because you have to do all this hand rolled mapreduce crap. SQL = fast query coding. It’s an interesting tradeoff; I want the best of both worlds!
A blog post I wrote on a foreign laptop ended up with byte values 0x92 for apostrophes and 0x93 and 0x94 for quotes. This is an old Windows “smart quotes” and makes sense in Windows code page 1252. It is not valid ISO-Latin-1; that encoding doesn’t have typographical quote marks in it.
Easy enough to fix once the encoding is identified: “iconv -f windows-1252 -t utf-8”
I should make a website that has one web page per code point. So you could go to a page named “0x92.html” and see what all it translates to in the world’s various codecs. There’s a bunch of one-page-per-Unicode-character sites out there, but I don’t know of a resource that lets you easily guess a mystery encoding by a few examples.
I wanted to download 1300+ images from a Dropbox gallery. Unfortunately Dropbox’s UI is so dynamic with Javascript there’s no simple list of URLs. So instead of trying to reverse engineer their code I opened up the Javascript console after the page had loaded to extract the dynamically generated HTML links.
l = document.querySelectorAll("a.filename-link")
a = []
for (i = 0; i < l.length; i++) { a.push(l[i].href); }
for (i = 0; i < a.length; i++) { console.log(a[i]); }
Pretty straightforward, but a lot more tinkering during the process. Those URLs lead to the image page; to get to the actual JPG you have to append “?dl=1” to the URL.
My whole work environment is UTF-8. Except Python. Python’s “print” will encode in UTF-8 if its printing directly to a tty. But as soon as you pipe that tty to something Python reverts to ASCII. And it’s a real PITA to overcome that.
Here’s one ugly kludge to make Python always treat stdout as UTF-8. It causes problems with some tools, but is sufficient for hacking around:
I’ve been using RunKeeper to track my walking. I wanted to work with the 40+ GPS tracks they’ve logged for me and didn’t want to download them one at a time. Some quick notes on how to scrape them all out.
Save that big HTML page to a file named activities.html
Capture the IDs of all your activities from that page with a regexp like this:
printMatches ‘link=”/user/USERNAME/activity/([0-9]+)’< activities.html > ids
Look in your browser for your JSESSIONID cookie. That’ll stand in for a login.
Use wget with that cookie. Here’s my little shell script to get them all
cat ids | while read id; do
wget --no-cookies \
--header 'Cookie: JSESSIONID=C~2BF2D2156284732CE8D8BDA900000000' \
-O $id.gpx \
"http://runkeeper.com/download/activity?activityId="$id"&downloadType=gpx";
done
Set up a PostGIS database with all the data
createdb walks
psql -d walks -f postgis.sql
psql -d walks -f spatial_ref_sys.sql
psql -d walks -f postgis_comments.sql
for f in *gpx; do echo $f; ogr2ogr -append -f “PostgreSQL” PG:dbname=walks $f; done
ogr2ogr will create a fancy schema for you that contains every field ever seen in a GPX file. For RunKeeper data, the salient things are:
tracks.wkb_geometry: one row per track, multiline string
track_points: one row per point with a point, elevation, timestamp, etc.
QGIS did a fine job rendering the tracks table for me. I also pulled in a raster OSM map for a base layer from http://wms.latlon.org/.
Here’s a quicky query to get the length of a track in miles. Need to understand the ST_Transform better, also join to something else to get proper data about each imported track.
select name, ST_Length(ST_Transform(wkb_geometry, 2163)) /1609 as miles from tracks order by name;
A quicky view to simplify the tracks a bit, plus a query that compares the length of the original and simplified views.
create or replace view simple as
select
ogc_fid,
ST_Simplify(wkb_geometry,0.00005) as track,
name
from tracks;
select
tracks.name,
ST_Length(ST_Transform(simple.track, 2163)) /1609 as miles,
ST_Length(ST_Transform(tracks.wkb_geometry, 2163)) /1609 as miles
from simple inner join tracks
on simple.name = tracks.name order by name;
I’ve finally got an editing tool that does enough with Markdown to be useful: Notational Velocity. No WYSIWYG, but the live preview is pretty great. Shockingly there’s no really concise quick reference to all of Multimarkdown; it’s full of ugly complex stuff. The Human Markdown Reference is pretty good, but I made my own.
# Header 1
## Header 2
### Header 3
Text can be _italics_ or **bold** or `fixed width`.
> This is a blockquote.
* lists are
* implicitly formed
We can make [basic links](http://www.somebits.com). You can also do this [Stupid link style][1].
[1]: http://www.google.com/
code samples come
by indenting four spaces
| Features | Advanced? |
- | -
Tables | Yes
Paragraphs | No
----
Multi-markdown link: <http://fletcherpenney.net/multimarkdown>
When my old server died I had some data in Postgres. I don’t think it was anything important but I can’t really be sure, I’d like to recover it. All I have are the binary files Postgres stores its data in. Turns out recovering from those sucks. Lesson learned: if you care about recovering your data, back it up into a SQL dump.
Postgres makes no effort to make its binary files compatible between versions. A 9.0 database can’t be used in a 9.1 install; when you upgrade, you have to run a funky recovery tool which dumps the 9.0 db and imports it to 9.1. A 9.0 database on a 32 bit machine can’t be imported into 9.0 built for a 64 bit machine, either. I’ve also seen problems in the past trying to work with data from a PostGIS database in a non-PostGIS install. I’m sure this format flexibility makes it easier to build a fast database engine, but it sure makes data recovery difficult.
I tried building 9.0 sources on my amd64 box and running it. That was easy enough, although setting up users and permissions is a bit finicky when installing by hand. But the DB was generated on an i386 box (32 bit) so it won’t load. At least it failed quickly, “FATAL: incorrect checksum in control file”. Then I started looking in to cross-compiling and realized the last thing I want is to set up a whole separate build toolchain. (A quick try with the linux32 command didn’t work.)
So screw it, what was I really storing in Postgres anyway? Not much, I did a quick test to see:
Only one Python program I wrote even imports the Postgres driver. And I can recover that data from original sources. I think I have some geodata I imported with shp2pgsql, too, but I can redo all that. So I give up on recovering data.
Cross-compiling
Maybe I gave up too fast. Building a 32 bit version of Postgres on Ubuntu was as easy as
(there’s probably 32 bit versions of readline and libz, but I don’t really need them). Building a server this way, my amd64 machine can load the database binaries generated on the i386 machine. I had no idea the 64 bit Linux distributions could build 32 bit code so easily.
And it works! “psql -l” to find what databases were there, then “pg_dump database” to get the data out, then “psql” to get the data back into my 9.1 database. Yay!
Backups
Lesson learned, I’m now doing some simple nightly SQL backups of my databases. There are fancy ways to do this, I’m going very simple:
Looking at traffic stats and Google’s mod_pagespeed I thought of a way to optimize my blog a bit: replace some of the small images with inline data: URLs. According to Wikipedia this works in all modern web browsers. IE7 is out of luck, but it (kind of) works in IE8.
For example, this Creative Commons logo is a 1082 byte GIF. Small, but there’s a lot of overhead in doing an HTTP request just for that image used in one place on my page. Fetching with wget takes 11 packets and 3 or 4 round trips. (A little better in a real browser with HTTP keepalives).
As a base64 data: URL it’s only 1467 bytes. That adds 1-2 TCP packets to the request and 0-1 round trips. The downside of inlining is that the image is now served with every single HTML page. No caching and bots will have to pay for it too. In the end I think it’s more work for my server, less work for the client, which is a good tradeoff for small images. (It may be less work for the server in general; fewer client requests per page.)
I arbitrarily decided 3k was the cutoff for converting to data URLs. That results in 5 images:
I converted the images via this online encoder. I am too lazy to measure the actual impact the change had, too much trouble. The HTML size of my blog went up 10k (46k vs 36k), but I’m loading 5 fewer HTTP requests (16 vs 20) and not loading about 7k worth of image binaries. I’m optimistic.
bash-4.2 (default on Ubuntu) has a super annoying bug.
d=/usr/bin ls $d/ssh-keyg[user presses tab] ls \$d/ssh-key
In a nutshell, bash “helpfully” adds a backslash to escape the dollar sign because the user must have meant the literal character $. Previous to bash-4.2 it would have expanded the variable, so we would have seen “ls /usr/bin/ssh-keygen” instead. Which is way more useful
A quick search online finds the usual set of incorrect explanations and cargo-cult changes to bash-completion. (A popular fix is to use complete to make it so that the “cd” command works, leaving expansion broken for every other command.)
The actual truth is that this expansion is intended behavior in 4.2. Chet Ramey himself said so. He also recognizes this is awkward and has written a patch to add a new shopt called “direxpand” that will restore the desired, pre-4.2 behavior. Sadly that patch hasn’t made its way into Ubuntu’s Oneiric distribution yet.
One workaround for now is to press ESC C-e before hitting tab; that forces the command line to expand everything first.
I’m working on rationalizing my MP3 collection. Here’s a Python script to print out the names of all songs that seem to have been bought from Amazon MP3. It uses the presence of “Amazon” in the ID3v2 comment tag. It’s not entirely reliable; songs I bought in 2007, 2008 are missing that tag.
#!/usr/bin/python
"""Print out names of MP3 files that are from Amazon.
Works by looking for the Amazon ID3v2 comment tag with a song ID.
This method is not complete: some early Amazon sales don't have this."""
import sys, os
from mutagen.id3 import ID3
def isAmazon(fn):
"Return the Amazon comment if it's an Amazon MP3, else None"
id3=ID3(fn)
for c in id3.getall('COMM'):
if "Amazon" in str(c):
return str(c)
return None
for dirpath, dirnames, files in os.walk('.'):
for name in files:
if name.endswith(".mp3"):
fn = os.path.join(dirpath, name)
try:
if isAmazon(fn):
print fn
except:
pass # ignore errors
sys.exit(0)
I use git enough now that my repositories are getting a bit messy. I decided to centralize them all in one place so I can access them over the network. (You know, the distributed part of DVCS). There’s lots of options, I settled on just using a bunch of bare repositories on a host I can ssh to.
Alternatives I considered.. Dropbox is a good alternative for the central git repository but I’ve got my own server so I’m using that. The git:// protocol seems like unnecessary complication. As for hosting and web frontends.. GitHub is too expensive for my 10+ private repos,, charging per repo. Sites like repositoryhosting, gitorious, codeplane, and bitbucket have cheap or free options, but I don’t really need a centralized host since I’m mostly working alone. I could also have gotten fancy and installed something like gitolite to have a webapp front end, but that’s overkill for me now. Maybe I’ll set up gitweb at some point.
Here’s how I migrated my exisiting ad-hoc repos to one canonical gitrepos directory on a server. I found a lot of conflicting and incomplete info on how to do this, for instance these notes, this blog post, and this stackoverflow post. Correctly getting all branches into the new canonical repo and then patching up the config of the old ad-hoc repo is not straightforward. I’m not confident this is really correct, either, but it seems to work for simple things.
Find all the .git repos. Still have to hand-edit this list.
$ find ~ -type d -name .git | egrep -v '/d3|polymaps/'
Create a new bare repo in my new ~/gitrepos directory, based on code from ~/src/dotfiles.
$ cd ~/gitrepos
$ git clone --bare ~/src/dotfiles dotfiles
$ # is this a good idea? necessary?
$ # cd dotfiles; git remote rm origin
Change my old ad-hoc repo to consider this bare repo as its origin.
$ git remote add origin ~/gitrepos/dotfiles
$ git push
$ git branch --set-upstream master origin/master
That bit about pushing and then setting the upstream is 100% black magic for me, I have no idea what it does. It seems to be necessary to create the magic so that later “git status” will tell you if your local branch is ahead of the canonical copy in ~/gitrepos. The push is necessary for some git config reason, even though there’s nothing to push. I find it confusing how git uses branches to track remote repos.
Also useful: “git remote -v” for seeing what remotes are configured, and “git branch -avv” for seeing more about git’s local view of various branches and remotes.
None of those examples above use a really remote repository, it’s all just Unix file paths. You can so name repositories like “nelson@example.com:~/gitrepos/dotfiles” and it will ssh to example.com and everything just works.
I almost always regret using uber-compressor bzip2. It generally compresses to, oh, 90% of the size of gzip but takes 10x as long to compress and 2x as long to decompress. Not worth it, bad space/time tradeoff.
The exception is Apache access log files. Something about the terribly repetitive text of these things is really good for bzip2. Here’s a quick test on a 26 meg access.log (using bzip2 1.0.5 and gzip 1.4 on Debian i686)
gzip: 10.8%, 860ms to compress, 160ms to decompress
bzip2: 5.7%, 12700ms to compress, 1600ms to decompress
The bzip2 is literally half the size of the gzip. That’s a lot. Too bad it took 15x as much time to generate it and 10x as much time to decompress it again. A quick Google suggests most people find bzip2 about 3x-5x slower, not sure why it’s so bad for me. Maybe because my sample is also unusually good at compressing!
Some other fast compression options: pigz, pbzip2, threadzip for parallel compressors, or snappy for Google’s very-fast-but-not-as-tight compressor.
METAR, the weather observation format, is a great little text format
KOAK 032353Z 00000KT 5SM BR SCT200 11/08 A3029 RMK AO2 SLP256 VIS SE 1 1/2
It’s also not a very standardized format, making parsing a bit of an art. Here’s a few different METAR parsing libraries I’ve found:
Tom Pollard’s python-metar, (sourceforge, github). This is what I used to prepare windhistory.com and it’s pretty good.
Joe Yates’ metar-parser for Ruby. Has some test coverage. Also references other Ruby implementations.
METAR decoding software from NWS. The closest thing to official code, written by Eric McCarthy, now on SourceForge. It’s 12,000+ lines of C code (!), albeit with a lot of comments, unit tests, etc. Has some interesting code for interpreting the meaning of METARs, like whether it codes for a tornado or the like.
There’s lots of other parsers for various languages: PHP, .NET, etc.
I keep forgetting the right way to make a DIV take up the full height of the web browser. For, say, a full screen map. Chrome and Safari default to filling the whole container but Firefox prefers to calculate a minimum height div. Long story short, here’s what to do:
html, body, div#map { height: 100% }
I’m not entirely sure this is correct but it seems to work and is in line with advice on this StackOverflow discussion. It’s not enough to set the div’s height, you have to set the containers too. There’s also something about using min-height instead but it seems unnecessary. What I don’t know is how to set the height of a div to be 100% minus 100px or the like; something that leaves room for a header or footer.
I’m working on replacing my existing IDE (WingIDE) with Sublime Text 2. I prefer Sublime as an editor, particularly since WingIDE runs under X11 on MacOS (yuck). Also I don’t use most IDE features of Wing; just a bit of smart completion, unit test integration, pdb integration, .. OK, several things.
Anyway, here’s a list of Sublime Text modifications I’m finding useful for Python. I’ll update this post over time. (As an aside it’s hard to search for plugins for Python developers, because the plugins themselves are written in Python and so you get lots of false matches.)
sublimetext_python_checker: one of several linter plugins. I like this one because I can set it up to run PyFlakes in an unobtrusive way.
PdbSublimeTextSupport 0.2: a tiny shim to have Sublime show you what line of your source code it currently is in. I’ve never been good with PDB, I immediately miss all the graphical support of a full IDE like Wing. So this may not be enough.
I’ve also set up my own build command to use to run unit tests. It’s not complete, I need to figure out Sublime’s support for showing where errors occurred. But it’s a start.
I was playing around with Python lint tools. There’s a lot of terrific info in this StackOverflow question, so all I really have to offer is some very simple knee jerk opinions.
pyflakes is very brief, but did a good job finding actual errors
pep8 is a nice way to check specifically for code style issues and nothing else.
pychecker is useless, since it executes the code
pylint is amazingly detailed and anal. Also useless because it prints way way too much. I really don’t care that my test functions don’t have docstrings or that my comments are more than 80 characters. Maybe if I were working on more team projects I’d build up a set of “ignore this message” rules and turn it into a useful tool to me.
Conclusion: pyflakes. If I cared more, I’d use pylint. If I were contributing code to libraries, pep8.
I decided to try out Riak on MacOS, using Homebrew to install. Here’s some rough notes.
“brew install riak” worked. However, it didn’t leave you the Makefile you need to do “make devrel” in order to set up the 3 node test cluster. So I interrupted Homebrew during the install, copied the patched sources, did “make all rel devrel” in my own source tree, then copied the “dev/dev?” directories off. Still using the Homebrew binaries. Lot of work for 4 lousy config files :-P
The Python client you want is riak-python from Basho. Unfortunately “pip install riak” doesn’t quite work, because Pip first tries to install protobuf and there’s a three year old bug open on Google’s protobuf client about how it doesn’t install right in Python. Some helpful soul forked Google’s library and his version can be installed witih pip install “git+http://github.com/rem/python-protobuf.git@v2.4.1#egg=protobuf”
With that you have a working Riak and Python environment that you can use to work with the tutorials online.
Insert notes
Trying to insert my weather data: millions of rows of 4 tuples: (station name, timestamp, speed, direction). Testing with 3 Riak nodes running on my single fast iMac. This data is not a good match for document oriented stores: I already learned that Mongo was not good and expect Riak not to be, either. Still, it’s real data I have and I want to try it.
Wow, is Riak slow if you just use it as a naive user. 3 node cluster running on a fast iMac, inserting 45,000 records one at a time with a store() between each took 120 seconds.
Some write optimization.. there appears to be no batch insert in the Python library I’m using (although see this). Riak’s exposure of consistency via the W parameter is really neat, but what I need is to commit 10,000 records at once. I’ve tried optimizing my writes (ie: windData.store(w = 0, dw = 0, return_body = False)). Switching from HTTP to Protocol Buffers gives about a 4x increase. Still, no matter what I do, I can’t do better than 1900 records / second. Compare Mongo’s 30,000 records / second or Postgres’ 10,000 rows a second. Am I doing something terribly wrong?
Sadly, I get a 10% speed increase (from 1900 to 2100 records / second) if I only have one node in the cluster. Not useful in the real world, but interesting.
With just a single node running Riak seems to use about 1 kilobyte / document (650,000 rows, 720 megs on disk). Not good, since the docs themselves are like 20 bytes of data. Compare about 50 bytes / row for both Postgres and Mongo. With 3 nodes the combined disk usage is about the same size; I’m surprised, I thought the default config was three copies of all data.
I sure miss the ability to drop a whole bucket. I don’t really have a way to reset my database while testing.
Query Notes
Once again I petulantly note that raw map/reduce is awfully low level if you just want a damn SQL function. Of course it gets wonderful when you want to query using 100 machines and a distributed data store.
Trying to list 50,000 keys in a bucket (via /keys?keys=true) kills both Chrome and curl: they complain the HTTP header returned is too big. Also the docs warn you to never do this in production. In other words, queries over the whole dataset are difficult. I think you need to use links or some extra indexing system to do queries. Riak has a search capability, btw, but it looks more full text oriented than simple data iteration.
I wrote some simple mapreduce code to do “select count(*) from bucket” and “select count(*) from bucket where parameter > 30”. It takes 16 seconds to run over 60,000 rows, that’s just unacceptable. Also the answer it gives is wrong; 43561 instead of 59072. Huh. While it’s cool I could run this query while nodes were dropping out, it’s uncool that the answer it gave varied as data was moved around.
I don’t think I have a bug in my query code, but you never know... Here it is.
import riak
client = riak.RiakClient(port=8081, transport_class=riak.RiakPbcTransport)
# select count(*) from KSFO
query= client.add('KSFO')
query.map("function(v) { return [1] }")
query.reduce("Riak.reduceSum")
for result in query.run(): print result
query = client.add('KSFO')
query.map('''function(v) {
var data = JSON.parse(v.values[0].data);
if (data[1] > 20) {
return [1];
} else {
return [];
}}''')
query.reduce("Riak.reduceSum")
for result in query.run(): print result
Evaluation
I knew this data was a poor match for Riak and now I’m doubly sure. The 1k / row is the real problem. I don’t think Riak is bad or anything, quite the opposite. Just curious how it feels to try it out on some data.
I really admire how Riak is distributed to the core. Most datastores design for a single server, then later add replication and partitioning. It’s a total mess. Riak started distributed, and if they did it right it should be significantly more robust for real network usage. Also for parallel data analysis. I also think it’s freaking amazing how you can do “riak-admin join” and “riak-admin leave” and the data transparently repartitions while the cluster is still up and serving write requests.
I wonder how robust Riak is in recovering if a node drops offline without a clean shutdown, then joins later with inconsistent data? The docs on CAP mention some voting and validation protocols, so they’ve thought about it. More a question of convenience than usability.
I just had a terrible time trying to upgrade PostgreSQL 9.0 to 9.1. I finally gave up and am still running the old one.
pg_upgrade is the recommended upgrade path. It’s pretty ugly, and among other things requires you have the old server binaries around. But it looks like it’d do the job. I had a few minor problems, like I ran “--check” and the check failed but left something around that made Postgres think a server was running. (Fortunately pg_ctl start just ignored that and started a server anyway, then pg_ctl stop fixed it.)
Then I hit a bigger problem: PostGIS I’ve got that installed in my 9.0. I *think* it’s installed in 9.1, too, but I can’t be sure with Homebrew. In any event pg_upgrade doesn’t think it’s there so I’m SOL for now.
An alternative is to do pg_dump on the old server, then pg_restore on the new. I suspect that’s what pg_upgrade does behind the scenes anyway. And I still have to resolve my PostGIS problem.
My little database became a big database, 100 gigs, and I never bothered to tune PostgreSQL. The defaults look tuned for a machine with about 1 gig of RAM total. I’ve got 8 gigs. Here’s a quick stab at some tuning:
I’m an old MySQL guy, it’s the only relational database I’ve used a lot. So it’s been fun to learn about Postgres. It’s like a database for grownups! Constraints! Views! Transactions!
MySQL has gotten better over the years, particularly with InnoDB. But fundamentally it was designed as a fast and loose database and it shows. Does it still coerce any string to an integer on insert rather than throwing errors? I can’t tell you how many 0s corrupted my database because someone inserted “apple” into an integer column, or even better null (when the column was marked not null). Also the MySQL driver for Python has always been pretty cryptic and poorly documented. It got the job done, but it didn’t lend a lot of confidence.
The psycopg2 docs are terrific, really well thought out Python driver. I love that it supports asynchronous queries, including with various coroutine libraries. The way you can extend the cursor and connection classes is quite spiffy, too. (DictCursors and named tuples! Logging cursors!) And lots of nice caveats about using the library properly, including what resources are held by cursors and connections and the like. Docs written by someone who’s really used the library in production.
I’m told MySQL is still faster than Postgres for big data. I’ve also heard Postgres replication is error prone. Nothing’s perfect, I guess. Looking forward to finding out. Of course my #1 reason to use Postgres is PostGIS: MySQL really can’t touch Postgres for geodata, it’s not even an option.
I’m playing around with my weather data, CSV files containing things like “KSQL 1136073600 270 10”. (Station name, timestamp, wind direction, wind speed). Each row is 10 bytes of honest data and I have oh, 300 million rows.
I would like a sophisticated query language for doing aggregate stats, like “show me a histogram of directions for winds > 5kts on Tuesday mornings”. I have been hacking reports up by hand in Python by loading CSV files into lists and doing lots of dict and slices, which is just awful.
Insert
I tried Mongo first because it was new and fun, but I think its query facilities are too limited to be useful to me. More on that in a bit. But it’s sure fast for inserts: 30,000 rows a second, 47 bytes / row on disk. It’s also fun to work with a schema-free database, it always takes me 20 minutes to get a SQL create table right.
Postgres is slower on inserts, about 10,000 rows a second and 52 bytes / row. (The Postgres FAQ says there’s about 28 bytes of overhead per row.) This is with naive Python executemany() insert; a bulk CSV import would be faster.
But I don’t much care about speed, and less about scalability. This is all one off calculations I’m running by myself. And I’m not equipped to do proper benchmarking anyway.
One caveat: I’m doing all of this measurement without indices. Well, not entirely, Mongo gets a sort of implicit index because I’m storing each station in a separate collection. In the real world of course you’d want an index on station, maybe also on aspects of the timestamp.
Queries
Mongo has very limited query support. It has a basic query predicate language that’s awkward and verbose, no date and time calculations, and precious little aggregation capability like SQL’s AVERAGE() operator. You can write all your queries in Javascript to run on the server. And Mongo has a nifty mapreduce capability for big processing. Only mapreduce doesn’t actually run in parallel in a single Mongo instance, so there’s not much benefit to that computing paradigm unless you have a sharded database.
The big drawback with Mongo is a lot of code to do something that’d be a one liner in SQL. For instance, here’s getting the average wind speed at a station.
# select average(s) from KSFO
# This map reduce version is slow, about 1s on 50,000 rows. It's single threaded :-(
# http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Parallelism
# Map function: turn a document into the value (1, speed)
# The key for this map is a constant, the number 1: we're summing over the whole collection
mapFunction = bson.Code("""
function() {
emit(1, { count: 1, sum: this.s });
}""")
# Reduce function: sum up the counts and sums
# Note this can be called on its own output, so have to match types from map
reduceFunction = bson.Code("""
function(key, values) {
var result = {count: 0, sum: 0};
values.forEach(function(value) {
result.count += value.count;
result.sum += value.sum;
});
return result;
}""")
# Execute the query and grab the results. Up to us to do the average calculation.
result = coll.map_reduce(mapFunction, reduceFunction, "myresults")
total = result.find_one()["value"]["sum"]
count = result.find_one()["value"]["count"]
print "Average speed: %.1fkts (%d samples)" % ((total / count), count)
That’s a lot of code just to do an average! Code I have to test, and maintain. It’s not particularly fast, either, 1000ms.
By contrast Postgres really is just one line of code for averages select avg(speed) from winds where station = 'KPAO'. And SQL has great complex date math, stuff I’d have to write myself for Mongo. Postgres is faster on this query, too: 600ms to do the average and that’s on a full table scan of millions of rows without even an index on the station. (It goes to 5ms with the index).
Conclusion
I’m not trying to say Postgres good Mongo bad, not at all. But Mongo’s not a good match for what I’m doing. I don’t have terabytes of data I need to shard across multiple servers. I don’t need sophisticated schema agility. I don’t really need relations, either. All I really need is efficient storage and a fast, convenient query language. Postgres and SQL are pretty good at that.
I’m playing with using MongoDB to store a bunch of wind time series data for my wind map. First time trying it out. Some quick notes:
I have a bunch of data that’s 4-tuples like this:
“KSQL”, 2011-09-23 11:47:00, 200, 7
That says that at KSQL at a specific time the wind was 7kts from 200 degrees. In an ideal encoding each row would take 10 bytes. In a comfortable encoding it’ll take 20. I’ll settle for 50 bytes per row in the unindexed database. MongoDB is taking 67 bytes per object. Or more!
Sample input: KDTW and KMDS. 116,000 rows total, 2 megs of CSV, 400k of csv.gz. After import, Mono is reporting a 7.8 meg data size, or 68 bytes / object. That’s with very short element names (“d”, “s”, etc). If I use long element names (“direction”, “speed”) it balloons to 87 bytes / object. And yes, the extra 19 bytes is exactly the # of characters I added to my element name.
Lame! Apparently Mongo compresses nothing, it doesn’t even try to use a lookup table to avoid storing a zillion copies of element names? (See this user request to tokenize field names.) That seems very bizarre; not only would a simple table save space, wouldn’t it save time by making the memory working set smaller?
I don’t have any need for queries across multiple station names. So instead of having one giant table (er, “collection”) for all my data, I’m going to make one collection per station. That’ll give me some 5000 collections. I’m still at 47 bytes per row, which I said was acceptable but seems awfully wasteful. I’m beginning to wonder if MongoDB is a good match for this data. All those ObjectIds aren’t doing me any good, that’s for sure.
SVG has a bunch of properties for laying out text. Two really handy ones are “dominant-baseline” and “baseline-shift”, which together let you move text up and down a bit. “dominant-baseline: central” seems particularly useful because it lets you lay out text where 0, 0 is the middle of the text, not the baseline underneath the letters. Ie: visually center things vertically.
Unfortunately those properties don’t work in many SVG implementations. They work in Safari and Chrome, but not in Mobile Safari, IE, or Firefox.
A workaround is to use the dy parameter on the text nodes to move them around. dy: .35em is about like centering. I don’t think this works via CSS, though, only in the DOM.
I’ve added some new code to my wind history project to show winds based on month of year. With all 12 months selected the new code should produce similar results to the old code. I don’t really have any proper tests for this stuff, though, so I’m just kinda looking at the pictures and saying “yeah, looks about right”. Here’s a before and after: do the wind roses look the same to you? (Note that I moved the location of one wind rose, San Jose. That’s a bug fix).
Update: Seth was nice enough to register the images and do a difference calculation for me. Which is awesome and sad all at once :-P
I’m adding geolocation to my windhistory project. It’s a very easy API. Some quick notes based on a call to getCurrentPosition() with a few options: { maximumAge: 1000*60*60, timeout: 1000*2, enableHighAccuracy: false}
Chrome on MacOS seems to use IP address to identify what city I’m in. It puts me at 37.775/-122.419, the middle of San Francisco, whether my WiFi is on or not.
Safari on MacOS seems to require WiFi location. It won’t geolocate at all if wifi is turned off; the Javascript API returns error -2 (no position available). With WiFi on it seems to use the same airhook style location as the iPhone. It puts me at 37.749/-122.428, which is just about where I’m sitting. MacOS has privacy System Preferences for location services. The geolocation API stops working if you disable location services entirely, but it’s not necessary to have “Safari” checked in order for Safari to geolocate you. That seems like a bug, even if Safari itself is doing some privacy protection.
Firefox 6 on MacOS also seems to use WiFi location, 37.749/-122.428. Didn’t test what it did without wifi.
MSIE 9 on Windows 7, running in a VirtualBox VM on my Mac, gives me a slightly different location of 37.748/-122.416. I’ve got no idea where it got that idea, but it’s a pretty good fix. Certainly not wifi! Maybe Microsoft has a geolocation service guessing based on external IP?
Firefox 4 on Windows 7 (in the VM) puts me at 37.775/-122.419, just like Chrome.
Bottom line: Chrome seems to use an IP database, Safari and Firefox use the Mac API, and who knows what IE is doing.
Playing with my new Mac, this is my first time writing Objective C code in 15 years, and C or C++ code in nearly 10. Some quick thoughts after finishing Your First Mac Application.
Header files? In 2011? That require forward declarations of classes? Ugh.
Objective C properties are handy syntactic sugar. I have no idea what “synthesize” really does, but I like the result.
Static typing is awkward. I’m prefering dot style for properties
self.track.volume = sender.floatValue;
But if the type of “sender” is id that doesn’t work. I have to fall back to
self.track.volume = [sender floatValue]
and rely on Objective C magically not type checking method names on id. Objective C has duck typing, sorta, but not everywhere.
Manual memory management continues to suck. Apple has papered over it in various ways, with retained properties and autorelease and now ARC. But the fact that the programmer is even aware of reference counts is a serious flaw in the language. Seriously, every other OO language for 20 years has had garbage collection. Hell, even C languages have had automatic garbage collection via a conservative collector like the Boehm collector. WTF is wrong with Apple that their development language requires manual memory management?
Xcode 4.1 is a pretty solid IDE. I could drop into it with just a basic tutorial and understand most of what was going on quickly. The Interface Builder stuff so far seems OK, although we’ll see how it works with real code. I’m impressed with how one can do complex user interface constraints entirely graphically.
I created my first Macintosh application today, following Apple’s excellent docs. I didn’t write any code yet, just the default Cocoa application template. I’m always fascinated what the size of empty apps is; it often indicates how simple and clean the underlying architecture is.
I did “Build for Run” and stripped the binary. The compiled app is 44k. The binary is 14k, the NIB is 26k. It takes 10M of memory (80+M if you count shared).
Xcode created 13 files in my source directory: 14,000 lines of source totalling some 400k. Almost all of that is an XML bloated NIB file I’ll never look at as text. There’s 51 lines of ObjC code in 3 files. Pretty much all that is boilerplate; the important bits are
int main(int argc, char *argv[]) {
return NSApplicationMain(argc, (const char **)argv);
}
@interface TrackMixAppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
}
It’s certainly nicer than the 400+ lines of unmaintainable garbage that Visual Studio’s wizard generates doing a similar task. I’m optimistic that the NIB system will work out well. MacApp’s version of this was a fucking disaster in the OS 6 days, but NextStep Interface Builder was always pretty impressive.
I want to embed a part of a web page from a third party on to my web page. Easy, right, that’s what iframes are for! Only I don’t want to embed the whole foreign page, just a 200x200 pixel chunk in the middle of the page. You can crop 200x200 with the width and height parameters, but there’s no clean way to scroll to the middle of the embedded page. The simple Javascript scrollTo fails because the third party page in the iFrame does not have the same origin as the main page.
There’s a work around: doubling up on iframes. Your main page embeds an iframe to a shim page on your own server. The shim page in turn just embeds an iframe of the foreign page. The master page can scroll the shim page since they’re in the same origin. Ugly, but it works.
D3 has a notion of “scales”, transformations of data from a domain to a range. Say your data is percentages (0% to 100%) and you want to draw them as bars of length 10-20. You can easily construct a linear scale to map your domain [0,100] to a range [10,20]:
var s = d3.scale.linear.domain([0,100]).range([10,20])
d3.selectAll("rect").data(data)
.enter().append("svg:rect")
.attr("height", s)
If that use of s seems magic, equivalents would be
D3 provides various useful scales. Numeric scales like linear, log, and pow, also discrete scales like quantize and ordinal.
One thing you can set on a scale is the interpolate function. It’s invoked when mapping the domain to the range and lets you make the range be something other than the usual numeric range.
There are pre-defined interpolation functions for numbers, colours, strings, objects, etc. I believe they’re also used by D3’s transition animations, specifically to automatically warp complex things like SVG paths from one shape to another.
interpolate = d3.interpolate,
i = interpolate(y0, y1);
function scale(x) {
return i((x - x0) * kx);
}
In the linear.js code [x0,x1] is the domain, kx is 1/(x1-x0). [y0,y1] is the range. So the above code takes the input x, maps it to the interval [0,1], then applies cached interpolation function i(). By default that function is a linear interpolation in [y0,y1], but the developer can override it.
I’m trying to build node.js from source on Debian/wheezy. There’s an RPM but it’s two major versions behind. I got an error about SSL methods not being declared when compiling. No idea why Debian’s dev environment makes node’s configure think it can build SSL when it can’t (I have libssl-dev installed), but a quick workaround is buidling Node without crypto, via ./configure --without-ssl.
[74/75] cxx: src/node_crypto.cc -> build/default/src/node_crypto_4.o
/usr/bin/g++ -pthread -m32 -g -O3 -DHAVE_OPENSSL=1 -DHAVE_MONOTONIC_CLOCK=1 -DEV_FORK_ENABLE=0 -DEV_EMBED_ENABLE=0 -DEV_MULTIPLICITY=0 -DX_STACKSIZE=65536 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DEV_MULTIPLICITY=0 -DHAVE_FDATASYNC=1 -DPLATFORM="linux" -D__POSIX__=1 -Wno-unused-parameter -D_FORTIFY_SOURCE=2 -DNDEBUG -Idefault/src -I../src -Idefault/deps/libeio -I../deps/libeio -Idefault/deps/http_parser -I../deps/http_parser -Idefault/deps/v8/include -I../deps/v8/include -Idefault/deps/libev -I../deps/libev -Idefault/deps/c-ares -I../deps/c-ares -Idefault/deps/c-ares/linux-ia32 -I../deps/c-ares/linux-ia32 -Ideps/v8/include ../src/node_crypto.cc -c -o default/src/node_crypto_4.o
../src/node_crypto.cc: In static member function ‘static v8::Handle<v8::Value> node::crypto::SecureContext::Init(const v8::Arguments&)’:
../src/node_crypto.cc:101:29: error: ‘SSLv2_method’ was not declared in this scope
../src/node_crypto.cc:103:36: error: ‘SSLv2_server_method’ was not declared in this scope
../src/node_crypto.cc:105:36: error: ‘SSLv2_client_method’ was not declared in this scope
Waf: Leaving directory `/usr/local/src/node/build'
Build failed: -> task failed (err #1):
{task: cxx node_crypto.cc -> node_crypto_4.o}
make: *** [program] Error 1
Apple’s mobile browser is great, but the viewport meta tag is kind of a hash. There seems to be two conflicting ways to hint to the iPhone or iPad how big to draw things.
width and height. Tells the browser this content is going to render best at a certain width, so render it to that size. width=device-width or width=320 is one way to tell the iPhone not to scale at all. width=600 or the like often solves the problem of stuff looking too small on the iPhone, while still letting it scale. If you set a small width the iPad will scale content up, making it bigger.
initial-scale, minimum-scale, maximum-scale. Gives an explicit scaling factor. The user can override this (unless you disable it).
What’s confusing is if you set both a width and scaling behaviour: which takes precedence?
Mike suggested what seems to work well for maps is setting initial-scale to 1.0 and maximum-scale to 1.0. This keeps Safari from doing its own scaling on the page at all. Even better, when you rotate the device it doesn’t try to scale the width to match the old view; instead it just loads some stuff that was previously off-screen. The only drawback is this effectively sets the width to 320px on an iPhone, you no longer get any in-browser scaling.
What I really want is no scaling at all on the iPad, and 1.5 scaling on the iPhone. I can’t figure out a way to do that without changing the tags depending on what device loaded the page.
The core datatype in the D3 Javascript library is the selection. But what exactly is a selection? What is its type and how do we work with it? It’s possible to use D3 without really understanding what selections are, but it makes a lot more sense if you understand the core type.
D3 selection type
A D3 selection is an array of arrays of DOM elements. That top level array object also has extra methods defined on it, the D3 selection methods like append(), attr(), etc. Both select() and selectAll() return a 2d array; the difference is that select() only returns the first of the matching nodes. Most of the time your Javascript code won’t ever iterate inside these arrays; D3’s methods themselves implicitly loop over the elements.
Sample document
The rest of these notes will work on a simple sample HTML document that contains two tables each of size 2x2 for a total of 8 td nodes.
D3 selections are basically just arrays and if you look at a D3 selection in a developer tool like the Google Chrome console it only shows the array. See line 2 below. But don’t be confused! The selection doesn’t show up as having a special type or representation, but it is special. It has extra methods assigned on it and you can inspect and call them:
Where does a D3 selection object come from? The select() and selectAll() methods. Those methods return a selection matching the input parameter. Often the developer selects for strings, using the selectors we know and love from the CSS specification. Selectors are a powerful mini-language worth reviewing to get the most out of D3.
In addition to strings, select() and selectAll() also work with ordinary DOM elements returned by other Javascript APIs. This capability can also be useful inside D3: inside an iterator function like each() you can use it to elevate the DOM element passed in the this parameter back into a selection object so you can then modify it with D3 methods.
>>> document.getElementById("td1-1-1")
1-1-1
>>> d3.selectAll(document.getElementById("td1-1-1"))
[ Array[0] ]
>>> d3.selectAll("td").each(function() { this.style("font-weight", "bold") })
TypeError: Property 'style' of object is not a function
>>> d3.selectAll("td").each(function() { d3.select(this).style("font-weight", "bold") })
[ Array[8] ]
Using a D3 selection
Most of your work with D3 is getting a selection and then invoking methods on it. All selection methods except call are implicitly loops, they will operate once per element in the selection. The methods attr(), style(), property(), text(), and html() allow modification of the selected elements. each() allows you to call arbitrary functions for each element; methods like attr() are implemented by calling each(). append(), insert(), and remove() allow elements to be added to the DOM. on() allows events to be bound to the selected elements.
Subselections
D3 allows you to create a subselection within a selection, to work on a subset of elements from an initial selection. Subselections allow like elements to be grouped so you can process your data in a structured fashion. (This also explains why selections are 2d arrays; they support the nesting). I haven’t needed to use subselections yet: the scatterplot matrix example shows their use.
The data() method allows data to be stored for each element in the selection. Data is stored in a __data__ property right on the DOM node. You should normally not access this property directly, but it’s helpful to understand how D3 keeps data associated with your document elements.
Note how the array returned by each() is length 10? We bound 10 data items to the selection, but we only had 8 matching td elements. The extra two new elements implied by the data are accessible as the enter selection. This enter selection only has append() and insert() methods defined on it; you cannot call attr(), etc until you create DOM nodes. There is a symmetric exit selection that has the full D3 selection methods, typically used for removing nodes from the DOM.
Trying to understand the this magic variable in Javascript. You’d think it’d be like self or the like in most OO languages. But Javascript is barely OO and everything is so dynamic, it’s confusing. Some useful references: Quirks Mode, MDC this.
My takeaway from reading stuff is that this is generally set to the object the function is defined on. If you’re saying foo.go(), then inside go() this will be set to foo. If you don’t know what object you called a function on, say because you have a naked go() in your code, then this is probably bound to the global window object.
The usual this behaviour can be overridden in various ways. Both call and apply let you invoke a function and explicitly provide a value for this. D3’s each() function does this so that inside each, this is bound to the DOM node for the specific element being manipulated. There’s also a new ECMA function bind that lets you create a function with a new value automatically used for this.
I’m still a bit fuzzy on the mechanics of how this is assigned, in particular when you copy a function from object A to object B. In general this seems to be set dynamically at the last moment before the function is invoked, so it generally picks up the value A or B depending on how the function was invoked.
My map contains a list of 3000 weather stations. The current JSON file driving the map contains lines like “KSQL”:[-122.25,37.52,”San Carlos Airport”]. It’s 137k, or 53k gzipped. That’s 46 bytes / station, or 18 bytes/station gzipped.
I’d like to add data to this file: the probability of wind coming from each of 12 directions. Probabilities can be scaled to [0-99] so the naive text encoding (32,4,12) is 24-36 bytes. That adds 50% to my file length. I actually tried it: the file becomes 210k, 80k gzipped.
I could do a more compressed encoding, say ASCII characters from 35 to 126 for 92 distinct values in one byte with no JSON encoding challenges. That gets me to 12 bytes / station, the whole file should be 160k.
My original plan was not to ship the wind probabilities at all, but render them server-side as PNGs (see previous posts). But each PNG is about 1k compared to 12 bytes for the wind data. And while bltting a PNG ought to be faster for the browser than drawing a bunch of SVG, it may not be significantly faster. Particularly since each PNG would need to be fetched as a separate file and it’s being rendered as an svg:image anyway. Need to test.
For my wind visualization I have a bunch of 2-3 megabyte text files containing a lot of METARs. I parse them to get the winds data, then do some statistics on them to produce a rollup.
Doing all this work in one swoop takes 5.3s for a smallish file (1.5 megs, 24000 lines).
Parsing the file and writing it to CSV takes 4.6s. Reading the CSV in and doing the rollups takes 1.4s. So I’ve added about 0.7s overhead in splitting the two steps thanks to the intermediate file. OTOH I should really only need to generate that CSV once.
Once again I learned the hard way that iterating line by line through gzip.open() is really slow; way faster to read the whole file in to RAM, a cStringIO if necessary. Terrible buffering in Python’s library.
I’m beginning to regret not just loading all this crap into a relational database.
I revisted headless SVG rendering and decided to stick with PhantomJS since I already have it working. It’s rendering text poorly and path strokes not at all, probably fixable with some upgrades that are inconvenient in Debian. But I can work around that for now.
Scripting PhantomJS turns out to be pretty easy. Here’s the Javascript program I use to drive it:
Unfortunately the input and output filenames are hard-coded. Phantom has command line argument support but I can’t figure a way to get that all the way into my HTML file (to load a specific script), so I just went with a hardcoded input file named data.js.
Here’s my shell script to render a PNG, crop it, and optipng crush it. The crop shouldn’t be necessary, but for some reason I’m ending up with 3 pixels below my SVG element.
set -e
# Render a wind rose image for the given datafile
input="$1"
output="${1%.js}.png"
# remove old crap
rm -f data.js out.png cropped.png "$output"
# Symlink the data to the expected place
ln -s "$1" data.js
# Render, crop, and crush
phantomjs/bin/phantomjs render.js
convert out.png -crop 64x64+0+0 cropped.png
optipng -force -quiet -preserve -out "$output" cropped.png
# clean up
rm -f data.js out.png cropped.png
It takes about 300ms to render a single image for my simple SVG based graphics.
I’m trying to submit patches to https://github.com/mbostock/d3. Only what I want to patch is in the gh-pages branch, a special magic branch on github that is published as a website. Forking and modifying a branch is confusing if you don’t understand git. Here’s what works in my shell, after forking the repository:
# Get a copy of the forked repo
$ git clone git@github.com:NelsonMinar/d3.git
Cloning into d3...
# Link in the upstream repo you forked
$ cd d3
$ git remote add upstream https://github.com/mbostock/d3.git
$ git fetch upstream
From https://github.com/mbostock/d3
* [new branch] gh-pages -> upstream/gh-pages
* [new branch] master -> upstream/master
* [new branch] mbostock-master -> upstream/mbostock-master
# Create a local branch, somehow linked to the upstream's branch
$ git checkout -b gh-pages origin/gh-pages
Branch gh-pages set up to track remote branch gh-pages from origin.
Switched to a new branch 'gh-pages'
# Make your changes and commit them locally
$ ed README.txt
$ git commit -a -m testing
# Push to your fork on github
$ git push
To git@github.com:NelsonMinar/d3.git
0d1679a..d351228 gh-pages -> gh-pages
The magic step is that checkout line. Other similar things like git branch gh-pages; git checkout origin/gh-pages don’t work and you can end up in weird states like “You are in ‘detached HEAD’ state.” I don’t really understand what all the working command is doing (I’ve got Matt to think for the code to copypasta) but I’m hopeful after reading the git docs on branches and remotes maybe it’ll make more sense.
I’m doing an S3/SVG visualization project and want an easy way to generate 3000 static images with a script. I need a headless SVG renderer. Mike suggested a couple of options: Rhino + Env.js + Batik, or maybe using node.js instead of rhino. Apparently the Protovis community does this; need to delve in their mailing list for examples.
PhantomJS happened to float across today, so I tried it out. It’s WebKit based instead of Mozilla based. It was pretty easy to get going. I had to install libqt4-dev libqt4-webkit on my Debian system to build it. I also learned it’s not really headless, requires an X server, so I installed xvfb and ran it via “Xvfb :1”. With all that in place the basic PhantomJS works. Including rasterizer.js, which loads an arbitrary URL and renders it.
My visualization didn’t work. First I had to remove the Ajax calls from it and statically load the data. (May not be strictly necessary, not sure). Second I had to set the background to white; the default background in qt4-webkit is transparent, which is actually pretty useful. With those changes my rendering sort of worked, but the font rendering is ugly and none of my stroked lines are visible. I’m using libQtWebkit-4.6.3; apparently 4.7 may fix the stroke problem.
I think I could massage this into something usable, but I’ll probably investigate the Rhino/Batik solution or something next.
My Python IDE of choice, Wing, has a capability to start the debugger when an exception is raised, but only if it “appears unhandled”. It’s great but a little delicate. It broke entirely on my recently, all exceptions appeared unhandled. I narrowed the problem down to running in Python 2.7.1. Python 2.6 works fine. The workaround Wing recommended was setting the debugger to break when exception is printed.
In Javascript, the dictionary type coerces its keys to Strings:
z = { 3: "three", 4: "four" }
for (var x in z) { console.log(typeof x); }
string
This sort of makes sense because dictionaries are really just Javscript objects, and objects are typically accessed by strings. Ie: z.foo is the same thing as z[“foo”]. Worth noting that z.3 doesn’t work, though. It gets spookier when you use null:
z[null] = "foo"
for (var x in z){ console.log(x, typeof x); }
3 string
4 string
null string
Maybe it wasn’t wise to use integers and null everywhere as keys in my JSON dictionaries. In fact the JSON spec says keys have to be strings, and the Python JSON library was already serializing my keys as strings (with None mapped to “null”). Now I know.
IE9 is out, and Microsoft finally supports SVG. Early testing with D3, Mike’s new Javascript library good for doing visualizations, is encouraging. All his examples work. My own code worked once I put <!DOCTYPE html> at the start to convince IE not to use quirks mode.
Apache 2 on Debian does not gzip encode by default. Enabling it is as simple as doing a2enmod deflate, then restarting Apache. The default configuration is fairly conservative; if you just want to compress everything modify defalte.conf to say “SetOutputFilter DEFLATE” instead of adding a few MIME types.
Google Chrome has bug 40502 where it appears files aren’t being compressed even when they are. Serving JSON files, if they were smaller than 190k dev tools showed Transfer was much smaller than Size, indicating compression. Bigger files looked uncompressed. But checking with WireShark they were actually comprssed, dev tools just lied. Apparently Apache2 decided to use chunked encoding for the larger files and Chrome has as bug with that.
I do a lot of quick and dirty Python scripts. One thing that bites me is trying to print useful data on exceptions, where the useful data contains non-ASCII and I’m trying to write it to sys.stderr and I get an exception in my exception handler, killing my program:
try:
process(inputString)
except:
sys.stderr.writeln("Error with input %s" % inputString)
UnicodeEncodeError: 'ascii' codec can't encode character u'\x81' in position 0: ordinal not in range(128)
Very irritating. One workaround is to use Python’s logging package. It’s a hugely complex configurable beast, but the default config is useful: print all warnings and above to stderr. And it handles Unicode sensibly.
Not sure what it’s doing; maybe trying Latin-1 and escaping anything else? I don’t care if the output is mangled as long as it doesn’t kill my program.
readline() inside a Python zipfile is slow. It’s much much faster to read the whole thing into memory once, then scan.
Compare:
fp = zipfile.ZipFile("foo.zip").open("data.txt")
# Iterate a line at a time
for l in fp:
if l.startswith("FOO"): print l
# Read the whole file into memory, grep
regexp = re.compile(r'^(FOO.*)$', re.MULTILINE)
data = fp.read()
if m: print m.group(1)
I’m not surprised that the second style is faster, but I’m surprised how much. Some 25 times faster both on my test case (0.5s vs 12s) and over 3.6 gigs of real data (8 minutes vs 200 minutes). Obviously reading the whole file first takes more RAM, but in my case the files are only 500k each.
A quick profile suggests zipfile spends a lot of time calling next(); maybe it’s doing work a character at a time? Issue 7216 suggests there’s a 100 byte buffer at work; yuck! Fixed in 2.7 or 3.x or something.
I learned Python when 2.2 was the new hotness. Since then I’ve picked up a lot of newer Python features but never really sat down to think of all the new language and library capabilities the system had. Here’s a list of some highlights in the 2.x releases I picked up off the what’s new pages. 2.6 (3.0) means the feature is available in 2.6 as a backport from 3.0. 2.6f (3.0) means the feature is only in 2.6 as a __future__.
2.4: Function and method decorators. 2.6 (3.0): Class decorators
2.5: Conditional expressions (“foo” if x == 3 else “bar”)
2.5: Absolute imports (default in 3.x)
2.5: try/except/finally unified
2.5, 2.6: with statement (this one is important; need to use it more)
2.6 (3.0): except ExceptionClass as variableName:
2.6 (3.0): strings are unicode. bytes type.
2.7 (3.1): dictionary and set comprehensions
Libraries
???: codecs.open() as a way to be explicit about character encoding
2.3, 2.4: Sets. 2.7 (3.1): set literals
2.3: Universal newline mode for files
2.3: logging
2.3: CSV files
2.5: functools.partial() for closure-like partial function application
2.5: ctypes, quick access to shared libraries
2.5: ElementTree (xml.etree)
2.5: sqlite3
2.6f (3.0): str.format(). 2.7: autonumbering
2.6f (3.0): print() as a function
2.6 (3.0): abstract base classes, particularly for collections and numbers
2.6: json (via simplejson)
2.7: collections.OrderedDict
2.7: argparse
2.7 (3.1): dictionary views
2.7: collections.Counter (replaces my accumulator.py)
2.7: unittest improvements, backported to 2.4 as unittest2
Actually using some of these features is harder: Google AppEngine is stuck at 2.5 and Debian is stuck at 2.6. And of course 3.2 is the new hotness now, but largely not usable for ordinary user code.
I wanted to try to get at an image hidden inside an SWF file, a Flash game on Armor Games. Google searches for “SWF extract” and the like offer a lot of unsavoury software, but a quick search of Debian turned up SWFTools, a GPL toolchain for making and unmaking SWF files. Compiling on Linux was as easy as ./configure; make
To actually extract the images, you have to find their IDs first, then extract them one by one. The compiled SWF file doesn’t seem to keep the source filename, so you have to hunt by size or the like.
$ swfdump foo.swf | grep image
[024] 14446 DEFINEBITSLOSSLESS2 defines id 1725 image 660x561 (32 bpp)
$ swfextract -p 1725 -o 1725.png foo.swf
$ ls -lg 1725.png
-rw-r--r-- 1 nelson nelson 14877 Feb 19 14:04 1725.png
That example is for a 600x561 lossless image, 14446 bytes long, with ID 1725. I didn’t see any quick way to get swfextract to just extract all the images, although of course it’d be easy enough to write a shell script to do it.
The way Javascript scopes “var” in loops and how it interacts with closures trips me up every time I go back to writing Javascript code. Here’s a fleshed out example that shows the confusion.
// Demonstrates using closures to capture the value to do what you meant. See also
// http://calculist.blogspot.com/2005/12/gotcha-gotcha.html
// http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/
var data = ["a", "b", "c"];
var wrongFunctions = [];
var rightFunctions = [];
function load() {
console.log("Creating functions");
for (var i = 0; i < 3; i++) {
// X will be set to "a", then "b", then "c". But at what scope?
var x = data[i];
// The naive way to construction a function that returns X
// Will not work: X is scoped to the function load() and
// is being modified in the loop
var wf = function() { return x };
// A more complicated way to make a function that returns X.
// The function execution creates a closure
// that captures the value during the loop
var rf = function() {
var t = x;
return function () { return t };
}();
// While the loop is executing and we're building functions,
// the output of wf() and rf() will match data[i]. No problem!
console.log (" ", x, wf(), rf());
// output is "a a a", "b b b", "c c c". Everything looks great!
// Let's store both functions away, what could go wrong?
wrongFunctions.push(wf);
rightFunctions.push(rf);
}
}
function play() {
console.log("Running stored functions");
// Let's loop through and call our stored away functions
// and see what happens
for (var i = 0; i < 3; i++) {
console.log(" ", data[i],
wrongFunctions[i](), rightFunctions[i]());
}
// output is "a c a", "b c b", "c c c".
// wrongFunctions were indeed wrong.
}
load();
play();
It’s been a long time since I’ve written C++ code. Or C code, for that matter. Like before STL, before g++ really did templates right, before namespaces. I sort of miss the drama of C hacking, but I sure don’t miss all the stupid stuff about C.
A friend of mine wrote a brand new Minecraft map renderer, in C++. It’s really fast. But compiling it was such a mess. g++ 4.4 apparently moved some include files around, so I had to manually include stdint.h in a few places. Why? So you can get an honest-to-goodness 32 bit wide int reliably, since of course C still assumes int is some random width that happens to be the default in that version of the compiler on that kernel. Even with stdint.h included the compiler still couldn’t pick up a macro from inside it. I never could figure out why, I finally just copypastaed the macro into the code. Awesome.
Then there’s linking. What a bizarre thing to have to do with code. The nice thing about linking is you can also link -static, and get a binary that really will run pretty much on any compatible system. Java can do the equivalent reasonably well, but Python is a total nightmare for distributing portable code.
At least I haven’t seen any segmentation faults in the running code yet. Nor buffer overruns. Nor typecast problems. Ah, C, your edges are so sharp!
I do all my Javascript development in Chrome. But I never really sat down to learn about the Chrome developer tools other than learning how to open the console. Here’s some bits I learned reviewing the docs.
Ctrl-shift-C lets you inspect DOM elements with mouseover. This is the same as clicking the little magnifying glass in the tools.
In Elements, the panels on the right show the live state of the DOM, CSS, etc. Most bits are editable as well as inspectable.
In Scripts, you can set breakpoints by clicking on the line numbers.
The docs describe a cool-sounding network page that I don’t have in my Chrome/stable. May be only available in developer for now?
There’s ridiculously powerful performance tools built in. Learning it all would take hours, but quickly: go to Timeline, click the round record button, reload your page, then click record again to turn off recording. There’s a profiler too, for statistical profiles. Both seem to work better in Incognito mode so you don’t have any extensions.
The console scripting prompt has some limited support for jQuery-like DOM identification of elements.
I’ve been trying to develop code on my Windows box. It’s the machine I sit in front of, it’s fast, and I like WingIDE. I have a Linux box for “real work”, but think there’s some discipline in moving back and forth between the two systems.
For GeoDjango hacking I decided to run the PostGIS database on my Linux box and the Django webapp on my Windows box. I’d hoped this would avoid having to install a bunch of funky binaries on Windows. No such luck. The GeoDjango docs are a bit out of date and the official GeoDjango Windows installer binary is for an old version. Here’s what I’ve learned doing it myself.
The first step is getting regular Django working. Here’s what I did:
Installed PostGIS + dependencies on Debian (testing) via aptitude install postgresql-8.4-postgis
Installed stock Python2.5 on Windows from Python.org
Installed Django 1.2 on Windows. I forget how I did this, I think using easy_install, which in turn requires installation as well. It wasn’t hard, just followed the tutorial. Django 1.2 includes GeoDjango Python libraries.
GeoDjango is harder. It relies on a lot of C libraries, some of which don’t support Windows well. The main hurdle is a working GEOS DLL. The GEOS page itself doesn’t have binaries. I found binaries from three places: OSGeo4W, the GeoDjango Windows Installer, and PostGIS. Here’s a quickie test program I wrote to try them out:
geosPath = r'.\libgeos_c-1.dll'
from django.conf import settings
settings.configure(GEOS_LIBRARY_PATH=geosPath)
from django.contrib.gis.geos import tests
tests.run()
Unfortunately, both the OSGeo4W and GeoDjango versions of the DLL don’t pass the tests. Version skew? Bug? The underlying error seems to be in memory management, something like
ERROR: test02_wktwriter (django.contrib.gis.geos.tests.test_io.GEOSIOTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\Python25\lib\site-packages\django\contrib\gis\geos\tests\test_io.py", line 30, in test02_wktwriter
self.assertEqual(ref_wkt, wkt_w.write(ref))
File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\io.py", line 147, in write
return wkt_writer_write(self.ptr, geom.ptr)
File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\threadsafe.py", line 55, in __call__
return self.cfunc(*args)
File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\errcheck.py", line 87, in check_string
free(result)
WindowsError: exception: access violation reading 0x02F12494
The library that did work for me was the version that came with PostGIS. I didn’t even install PostGIS, just grabbed the DLLs out of their zipfile. Unfortunately GEOS is spread into two files: libgeos_c-1.dll and libgeos-3-2-2.dll. The latter needs to be in a directory where Windows can find it as a normal DLL, I put it in the working directory of my own code.
GEOS was enough for me to get the tests working and my simple GeoDjango program working correctly. There’s more work to be done: I believe you want both GDAL and PROJ.4 available to GeoDjango on the Windows side. Or does PostGIS do the work on the database server? I haven’t tested that yet.
In addition to basic GeoDjango on Windows setup, here’s notes specific to my code:
Sweated a lot over environment considerations, specifically Python path. I hate setting up new development environments, and Django with its mix of servers and applications and developer code and third party libraries is complicated.
I’m trying to run a script directly, not via manage.py. To make that work you need to set the DJANGO_SETTINGS_MODULE system environment variable to point to the Python path of your settings.py
settings.py needs to specify a special database engine:
‘ENGINE’: ‘django.contrib.gis.db.backends.postgis’
There’s some more useful notes about Windows and GeoDjango in this blog post by Reinout van Rees.
I’m new to Javascript hackery, my little aviation weather hack had me doing a lot of new stuff with Ajax and dynamic HTML. So I asked my friend Mike for a code review. He’s the smartest Javascript hacker I know, and we both worked at Google where rigorous code reviews were a thing.
Here’s some complicated things I learned from him:
There’s ways to create private namespaces for libraries and classes. Douglas Crockford’s “Private Members in JavaScript” is a good introduction, some examples from Mike are kmeans.js and crimespotting.js. The key thing is creating a closure to scope the private stuff, then assigning the public functions to a module object. There’s potential per-instance overhead to doing it this way.
Reassigning the CSS class of a DOM element at runtime is totally OK. In jQuery, it’s like doing foo.attr("class", "someStyle"). It’s a handy way to make the document suddenly look different, but it made me nervous.
Editing the CSS style of a DOM element is also OK. In jQuery, it’s doing foo.css("font-weight", "bold"). Presumably it’s using element.style.setProperty() to do the manipulation.
jQuery.ajax() gives different types types depending on what it thinks the response is. XML gives back a DOM object, HTML gives back a string, JSON gives back a Javascript blob. My code is getting HTML and then uses the magic jQuery(htmlString) capability to parse the HTML into a DOM and then query it. (BTW, turning strings into DOM is not easy in Javascript.)
Also some simple things:
Javascript has Array.join() just like Python. Handy to avoid lots of String concatenation.
Not clear that testing if (foo === 3) is worth typing the extra =. There’s circumstances where it saves you, but in practice may not be a big deal.
Array.push() can take multiple arguments, to avoid repeated calls
return "" + x is an easy way to ensure the return type is always a string
Be sure to use “var” for all local variables. This is rookie Javascript, but I still forget.
I learned a lot. Code reviews are a great way to teach and learn, it’d be nice to have an online community that offered them along the lines of StackOverflow or github. Both for basic education, but also helping clean up important open source libraries. Key tech piece: a really good browser based code annotation tool.
Now as a favour in kind I’m going to try porting my code from using jQuery to using his D3 library. D3 is more of a visualization library than a jQuery replacement, but it happens to have the selectors and Ajax support I need.
Inspired by my playing with Chrome Web Apps, I sat down and read up on two of the ways HTML 5 allows Javascript to use local storage.
Offline Web Applications let you build webapps that work even when the user has no network connection. The key thing is you create a “cache manifest” file which contains a list of the files that should be cached locally. If the user is offline (or if the site is down?) then the browser will use the cached version. There’s complicated extra stuff for fallbacks and wildcards that allow for webapps to opportunistically cache just the stuff the user saw for some other reason. And there’s DOM events to let the webapp know what’s going on with caching and network status.
Local Storage is a variety of technologies for a webapp to read and write data on the local hard drive. The main new one is the localStorage object, a persistent Array. Basically a key:value store with String being the only datatype. Apps get 5 megabytes of local store. There’s also some work being done on SQL and object databases, but nothing finished yet. Miraculously, local storage seems to work in every browser, even IE 8 and above.
About once a month someone links to my blog and I get all excited to see how many clicks they drove. Despite 10+ years of Javascript tracking systems like Google Analytics, I still don’t have a proper tool to just quickly show me “what’s driving traffic today?”. I usually cobble together some hideous thing that starts awk { print $7, $11 } | grep -v ... and then get annoyed. So today I wrote a proper Python script:
#!/usr/bin/python
import itertools, re
skipRE = re.compile(r'(js|png|gif|jpg|css|rss091|atom|ico)$')
def skip(url, referer):
return skipRE.search(url) is not None or \
referer == '-' or \
referer.startswith('http://www.somebits.com')
for l in itertools.chain(file("/var/log/apache2/access.log.1"), file("/var/log/apache2/access.log")):
d = l.split()
url = d[6]
referer = d[10].strip('"')
if not skip(url, referer):
print url, referer
The output is then piped through a Python script I wrote years ago which counts up the most common lines.
One remaining mystery; the large majority of my pageviews have a referer of -, or empty. I know folks aren’t pasting URLs in by hand, where does this come from? Do redirectors somehow clear Referer?
Yesterday’s hack was finishing up AvWx, a quick Javascript thing I wrote to show me forecast data useful for flight planning. It’s an iPhone friendly web page that shows forecast maps for the next 3 days at 1800Z. 3 images for general weather (from Wunderground) and 3 images for winds (from ADDS). This is the quick and dirty data I look at when planning a multiday cross-country flight.
Like many of my recent hacks most of the work is done client side, in Javascript. Unfortunately I had to have a server-side CGI to work around the stupid same origin policy. There’s a couple of new-to-me Javascript tricks in there.
One is I’m using jQuery and AJAX to fetch a form off of ADDS and parse it to extract the filenames for the wind maps. The image naming was complicated enough it was better just to use the HTML. I’d done AJAX stuff before but always with XML or JSON data, never HTML. It’s not so bad:
$(data).find('option[value^="ruc"],option[value^=eta]').each(
function(i, e) {
var timeString = $(e).text();
var filename = $(e).attr("value");
r[timeString] = filename;
});
The other trick I did was scaling and cropping the wind images client-side. ADDS returns a 680x680 image but I want to scale it to 640 wide, then slice about 450 pixels out of the middle of it to display. I did this with the “CSS background cropping” technique; basically you create an empty div and set its background image property to your image, then use CSS to position, scale, and crop. Total hack, but it looks good in Chrome and the iPhone.
There was more work involved, but that’s the nut of it. I ended up writing a pretty comprehensive QUnit test suite for the parsing and filename munging. Felt like overkill, but already has paid off in letting me test and improve the code.