Some Bits: Nelson's log

86 posts in 2017

Duplicati remote backup notes

Some notes on Duplicati for remote Linux backups. Primary opinion: seems reasonable, needs better docs.

I need a new remote backup solution for my home Linux box now that CrashPlan is truly closing up. In the past I hacked up a a remote rsnapshot option but I wanted something more user friendly. From the Hacker News discussion it seems Duplicati is the consensus choice. The other option I should explore is rsync.net.

I was backing up about 50GB of stuff on CrashPlan. At Amazon pricing that’d be about $1.30 / month. rsync.net would be $4.00/month. I can probably do this for free now on a server I have lying around in a datacenter. The fact the blocks are encrypted makes this all much more reassuring.

Installing

Duplicati runs as a systemd service. It has a web GUI listening on port 8200 and some sort of schedule thing where it runs every few hours. It stores backups in some Duplicati-specific database in encrypted 50MB chunks. The nice thing about Duplicati is it can store those data chunks on a variety of offsite backends, including any FTP, SSH, WebDAV, or S3-like service. Also support for specific services like AWS, Dropbox, etc.

Installing was kind of awkward: I followed the instructions for this headless install since the Debian/Ubuntu package they provide apparently requires an X environment. Even so I still had to install Mono, which is an awful lot of packages. Looks like the thing is written in C#.

Configuring seemed simple. I’m starting with just backing up my source code to local disk. I have a convention of putting some files in “nobackup” directories if they are huge downloads I don’t want to back up. I added a filter for that, “-*/nobackup/”. There’s also a default set of Linux filters which seems to be about not backing up any system files. Including stuff like /etc which honestly, you probably want backed up. But it seems reasonable for backing up home directories. Half-tempted to not back up my virtual environments for Python; I’ve got a bunch of 500MB monstrosities. But then it’s a PITA to rebuild them and it’s safer to just back up everything.

I made one config mistake which was to enable throttling of bandwidth. This applies even to local disk backups. I do want to throttle for network backups eventually.

Running

Anyway, set it all up and started it running. Seems to be doing something, judging by the 100% CPU usage of the mono-sgen process running Duplicati. The docs mention everything being compressed so I guess that’s where the CPU is going.

I tested this with about 19 gigabytes of files, 9 gig to be excluded by the nobackup filter. First run took 30 minutes. Duplicati said it was 9 gig to backup and 5 gig stored, which seems about right.

Second run with basically no changes took 1 minute. Backup directory expanded by about 5 MB.

A restore of a 770MB directory took less than a minute. It restored everything right, including timestamps and file permissions.

Remote backup

The local disk test went so well I went ahead and set up an ssh remote backup to a Linux server I own. I created a new user on that system, the configured Duplicati to back up to that host with a saved username / password. (There’s an option for ssh keys too). That’s about all I had to do, it’s just backing up as I speak. I did set up a network throttle at 400 KBytes/second. That seems to be consuming 3.46Mbits/ssecond, so there’s 260kbps in overhead. Probably TCP. CPU usage on the backup process is mostly about 3% when running throttled like this, with brief bursts of 100% activity. A second backup and a restore both worked fine.

Opinions

I like the product! It works well and simply. It could probably replace what I use rsnapshot for as well as my remote backups.

The documentation for the project is pretty poor, with stuff spread out over a few articles, wiki pages, and forum postings (!). Par for the course for free software. Also kind of a slow development process, it’s been 2 years+ for the 2.0 and it’s only sort of in beta now. OTOH it all seems to work, and is free, so I shouldn’t be complaining.

I’m a little nervous about my backups being in some unknown database format. OTOH the code is open source, absolute worst case presumably some nerd could figure out how to solve any problem.

 

Blu-Ray to x265

I am super excited about the Vinegar Syndrome re-release of Liquid Sky. One of my favorite movies from the 80s, most of us watched it on crappy 3rd generation VHS tapes or if we were lucky, a low quality DVD. Vinegar Syndrome remastered it and put out a beautiful Blu-Ray with gorgeous color and lots of extra features. Only problem: it’s a disc. Who can play discs these days? So I ripped it. (For myself only, I respect Vinegar Syndrome far too much to give out copies.)

Pasted image at 2017_12_12 02_36 PM.png

Blu-Ray discs are encrypted so most computer tools can’t read them. But MakeMKV can. It’s a straight up rip; it copies all the tracks off of the Blu-Ray and puts them in MKV containers on your hard drive. No re-encoding so the 2 hour movie is like 29 GB.

Re-encoding it to a smaller file is easy. Handbrake will do the job fine but for some reason was running slowly for me, so I used ffmpeg instead. Here’s the command:

ffmpeg -hwaccel auto -i title00.mkv
-map 0:v -c:v libx265 -crf 26 -preset slow -tune grain
-map 0:a:0 -c:a:0 aac
-map 0:a:1 -c:a:1 copy
-map 0:s:0 -c:s copy
ls.mkv

I’m doing this the complicated way with -map options so I can pick and choose audio tracks. Track 0 is the main audio, track 1 is director’s commentary. There’s also a track 2 which is the sound without dialog, but I decided not to include it. Just the one video track of course, and one subtitle track.

I transcoded the main audio. The source is in 768kbps DTS, overkill particularly since the audio is mono (as the original film was). So I’m re-encoding it to AAC. I have no idea what bitrate that was going to give me. The result is about 150kbps which seems reasonable, if generous.

I also transcoded the video to H.265, the result is about 3300kbps for 1920x1080. crf 26 is higher quality than the default crf 28. Preset slow trades off CPU time for higher quality / smaller video. And “tune grain” tweaks the encoder to try to preserve film grain, something abundantly visible in the source disc.

I wanted to transcode the subtitles to SRT but that didn’t work for me, ffmpeg threw an error.

The metadata mostly came through but then some of it is wrong; bitrates and stuff were copied from the Blu-Ray. Chapter marks did come through from the original source.

All told it took about 18 hours or about 0.1x real time speed. That slow preset really makes it slower, something like 4x slower.

Hardware accelerated ffmpeg transcoding

Since I have a Linux VM with a big GPU lying around I thought I’d take a quick stab at hardware accelerated video transcoding using ffmpeg. Quick results:

  • software decode, h264 software encode: 0.355x real time
  • software decode, h264_nvenc hardware encode: 2.7x real time
  • cuvid hardware decode, h264_nvenc hardware encode: 2.8x real time

So the hardware h264 encoder is about 7x faster than software. Hardware decoding is nice but not a huge improvement.

This is all on a 1 vCPU, K80 Google Compute server. Crappy little CPU and big beefy GPU. Normal desktop machines probably have less of a spread in results.

I really wanted to test this with H265 encoding, but the hevc_nvenc encoder does not work with the Kepler-class K80 hardware. I’m regularly doing H264 -> H265 transcoding at home now and on my i7-2600 it transcodes 720p video at just about real time.

Between the video transcoding and the machine learning I’m itching to own my own Linux box with a GPU in it. I could add a GPU to the existing server but it seems to be $200 minimum. The old server is 6 years old, maybe it’s time for a full hardware upgrade. Go for SSDs. Ubuntu 17.10 while I’m at it; these LTS releases are reliable but limiting.

I wonder if there’s a way to use the on-chip Intel GPU more? Probably not worth the hassle.

 

Leela Zero, GPU machine learning on Google Cloud

I’ve been excited about the Leela Zero project that’s doing machine learning with volunteered computers for the game Go. I’ve been running it on my Windows box for a few days but wanted to try running it on Linux.  So I leased a Google Compute server with a GPU.

End result is costs about $0.10 / training game on Google Compute. It might be possible to improve this by a factor of ... 4? 10? ... by picking a better hardware type and tuning parameters. My Windows desktop machine with beefier hardware is using about $0.01 / game in electricity. AlphaGoZero trained itself in under 5M games. If Leela Zero does as well it’d cost well under $1M to train it up to superhuman strength. Details vary significantly though; Leela Zero is so far not learning as fast. And the time to play a game will go up as the network learns the game.

Here are my detailed notes. This is my first time setting up Google Cloud from scratch, and my first time doing GPU computation in Linux, so all is new to me. Nonetheless I got Leela Zero up and running in under an hour. One caveat: Google Cloud gives new users a $300 free trial. But you cannot apply that balance to a GPU machine. The cheapest GPU machines are about $0.50/hour.

Update: someone on Reddit notes you can get similar machines from Amazon EC2 at a $0.23/hour spot price. They have more CPU too, so maybe it gets down to $0.03/game?

 

Setting up a Google Cloud machine

The only subtle part of this is configuring a machine with a GPU.

  1. Create Google Cloud Account. Attach a credit card.
  2. Create a new Project
  3. Add SSH keys to the project
  4. Create a server
    Compute Engine > VM instances
    Create an instance. Choose OS (Ubuntu 17.10) and add a GPU. GPUs are only available in a few zones.
  5. I picked a K80, the cheap one; $0.484 / hour. The P100 is 3x the price.
  6. Got an error “Quota ‘NVIDIA_K80_GPUS’ exceeded. Limit: 0.0 in region us-west1.”
  7. Upgrade my account past the free trial.
  8. Try again, get same error
  9. Go to quota page. Find the “Edit Quotas” button. Request a single K80 GPU for us-west1. Have to provide a phone number. This seems to be a manual request that requires human approval, but it was approved in just a minute or two.
  10. Try a third time to set up a machine. Wish that my template machine had been saved. Works!
  11. Log in to the machine via IP address. It’s provisioned super fast, like 1 minutes. Ubuntu had already been updated.

Setting up GPU drivers

Mostly just installing a bunch of Linux packages.

  1. Try seeing if I can do GPU stuff already
    # apt install clinfo; clinfo
    Number of platforms 0
    Nope!
  2. Figure out what hardware I have
    # lspci | grep -i nvidia
    00:04.0 3D controller: NVIDIA Corporation GK210GL [Tesla K80] (rev a1)
    This is a late-2014 $5000 GPU. Retails for $2500 now. It’s got 24GB of VRAM in it compared to gamer cards’ 6GB or so. It’s really two GPUs in one package, but I think I’m only allowed to use one? Probing shows 12GB of GPU memory available to me.
  3. Follow the instructions for installing drivers from Google.
    This boils down to installing the cuda-8-0 package from an NVIDIA repo. It installs a lot of crap, including Java and a full X11 environment. It took 6 minutes and my install image at the end is about 6.2B.
    Note there are many other ways to install CUDA and OpenCL, I’m trusting the Google one. Also there’s a cuda-9-0 out now but I am following the guide instead.
  4. Enable persistence mode on the GPU. I have no idea what this means; isn’t it delightfully arcane?
    # nvidia-smi -pm 1
    Enabled persistence mode for GPU 00000000:00:04.0.
  5. Verify we now have GPUs
    # clinfo
    clinfo: /usr/local/cuda-8.0/targets/x86_64-linux/lib/libOpenCL.so.1: no version information available (required by clinfo)
    Number of platforms 1
    Platform Name NVIDIA CUDA
    Platform Vendor NVIDIA Corporation
    Platform Version OpenCL 1.2 CUDA 9.0.194
    ...
  6. Further optimize the GPU settings based on Google docs.
    # sudo nvidia-smi -ac 2505,875
    Applications clocks set to “(MEM 2505, SM 875)” for GPU 00000000:00:04.0
    All done.
    # nvidia-smi --auto-boost-default=DISABLED
    All done.

Compiling and running Leela Zero

Mostly just following these instructions and these instructions

  1. Install a bunch of libraries. Took about a minute, 500 MB.
  2. Compile leelaz.
  3. Run leelaz. It shows you an empty Go board.
  4. At this point you’re supposed to hook up a fancy graphical Go client. But screw that, we’re hacking.
    play black D3
    genmove white
    genmove black
    Here’s a sample output from one move
  5. Compile autogtp
  6. Copy the leelaz binary into the autogtp directory
  7. Run autogtp. Here’s a sample output

Performance

I didn’t benchmark carefully but I put this here because it’s most likely to be of general interest. Run times are highly variable; my first game on Google Cloud took 720 seconds for 270 moves, my second game lasted 512 moves (!) and took 1028 seconds. So comparing time / game for just a few games is not useful. Perhaps the ms/move numbers are comparable or at least useful for finding optimal work settings, but even they seem highly variable in ways I can’t understand. Benchmarking this for real would take a more serious effort.

  • Google Compute. 1 vCPU, K80 CPU.
    1 thread: 63% GPU utilization, 800 seconds / game, 2650 ms / move
    2 threads: 69% GPU utilization, 1200 s/game, 2500 ms/move.
    4 threads: 80% GPU utilization, 1113 s/game, 2110 ms/move
    10 threads: 57% GPU utilization, ?
  • Windows desktop. i7-7700K (4 cores), GTX 1080 GPU
    1 thread: 612 s/game, 1700 ms/move, 30% GPU
    2 thread: 389 s/game, 1120 ms/move
    3 threads: 260 s/game, 740 ms / move. 70% GPU
    4 threads: 286 s/game, 701 ms / move. 84% GPU
    5 threads: 291 s/game, 750 ms / move
    8 threads: 400 s/game, 740 ms / move, 80% GPU

Bottom line, I’d say the Google Compute systems are roughly 800 seconds / game, or 5 games an hour. That pencils out to about $0.10 a game. My Windows box with better hardware is about 3-4 times faster. I’m guessing it uses about 200W (didn’t measure), which is about $0.08 / hour or < $0.01 / game in electricity costs.

I’m confused about the performance numbers. I think those are normalized by number of simultaneous games (the -g parameter), so lower numbers are always better. The seconds/game number is highly volatile though since game length varies so much. I guess the ms/move parameter goes down on the Linux box with more threads because we use more of the GPU? But why not the same pattern on Windows? FWIW the program author has noted Windows performance is not great.

Leelaz seems to only use 63MiB of GPU memory, so a very low RAM graphics card is probably fine.

One last thing: I’ve been running the Windows .exe binary under Windows Services for Linux. 4 threads in this environment is 710 ms / move. 4 threads in a DOS window is 777 ms / move. Not sure it’s significant, but seemed worth noting.

 

soup-to-nuts Jupyter notebook project

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.

Some notes:

  • IPython has a thing where if an output cell is too tall it will make it smaller with an internal scrollbar. You can adjust that size with some simple Javascript.
  • 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.

simple database exploration

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.

 

Python shelve: db type could not be determined

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).

Some IndexedDB notes

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.

 

gzthermal compression visualization

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!

gzthermal.now.sh

Javascript Promises wot I learned

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");

Ubiquiti EdgeMAX EdgeOS router notes

I’m setting up a new Ubiquiti router, an EdgeRouter X SFP using firmware v1.9.7+hotfix.4. Some notes on doing this:

Out of the box the router only works on ethernet port 0 (eth0). It does not run DHCP. You have to manually configure a computer to talk to it on 192.168.1.1.

The router will redirect you to HTTPS when you connect. However they of course don’t have an SSL certificate for 192.168.1.1 so your browser will refuse to connect. You can override this in Chrome and Firefox by looking for “Advanced” mode on the error screen.

The first thing to do with a new Ubiquiti router is upgrade the firmware. The stock firmware is old and missing important features. (My memory is upgrading UniFi access points is also necessary, the shipping version had a crippling bug.)

Once you flash it the first thing to do is run the “Basic Setup” Wizard. (Note, this is not available in the shipping firmware.) This will set the router up to do What You Expect from a consumer router; NAT routing for eth0 (the WAN port) and DHCP for the rest. For a simple home network that is probably all you need to do.

1.9.7 and other versions have a bug where if you manually configure some static IP addresses along with DHCP, then dhcpd won’t start when you reboot the router. The fix for this is to remove all static entries. I was able to add one static entry later via the DHCP control panel and rebooting still works. Not sure if I can manually add an entry or not. This is all probably a bug in vyatta, their GUI config system.

DNS is not enabled for DHCP entries or static hosts. That’s a thing the dnsmasq used by many routers does for you. I can’t figure out how hard this would be to enable. The obvious wizard reportedly only adds your entries to /etc/hosts on the router itself which is not propagated by its DNS server. I didn’t try very hard.

UPnP is not enabled by default. You can add it via a feature wizard; internal is “switch0” and external is “eth0” (or whatever your WAN port is).

For my own notes, a network setup idiosyncratic to me, I added a static interface route to 192.168.1.0/24 going out eth0. Hoping to reach my invisible wireless ethernet bridge boxes on 192.168.1.110 and .111. No luck, but I think that may be because they’re configured to think the network is 192.168.0.0/23 and so can’t talk to my 192.168.3.* addresses. Oops.

 

Strava’s new heatmap, some observations

Strava just published a new map of all their data. 3 trillion GPS points turned into a heatmap. It’s lovely.

Pasted image at 2017_11_02 08_32 AM.png

They wrote a fantastic writeup of how they made the map. All custom software. It’s not really a “heat map” in the sense I use the term, in that it lacks heat diffusion that leads to blobbiness of a true heat map. It’s more of a spatial histogram. That’s just a quibble, but it helps me keep this visualization straight from the new Mapbox JS GL heatmaps I’m playing with.

The smartest thing they do is adaptive normalization of the colormap to spatially local data. They describe it in detail with the CDFs they calculate. Basically bright yellow indicates the highest number for a local region near where you’re looking now, not an absolute number for the highest value in the whole world. This allows seldom-visited areas to still have compelling and readable visualizations. You can see this in effect if you zoom in to Alcatraz which has relatively few visits; the brightness changes radically from z=15 to z=16. A trick worth stealing.

I was also struck at how all the tracks look nicely snapped to roads. Mobile phone locations are never that accurate. And they deliberately fuzz all points by 2 meters, why are the roads so sharply defined? I think they simply have enough points that the average that comes through visually really is the actual road. Neat! You can see this in a hyper-zoom on the Golden Gate bridge where you can see faint traces of tracks off the bridge, but the main bridge path is highlighted. Note also the little bump, that’s where you have to walk about 2m to the outside to avoid the tower. (I believe the two tone-line is because this is walking data, pedestrians tend to walk the east side.)

Pasted image at 2017_11_02 08_33 AM.png

 

Google Cloud Postgres connections

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.)

  1. Download cloud_sql_proxy to my dev box
  2. 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.
  3. Authorize my home IP address to connect to the SQL instance via the cloud console.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.

simpler database access in Python

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.

I really like Python 3.6 format strings

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 used to do this kind of thing a lot:

print ("{date} {asin} {title}".format(**locals()))

That’s gross for several reasons. Now I can just do

print(f"{date} {asin} {title}")

and be done with it.

GeoAlchemy and SQLAlchemy thoughts

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.

 

Firefox Quantum

I’m trying Mozilla’s new web browser, Firefox Quantum (aka Firefox 57). It’s in beta now, will be the primary Firefox release in a few weeks.

There’s a lot going on with this release but the primary feature is speed. It is super snappy and responsive. From simple tricks like taking UI actions faster in response to input, to deep things like a brand new CSS engine (in Rust) and a new process model. Firefox had been single process up to now, unlike Chrome. Now it’s multi-process but still using threads in a performance / resource usage tradeoff. Uses less memory too although since I never keep many tabs open that’s less of a problem for me.

One drawback of the new release is old Firefox extensions no longer work; developers have to make significant changes for the new process model. Most of the Chrome extensions I care about also have Firefox versions that have already been updated. uBlock Origin, LastPass (a beta), Imagus, Pinboard+.

Been awhile since I used Firefox. It’s still good. Some customizations that helped me:

  • Disable Ctrl-Mousewheel zooming by going to about:config and setting mousewheel.with_control.action;0
  • Customize the layout by enabling “Drag Space” so you have a few pixels of window frame above the tabs.

python 3.6 on Ubuntu 16.04 LTS

I want to use python 3.6 on my Ubuntu 16.04 LTS box; they only have python3.5. It’s pretty simple following these instructions but here’s the details.

Step 1: install python 3.6 from Jonathon Fernyhough’s PPA.

add-apt-repository ppa:jonathonf/python-3.6
apt-get update
apt-get install python3.6 python3.6-venv python3.6-dev

Step 2: set up a 3.6 venv

python3.6 -m venv venv
source venv/bin/activate
pip install -U setuptools pip
python -V

Now when you activate venv, you’ll automatically get python 3.6 in that environment.

In addition to the jonathonf PPAs there’s also the deadsnakes PPA which has old versions of Python as well as new ones.

Leaflet heatmap options considered

I mentioned wanting a heatmap for some geographic data. Leaflet has a variety of heatmap plugins, I spent a couple of hours looking at them.

First, a word about heatmaps. A true heatmap has a feature where if you keep adding points (“heat”) to a spot, that heat diffuses and spreads out. In theory you could cover the whole world in hot red just adding to a single lat/lon because the heat diffuses (unless you have cooling/decay enabled). I want this feature. Calculating diffusion like this is complicated and slow. So most “heatmaps” cheat and instead of running a diffusion algorithm just draw blurry transparent dots. When they overlap it looks a lot like a heatmap, but you never get the full diffusion. It’s a reasonable compromise for a lot of applications (and way faster, particularly since it’s GPU-friendly) but it’s a compromise I’m hoping to avoid. See also this technical discussion.

Another key thing is how map zooming is handled. The heat blobs are really rendered in terms of pixels, not meters or geographic degrees, so the heatmap picture needs to be re-rendered at every zoom level. Some of the libraries look like they just render one image and raster scale it to match the zoom. The behavior I want is visible in this demo: notice how the blobs get more detailed when you zoom in.

Anyway, here’s my quick review of the 7 plugins:

  • Leaflet.heat; first one I’ve used. Canvas based, seems to work for 20,000 points no problem. Not a true heatmap, just fuzzy circles, but it looks good. Last update a year ago.
  • heatmap.js: canvas based, I think a true heatmap. Demo doesn’t recalculate on zoom the way I want and I don’t think there’s code for doing it. The library is mostly used for rendering user attention on web pages.
  • webgl-heatmap-leaflet. I gotta think WebGL is a good idea. New code, mostly 3 months old. Unfortunately it doesn’t seem to have the zooming behavior I want. There’s some scaling code (units and size option) but that seems to be about projecting circles of a consistent size at different latitudes.
  • Leaflet-solr-heatmap, see examples here. It’s pretty impressive being able to handle 10M points but the grid display isn’t what I’m looking for.
  • leaflet-div-heatmap is clever for using CSS and divs. No live demo I could find though, and no commits in 4 years, so I stopped looking.
  • MaskCanvas: not a heatmap, more of a “reveal the map” display. It’s neat though! Last real update was 2 years ago.
  • HeatCanvas: true heatmap, a bit too oriented towards static images. Not sure if it works well in zooming. Last real update was 4 years ago, I didn’t look further.

In summary: Leaflet.heat is the one I want. It’s the only library that recalculates on zoom. The downside is it’s not a true heatmap. I think that actually matters for my application (I expect a lot of dwell time in one place) but it’s a compromise I can accept.

Worth keeping an eye on mourner’s WebGL work for mapbox.js too; I’d rather just use vanilla Leaflet though. But his demo looks great.

Heatmaps for geopoints?

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.

map2.png

Razer Blade 2017 opinions

I bought a laptop for my trip to Germany. Difficulty level: ultrabook, but able to play Windows games. Turns out you don’t have a lot of options. I ended up with a 2017 Razer Blade. Some thoughts:

It’s accomplished its goal, I like the machine. In ordinary use it’s a quiet nice laptop. Good keyboard, nice screen, and it’s silent. Light 2d games (Necrosphere, Heat Signature) also run silently on the Intel GPU. When I engage a demanding game (XCOM 2 mostly these days) the NVidia GPU kicks in and soon after, the giant ridiculous loud fans.

The fan noise is really awful. Like don’t make a phone call in the same room awful. it seems to mostly be turbulence sucking air in from the 1/8″ gap under the laptop. But with earplug-style headphones and in a different room from other humans it’s OK. Heat is acceptable. This is the compromise one has to live with putting a GPU this big in a laptop. I kinda wish I could have bought a lower power / cooler GPU. Or maybe figure out a way to underclock this one. Games autodetect highest settings and when i turned them down it’s a bit quieter.

My main complaint as a sorta-Ultrabook is the weight. 4 lbs is noticeably heavier than my old 3 lb Macbook Air. But then the machine is much more powerful, too. I also wish the screen didn’t have such an enormous bezel. I think most laptops are now sized to the panel, but I suspect this Razer machine is sized to something else and they picked the biggest panel that’d fit and it’ about an inch shy. The speakers in the machine aren’t great either, another unappreciated thing Apple does.

But pretty much this Razer Blade is a nice machine. I think I chose right. I continue to wish someone made a true ultrabook with just a slightly nicer GPU in it than stock. At this rate Intel’s gonna catch up before that happens.

MQTT, OwnTracks, and location tracking

I want a passive location tracker on my phone, something to tell me where I’ve been over the span of years. Google Timeline + Android does this pretty nicely and this blog also has previous notes on Fog of War and other gamified apps. I was using OpenPaths on my iPhone to do something similar, but it was abandoned. The backing server is already gone and the app will die with iOS 11.

So what to do? A friend suggested OwnTracks, an iOS tracker. This isn’t civilian software; there’s no public service. The docs are all about running your own custom server to collect your location data. But the iOS tracker is capable. In particular you can choose battery vs. accuracy. You can either record your position every N seconds / every M meters, which takes about 10% of your battery an hour. Or you can use a more passive “significant movement” mode that is less sensitive but uses very little battery, maybe 1% an hour. I think that’s what OpenPaths did; I ran it for years without a problem. (There’s also a newer iOS API for “Visits” that also looks useful).

OwnTracks publishes data via MQTT, a message queue protocol designed for Internet of Things apps. It seems awfully complicated and a bit fusty, but if they’ve thought through reliable, low power connections for limited devices I’m glad to use it. The OwnTracks docs have some info on running your own MQTT server but that seemed complicated, so I’ve started with CloudMQTT which has a nice free level.

I created a CloudMQTT account and then just plugged in the Instance Info username/password into OwnTracks and set it to logging. CloudMQTT has a “Websocket UI” that shows you the message stream to verify the plumbing is working. OwnTracks reports look like this:

{
"batt":98,
"lon":13.41240532107618,
"acc":1414,
"vac":10,
"lat":52.53526024421524,
"t":"t",
"_cp":true,
"conn":"m",
"tst":1505981237,
"alt":53,
"_type":"location",
"tid":"fi"
}

So that all works. Now what about capturing that data for myself? After some false starts I ended up at paho-mqtt, a Python client. The example client on that page more or less works, except you have to modify the on_connect() function to take a fourth flags parameter. (That’s a hint this code is musty.) The example connects to some public MQTT endpoint with a bunch of events flying by so you know it worked. Eventually one sent non-UTF8 and broke the Python code, but at least it was working.

Last step was to reconfigure the sample client to connect to my CloudMQTT instance. To get that working I had to create a new user and set it up with the ACL controls. (Wildcard access, read/write). For some reason the main user/login didn’t work; maybe because it was in use by OwnTracks? I also had to call client.subscribe() to get messages on my specific OwnTracks topic; not sure if that is supposed to be necessary.

Cloud MQTT also has support for forwarding events to Amazon Kinesis. I set this up hoping it was an easy way to get at the data but it just adds complexity and another system for me right now. There’s probably some way to feed the data into a database with AWS plumbing that might be nice. And it’ll scale!

Things to learn more about with MQTT:

  • Is MQTT a living tech, or is it abandoned?
  • CloudMQTT user management
  • paho.mqtt: naked TCP vs TLS vs Websockets
  • MQTT topics and subscriptions
  • Is Amazon Kinesis interesting for my application? Would be nice to have less code + servers to manage

 

Berlin home Internet link

More details on my Berlin Internet sitch. My apartment has a Technicolor router that comes from PrimaCom’s cable modem service. It was down entirely for several days (and not just for me) when we got here, which is not so awesome. Mobile hotspots are a poor alternative.

The downtime revealed PrimaCom manages the router WiFi. When the Internet was down the WiFi was also turned off. You couldn’t even turn it on in the admin pages (default login: username blank, password admin). Once Internet service was working again and I rebooted the router, I had WiFi. Weird.

The bummer about the router, or the larger network, is that it just forgets about idle TCP sockets after about 5.5 minutes. Idle ssh sessions and other quiet TCP links just stop working. Not even a reset, just a timeout, and it’s consistently timed so it’s not a FIFO queue filling up. There’s nothing in the router config that’s obviously causing the problem.

Of course web browsers never even notice, so most of their customers have no idea. I wonder if it breaks notifications via WebSocket though. For ssh I work around it with ServerAliveInterval=50. I suppose TCP keepalives would fix it in general but that’s a half-abandoned tech and the default interval in Windows is 2 hours (!) so you have to fiddle the registry. Ken has some weird TN3270 sessions he uses, I think SSL and telnet. We fixed his timeouts by just using Tunnelbear VPN which papers over the problem. I really should run my own VPN server.

We never could connect to an old school PPTP VPN. The TCP control channel for setup seems to have worked (according to Wireshark) but no GRE packets ever arrived.

The fun thing is I have an honest-to-goodness IPv6 address and all of it works. Sometimes I seem to be connecting to Google via IPv6. I’m not quite sure what to do with this capability, but it’s novel for me. I wonder if the router is still doing NAT for IPv6? The IP address a test site shows me is the same one my Windows box tells me I have, so I guess not. The router does have an “IPv6 firewall” enabled though, perhaps that provides basic protection from outside attacks? I should set up a remote IPv6 box to play around with this.

Update: Primacom seems woefully underprovisioned. In the morning I get about 5000kbps, bursting to 10Mbps. In the evening I’m doing good to get 500kbps, 1/10th the speed. I assume that’s contention with my other cable modem users. 500kbps isn’t really enough to even stream video.

 

Here’s a traceroute on IPv4

|------------------------------------------------------------------------------------------|
|                                      WinMTR statistics                                   |
|                       Host              -   %  | Sent | Recv | Best | Avrg | Wrst | Last |
|------------------------------------------------|------|------|------|------|------|------|
|                             192.168.0.1 -    0 |    3 |    3 |    2 |    5 |   10 |    5 |
|                              10.195.0.1 -    0 |    3 |    3 |   10 |   20 |   41 |   41 |
|                            172.16.0.201 -    0 |    3 |    3 |   15 |   24 |   42 |   42 |
|                            172.16.0.109 -    0 |    3 |    3 |   15 |   24 |   42 |   42 |
|                             172.18.0.53 -    0 |    3 |    3 |   16 |   25 |   43 |   43 |
|        ae63.edge7.Frankfurt1.Level3.net -    0 |    3 |    3 |   24 |   30 |   43 |   43 |
|   ae-2-3210.edge4.Frankfurt1.Level3.net -    0 |    3 |    3 |   30 |   34 |   44 |   44 |
|             10ge10-15.core1.fra1.he.net -    0 |    3 |    3 |   27 |   35 |   50 |   50 |
|              100ge5-2.core1.par2.he.net -    0 |    3 |    3 |   74 |   81 |   93 |   93 |
|             100ge14-1.core1.nyc4.he.net -    0 |    3 |    3 |  114 |  124 |  143 |  143 |
|              100ge9-1.core2.chi1.he.net -    0 |    3 |    3 |  143 |  156 |  163 |  143 |
|             100ge12-1.core1.mci3.he.net -    0 |    3 |    3 |  141 |  154 |  162 |  141 |
|               10ge4-1.core1.mci2.he.net -    0 |    3 |    3 |  142 |  155 |  163 |  142 |
|wholesale-internet-inc.10gigabitethernet1-3.core1.mci2.he.net -    0 |    3 |    3 |  142 |  155 |  163 |  142 |
|lag-to-oak.edge-a.clay1.mci.us.as32097.net -   34 |    3 |    2 |  160 |  161 |  163 |  160 |
|lag-core-b.dist-1-3.clay1.mci.us.as32097.net -    0 |    3 |    3 |  146 |  156 |  163 |  146 |
|                         wk.somebits.com -    0 |    3 |    3 |  145 |  157 |  163 |  145 |
|________________________________________________|______|______|______|______|______|______|

Powerline ethernet

I’m spending a few weeks in an apartment in Berlin that’s a large sprawling place. The single wifi router at one end has no hope of reaching the other end and there’s no ethernet in the house. So I took a $50 gamble on a powerline ethernet kit and it seems to work, at least up to 30Mbps. We’ll see if it lasts; my friend says in his experience these things fail after a month or two.

The plug-n-play experience out of the box is pretty great. Plug both devices in, press the pair button, and you’re done. It acts more or less like a bridged ethernet. Plug one end into your router, another end into a computer, and you’re done.

One wrinkle here is security. Your network is being carried out on power lines and who knows how far they’ll go. So the products all have a shared key encryption mechanism (pairing is key exchange) to keep your network private. They probably leak all sorts of RF out the modulated wires, oops.

TP-Link makes a huge variety of these devices. My box says “AV600 TL-PA4020P Kit”, a variant I can’t even find anywhere, but it seems about the same as the AV500 versions only 100Mbps faster. The choices seem to be power passthrough or not, 1-3 ethernet ports per device, and then more expensive for higher bandwidth (up to 1.2Gbps). Different versions for different countries too, both the electrical plug shape and radio frequency interference concerns. Some versions also have a WiFi access point built in, I kind of wish I’d bought one but I wanted to keep it simple and cheap.

The relevant network standard is HomePlug, some vendor consortium for powerline networking. (They just dissolved last year and put all the specs in the public domain.) In theory there’s vendor interoperability. I don’t quite know what’s going on, the Wikipedia article talks about 1000+ channels from 2 to 86MHz.

The really interesting play here is if all your Internet of Things devices supported this kind of networking. Just plug them into the power; no wifi or ethernet required. I wonder why that’s not more popular, I suspect it’s because of the rumored flakiness of powerline ethernet.

 

Converting video to x265 with avconv

A simple command line for converting video to small x265. These options are chosen to produce acceptably low quality, low bitrate output.

avconv -i in.mkv -c:v libx265 -c:a copy -crf 29 -s 854x480 -preset fast out.mkv

  • c:v libx265 means “encode using x265”.
  • c:a copy means “copy audio, don’t re-encode”
  • crf 29 means “slightly worse than default 28 quality”
  • s 854x480 means “resize to 480p”
  • preset fast means “I don’t have a hardware encoder so please don’t take forever”

Obviously better quality is possible, this is producing about 500-600kbit/second video or about 4x the same of the audio track.

Speaking of audio track it’d be nice to convert whatever the source is to 128kbps AAC stereo. I’m not clear if a simple “-ac 2” is sufficient or if more complex downmixing is necessary.

Windows: typing European on American keyboard

Apple has this great way to type non-ASCII characters like Ö or ß or € on both MacOS and iOS. You long-press the key that looks similar to what you want (an O, or an S, or a $) and then wait a bit and a UI pops up and you choose what you want from a UI picker. It’s not great for fast touch typing but for that you’d want a full language keyboard. But for wanting to type the occasional non-English word, it’s great.

Windows, not so much. The frequent advice is type it by character code as if I’m going to memorize 153 and 128 and 223. Not to mention my laptop doesn’t have a numeric keypad. The advice to use the Character Map in that post is not so awful, it works OK, but it’s pretty clumsy.

The best bet seems to be the US international keyboard. It’s an alternate American keyboard where ’ ” ` ~ ^ are dead keys; they’ll modify the next letter to be accented, or else insert themselves if that makes no sense. It works pretty well. Even better the right Alt key can be used to type a bunch of other stuff like ß or €. It’s not perfect but it’s pretty good. Note the Windows 10 anniversary edition moved this; it’s now listed as an “Option” on the English (US) keyboard, not a separate keyboard.

I also tried Holdkey which promises to add an Apple-like typing UI. But it didn’t work very well, the way it grabs onto the keyboard is problematic. There’s some other options along these lines I didn’t try.

Update: if I type y’all I get yáll which I think is hilarious.

Update 2: by default Ctrl-Shift switches between keyboard layouts. That’s obnoxiously easy to press by accident. You can turn that off or change the key mapping.

Twitter API, tweepy, and error handling

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))

SQLAlchemy thoughts

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.
  • sqlite is a PITA for migrations because it doesn’t have much support for alter table. But Alembic does have nice “batch” support for “move-and-copy” migrations.

Wanted: simple persistent apps

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.

Alfred replacements for Windows

I loved Alfred on MacOS. 95% of the time I used it to launch apps with the keyboard, but I also liked its clipboard management, access to Google searches, etc. What about Windows? Turns out there’s lots of options. I cribbed these from this Reddit discussion, also see this article. Many of these are cross-platform and work on Mac and/or Linux.

Hain is pretty slick and what I just chose to switch to. It feels almost exactly like Alfred to me, the only thing it’s missing is number key shortcuts to pick items. It’s not very configurable (no skins for instance) but the defaults are good. I added some plugins: Clipboard (to replace Ditto), Google. The terrible / great thing about Hain is it’s implemented in Electron so there’s a full HTML5 shell running. Or several maybe. I see four hain.exe processes total about 200 MB of RAM. And 0.02% CPU which is small but not zero.

Zazu is newish and open source. It seems OK but not as polished as Hain; configuring it requires editing a JSON file, for instance. It’s also HTML5 based (Chrome?), 240MB in memory and 0.02% CPU.

Wox is popular and pretty solid. The install is strange; it says it requires you also install both everything (a file indexer) and Python3. But I think those are both optional upgrades. It’s a little ugly out of the box, Hain is nicer. Wox is 125 MB of RAM and 0.12% of CPU. It’s built in .NET.

Launchy is what I used to use. It’s old and ugly and doesn’t really do anything but launch apps. And that, not very well. Nothing to love but it does work and is free.

FARR is another option with a long history. I couldn’t figure out how to rebind the hotkey, and it’s kinda old and ugly too, but it seems very capable. Also quite small; 20 MB RAM and 0.00% CPU when idle, like it should be.

 

While I’m here, a shout-out to Seer which gives a space bar quick-preview to the Windows Explorer, like MacOS finder has. It’s about $12. Lightshot also seems like a nice improved screenshot-taker. It’s free, I think they’re trying to drive ad traffic to prntscr.com. (Speaking of which my Apple keyboard has no PrntScrn button. It does have an F13 though which you can bind in Lightshot, even if the UI shows a blank key when you bind it.)

Twitter API: extended tweets

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.

Symantec VIP two factor auth

I just set up Symantec VIP two-factor authentication for my bank account, to replace an old VeriSign hardware token. Symantec VIP is a mobile phone app, they also sell a hardware token.

The basic security model is similar to the VeriSign token or TOTP as implemented by Google Authenticator. I type my password to log in, then am prompted to type a six digit second code from the Symantec VIP app. The code generated is valid for 30 seconds. I’m not positive it’s time-based; every time I generate a new token, it shows being valid for a full 30 seconds.

The Symantec VIP app has a very simple model of user identity. The first time I ran the app on my phone it assigned me a “Credential ID”. I then supply that to every single site that I want to use it for 2FA. That’s different from the Google Authenticator model where you scan a QR code to set up a new site. Not sure how Symantec supports having multiple identities or changing your ID. There is an option to scan a QR code, so maybe there’s a second identity model.

There’s no backup of the token; if I lose the phone or something I have to go back to my bank to set up access again, out of band.

Another slight weirdness; my bank says it will take 48 hours to enable the token. No explanation why it’d take that long. In the meantime they gave me a temporary 6 digit code that will work many times as my 2FA code. That’s not ideal but probably harmless, at least in this application.

Symantec VIP is more complex than I’ve seen. There’s a whole VIP Manager product for enterprise management, maybe that provides more flexibility and control for advanced users.

As an end user I prefer Google Authenticator, mostly because I’ve got it set up for several sites already. But Symantec VIP seems OK too. No idea how their backend integration tools compare. TOTP sounds awfully simple to deploy.

Update: one problem with the basic Symantec VIP model; my bank is relying on Symantec to keep the secret safe. They didn’t generate a new secret for me to share with them, they’re using whatever is baked into my default Symantec ID. That may be appropriate for many businesses that want to outsource security, but it’s a form of risk.

Update 2: the python-vipaccess tool works to generate new Symantec VIP tokens that you can then import into Authy.

Python metaprogramming

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.

 

Some ssh tricks

I’m making some ad-hoc solution for monitoring a security camera after my bad experience with Foscam. Here’s some ssh tricks I had to do to make it work.

Restricting ssh to rsync. A way to set up a passwordless SSH key for rsync that’s not a total security hole. I did something similar myself for backups awhile back.

Chaining ssh tunnels. I need to create an ssh tunnel to a second host, and from there to a third host. Tunnels more or less chain like you’d expect but you need to add the -t flag to ssh to get it to create a tty for some reason. The -A flag is handy too, of course.

 

Foscam R2 is garbage

I got a Foscam R2, a cheap and capable Internet camera for home security. But the software is so bad and insecure I’m returning it. A camera in my house has a high bar for security. I do not want video from my house leaking on the Internet. Foscam is designed around a cloud service, so the bar is very high indeed. Given how bad my first 30 minutes were I’m returning the thing.

Summary:

  • I can’t upgrade the firmware
  • I can’t connect to the IP interface at all
  • The website requires a native code plugin to run
  • They don’t quote user input correctly

Security problems

The biggest problem is utter contempt for basic security. Some examples:

The camera configuration won’t accept my wifi password because it has a space in it. Foscam support has an alarming list of characters you can’t use, including & and =. This suggests they aren’t properly quoting user input. (The linked discussion confirms that.)

The camera’s local IP interface is HTTPS only. Nice! Only there’s no valid SSL certificate since there’s no meaningful hostname. After telling my browser to ignore the warning I can get a login page and a tip briefly pops up “Don’t support using HTTPS to login chrome”. Logging in with Chrome does not work. Neither does Edge. I can maybe log in with IE10, but all I get is a popup saying I have to install a .exe plugin first to use the camera. No thank you.

There’s several separate websites: foscam.us, foscam.com, and myfoscam.com. I’m not positive but I think the .us site is an American reseller? They have an alarming security note

In early June Foscam Digital had been notified of 18 security vulnerabilities that existed on cameras manufactured by Shenzhen Foscam ...  Foscam Shenzhen initially did not address the vulnerabilities for several months ... . However, on June 14th, shortly after the vulnerabilities were communicated directly to end-users by Foscam Digital in order to pressure Foscam Shenzhen to take action, Foscam Shenzhen released a firmware update response available here

Usability problems

I can’t upgrade the firmware. The mobile app has a firmware upgrade option and does seem to upgrade the camera to 1.11.1.6. But then there’s a second upgrade to 2.x.1.18 (yes, the x is part of the version number) that does not work via the mobile app. There’s instructions for upgrading via the web interface but since I can’t log in, I can’t do that.

 

The English translation is terrible. The very first text you see in the mobile app you have to use to configure the camera is “Has the account?Sign up”. There are translation errors all over the product. I’m usually the last person to criticize someone who speaks imperfect English as a second language. But this sure makes for a bad impression.

The website for the Foscam cloud service works for about 30 seconds, then pops up a dialog that says “Foscam web component has beed upgraded” (sic). The popup is modal with a “Click to download” button that says “Please click me to install plugin(Now we don’t support IE(64))”. It downloads a .exe that I wouldn’t dream of running.

 

I can’t find their MAC address prefix 00:62:6e in the OUI database. That might not mean anything. Or it might mean they’re cutting some important corners with their ethernet chipset.

 

 

Twitter Python clients by release date

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.

Windows sshfs clients

I want to access a remote machine’s Unix filesystem via ssh, the way you’d do with sshfs and FUSE in Unix. There’s a lot of options for it.

  • SFTPNetDrive, what I’m using now. Works simply out of the box. Free for personal use, $100 for commercial use.
    Seems fine, Y: is now my remote disk. Has some reasonable customization options but nothing overwhelming. There’s an option to mount the disk as “Network, Removable, or Fixed”. I was hoping that could fake out WSL so that I could see the remote disk in the Ubuntu-on-Windows subsystem (which now supports removable disks). No such luck.
  • NetDrive, the big daddy commercial system. This provides interfaces for a whole bunch of cloud storage options: S3, OneDrive, etc. 30 day eval, then you pay $50
  • ExpanDrive, another multi-service commercial option. $50
  • sshfs-win using WinFSP. Open source FUSE-like solution. Looks promising.
  • win-sshfs, a fork of an older project (keyword: Dokan). No commits for 9 months, but does have Windows 10 support so it’s not totally dead.

 

Canon MX850 and Windows 10

tl;dr: reinstall the Windows 8.1 driver to get the scanner working.

I have a Canon MX850 I bought 8 years ago. It’s one of those cheap multifunction inkjet printer/scanner/fax things, the ones that cost $20 but each ink refill costs a small part of your immortal soul. The printer has been pretty reliable, but the scanner keeps failing. I’m not certain but my guess is that Canon’s network scanner driver isn’t smart enough to follow the scanner through IP address changes from DHCP. But the printer keeps working, huh.

Anyway, the simple fix is to download and reinstall Canon’s driver. No need to uninstall first. Windows 10 is not supported by Canon, but the 8.1 (x64) driver seems to work fine. At least scanning does, via Windows Fax and Scan. Haven’t tried the fax side.

DDNS clients

I set up a new router and so once again am trying to figure out the hack I need for Dynamic DNS updating. I use afraid.org for DDNS and I need something on my home network so that if my IP address changes I notify afraid to update my record. And boy it’s complicated. In the past my router firmware (Tomato or OpenWRT) seemed to handle it for me, but my new router (Ubiquiti EdgeMAX) isn’t working. It has a DDNS client, but it’s fail.

Why so complicated? Because of history. In the bad old days there were all these complicated protocols for DDNS. Software like ddclient has support for a zillion different proprietary protocols. But DDNS has mostly now stabilized on “fetch this URL with a secret token to refresh your IP address”, taking the IP address implicitly from the source of the HTTP request. And that’s all we need. afraid acknowledges this, with a sample cron job which fetches every 5 minutes. Done.

Well not quite. Ideally you’d only post an update if your IP address actually changed. And ideally you’d update immediately, not every 5 minutes. This is possible (and implemented in the Tomato router) but it’s too much work to figure out how to do it. So the cron job it is.

One last wrinkle; afraid has two versions of the dynamic update. v1 and v2. Conceptually they’re the same, but v2 has improvements. The one I like is v2 doesn’t say “ERROR” if you post an update without a change, it just acknowledges that nothing changed. You have to opt names into the v2 interface in the web UI first.

I like how afraid’s example cron job is randomized so it runs at a random second, not exactly at 00:00:00 and 00:05:00, ... Thundering herds are bad.

RF scan in San Francisco

My fancy Ubiquiti access point has an RF scan tool. Here’s what it found in my house in San Francisco, Noe Valley.

Capture.PNG

Capture2.PNG

 

Not a great visualization; the yellow bar fills up the trapezoid. Mouseover tells me the 2.4GHz channels are about 20-30% “utilized” with “interference” of -95 dBm (noise floor?). 5.0GHz channels are mostly 0% utilized except for 112 and 136, which are about 20%. Interference there is -91 dBm for most, -96 for a couple.

My iPhone sitting nearby can see about 4 neighbor’s WiFi networks. Also probably a lot of 2.4GHz cordless phones, including mine. In practice 2.4GHz barely works through the house and 5.0GHz is terribly unreliable, probably because the walls are lath and plaster faraday cages.

 

Simplifying the efficiency gap measure

Spoiler: this is a summary of a failed experiment.

There’s a wonkish new measure of gerrymandering that’s influencing the courts called the efficiency gap. It is a measure of partisan bias of a districting plan, trying to quantify “wasted votes”. It’s not too complicated a measure. Suppose a single district election goes 53 voters for candidate D and 47 for candidate R. Then 2 of those D votes were wasted, because they were in excess of the 51 votes needed for a victory. All 47 of the R votes were wasted, since their candidate lost. If you count up all those wasted votes over all the districts you have a measure of how many votes were wasted in a state. For instance if the Rs consistently win 80% of a state’s districts 53/47 and the Ds win 20% of a state’s districts 20/80, then the Ds waste a lot of votes both in the winning districts (80% instead of 51%) and in the losing districts (47%). When you apply this measure to real elections it quantifies just how much the Republicans successfully gerrymandered a partisan advantage in states like Pennsylvania or Ohio.

It’s a simple measure, but it’s still complicated to explain to people. So I took a crack at quantifying something even simpler, the gap between popular vote and congressional seats. For instance in North Carolina last year Republicans took 53% of the popular vote for House of Representatives. However they took 10 of 13 seats, 77%. That’s a pretty remarkable spread of 24%. That outcome spread is a different measure than the efficiency gap, much less subtle, but it’s one I think people can relate to pretty easily.

What happens if I add that spread up over all 50 states’ elections and graph it over time? I scraped data from Wikipedia pages and came up with this:

image.png

There you go. It shows that in 2016 the Republicans got 55% of seats with about 50% of the popular vote, a spread of +5%. Back in 1990 they got only 39% of the seats with 46% of the vote, a spread of -7%. It’s the spread between the two that I’m interested in, so let’s graph the spread directly:

image (3).png

Note the graph of the spread is more or less correlated with the blue line above, the % of seats the Republicans got. I’m not sure what that means but it seems important.

Visualization Failure: Oversimplified

My main conclusion from this exercise is it’s a failure. I’ve oversimplified. there’s no obvious story here. I think any fine point about redistricting gets lost in the broader story of swings between Republican and Democrat popularity.

I think it’s a mistake to add up the votes and seats across different states. Every state is a different story. North Carolina had a virulently partisan districting which probably explains its huge gap in favor of Republicans. California has an independent non-partisan commission designing its districts, so a different process, although the outcome in 2016 still seems somewhat to benefit Democrats (62% popular vote, 73% of seats).

It might also be a mistake to assume all Republicans and Democrats are the same. I mean as partisan as the United States has become, Representatives are still elected to represent a local community and in many cases are known to their constituents. Congresspeople have individual agenda and views and don’t just reflect their R/D affiliation.

So back to the drawing board. I should consider just redoing visualizations from the efficiency gap data Stephanapolous and McGhee collected.

Update

There’s some nice visualizations of the efficiency gap in this paper from the Campaign Legal Center

Time series view:

Capture.PNG

Per-state view. (Darker color = bigger efficiency gap. Larger square = bigger state.)

 

Capture2.PNG.

Redistricting tools infodump

For the last couple of months I’ve been reading a lot about redistricting, hoping to find a way I can use my programming skills to have some political influence. There’s a remarkable story in recent politics summarized in the book Ratf**ked; the Republican Party engineered a takeover in 2010 of the House of Representatives. Long story short, they worked hard to win state legislature elections in 2008 and 2010. This gave them control over the redistricting process in 2010/2011, drawing the lines for House of Representatives elections. That line-drawing worked, the cartography alone is responsible for something like 10% of the Congressional seats that the GOP holds. You get crazy things like North Carolina having 10 of 13 representatives being Republican, despite the popular vote for those seats going about 50/50. The GOP is quite explicit about what they did, too:

The state representative who drew that [North Carolina] map said he had engineered 10 safely Republican seats only “because I do not believe it’s possible to draw a map with 11 Republicans and two Democrats.”

I’m interested in the data and cartography part of this, the technical question. So I’ve been reading up. Here’s some of what I learned. See also Mike Migurski’s notes.

Maptitude: ArcGIS for politics

The key software tool used in 2010 is Maptitude for Redistricting. It’s a GIS tool specialized for redistricting. It comes preloaded with demographic data, election data, and political boundary shapes. It lets you draw district plans and see what the result is. Think of it as ArcGIS but for political scientists. There are many demo videos online.

An individual license for Maptitude costs $700 on Amazon. Mostly they negotiate sales contracts for group use, Ratf**ked suggested it was $5000-$10,000 for a state. Compare $500,000 for previous software from the 1990s.

Maptitude is by Caliper Software. They seem to have a democratic mission, putting redistricting tools in the hands of ordinary people. In 2011 they even made a web version for communicating to voters called Maptitude Online. Several states bought and deployed it: Maryland, Idaho, Wyoming... None of those 2011 apps still work, the backing server seems down. But there’s video online. It’s a pretty clunky web UI, from the era when people compiled their Win32 C++ GUIs to Javascript and called it a day. I imagine the 2020 version will be much more Web native. But it does work to genuinely communicate redistricting to people on the Internet.

Political data

One nice thing about Maptitude is it comes with political data that you buy from them. But it’s all proprietary and expensive. What about open source / open data hacking? Wanted, for every state, for every election every 2 years:

  • Shapefiles for each voter precinct. The voting precinct is the smallest building block of election data. You can’t find out how an individual voted in the United States, but you can see how a group of ~25-300 people in one precinct voted.
  • Per-precinct vote tallies for every major national election. President, Senate, House of Representatives. State legislature data would be nice too.
  • Shapefiles for every House of Representatives voting district. These are typically, but not always, the union of precincts. State election districts would be nice too.

America has no centralized election system. There is no simple database of election results, political districts, etc. Particularly not for data as detailed as per-precinct results. Every state maintains their own data. Some states publish nice clean CSV and Shapefiles. Some states will send you a scanned handwritten ledger if you call and pay a $4.95 document fee. It’s a mess. Here’s what’s available for open use.

  • OpenElections collects election returns. It came out of a data journalism product and they are doing good work towards a 2016 set but it is a long process.
  • election-geodata is a project headed up by Nathaniel Kelso which collects precinct and district shapefiles. It’s not complete but has gotten a whole lot of data, particularly for 2016.

Between those two projects I think we have ~75% of 2016’s election in easy-to-use format.

Several folks have published detailed maps on the Web but have not published formal data exports. Decision Desk HQ published a per-precinct map of the Presidential election in 2016. ESRI published a per-precinct map for the 2008 presidential election. I could have sworn I’ve seen a 2012 national per-precinct map too, but I can’t put my hands on it. The LA Times Data Desk has also done good work but it may be California-only.

Also worth reading: Mike Migurski’s work on North Carolina elections, where he goes through the exercise of collecting and analyzing the 2016 election for that state. It’s a model of what I’d like to be able to do easily for every state and every election.

Demographic data

I haven’t researched this much yet, but the other half of redistricting is understanding the demographics of the people you’ve put into the districts.

Census data is the basic data standard here, free and public and easy to work with. It comes broken down by census blocks, groups of 0-500 people. Those blocks do not line up with voting precincts, so some slicing and joining is required to produce per-precinct views of census data. Migurski did this for North Carolina.

Marketing data is the other interesting option here, and a total black box to me. But all of the tracking tools that enable direct sales and Internet advertising are producing data that’s a political goldmine. I suspect little to none of this data is available for free open hackery. News articles about the 2016 campaign are full of stories about how various political groups used this data with varying levels of effectiveness.

Edit: see this amazing article about Cambridge Analaytica, Trump, and Brexit.

Areas of work for redistricting

When I started this research I had no idea something like Maptitude existed. I thought maybe I could help build a GIS-for-elections and revolutionize politics. Ha! I’m at least 10 years too late on that. The state of the art in 2011 was a tool that let political experts draw district plans and then understand with great detail how those people voted in recent elections and therefore, how they would likely vote in the next election. What about 2020?

  • Demographic prediction. District plans last ten years; you can design a plan that looks great for your party in 2022 only to find it fails in 2028, what is called a “dummymander”. Predicting demographic trends sounds like a good data problem. There’s a lot of expertise on this already.
  • Automated districting. I get the impression 2010 districts were still mostly hand drawn. But computers can easily produce zillions of plans. It’s a problem ripe for optimization algorithms.
  • Smarter measures of gerrymanders. This topic is hot politically now, particularly a new measure called the efficiency gap which quantifies the partisan bias in a district plan. Communicating these measures to the voting public seems really valuable.

The hard part for me with all this is I’ve rapidly learned that redistricting is not a technical problem, not something I can program a solution to. It is a political problem. People with political expertise and power are going to set the agenda. But software is a tool for that politics, maybe a tool I can help craft.

Fog of World, imports

Played with Fog of World today, an iPhone app that turns GPS tracking into a game. It records where you go and then paints the map, “lifting the fog of war” in videogame style. It’s heavily gamified; lots of badges and stuff for exploring more of the world. I love the idea of this kind of thing, my previous experiments with mapping walks I took is in the same vein. Also GPS tracks for my private airplane flights.

The engineering is pretty good quality. It has very thoughtful import/export options, including a nice integration with Dropbox. Map rendering is pretty good. Plenty of care applied to battery management.

I’ve been running OpenPaths for years, recording my world travels. It took about 5 minutes to export that data to KML and import it to Fog of World and boom, I’m level 75 with a filled out passport. Unfortunately OpenPaths only records point locations every few minutes, not full paths, so I have a bunch of little speckles of revealed parts of India rather than a clear path on a trip. Fair enough.

I also imported my RunKeeper data from my old walks project. That gives much smoother paths. The display is still kinda janky though, if I were building this app I’d give paths more width and smoothing. That or else try to do some scalable measure, where if I’m looking at a whole country map I see all of the Bay Area filled in, but then I can zoom in for more detail.

Update: this app seems to be killing my battery. The usage monitor in iOS only shows it using 20-30% of my energy, but having it running is the difference between  a 5% battery in the morning vs a 60% battery. At least I thinks it is.

I’m trying Strut now, a similar thing, but much more heavily focussed on competition. Also no import / export :-( But it is free. (Update 2: it’s even harder on the battery than Fog of World). Also while researching all this I found a nice comparison of Fog of War v1 vs v2.

Screenshot below, compare to this map

Photo Apr 05, 10 35 49.png

SSL and hostname privacy

The GOP’s craven selling-out of user privacy to ISPs has me wondering, just how private is the modern web?

Only sort of private. HTTPS Everywhere is working, at this point I’m surprised if a site doesn’t support SSL. So the contents of web requests and replies are encrypted. Of course the IP address of who you’re talking to is not protected. But the hostname is also in cleartext; your ISP can see that you are specifically visiting eff.org or nelsonslog.wordpress.com. This is true both in HTTP/1.1 and HTTP/2.0.

Really the hostname is being exposed by SSL/TLS itself, in the Server Name Indication. The SNI is the way a single server can serve multiple web domains, it’s virtual hosting for SSL. The client initiates a connection and sends in cleartext “I’m trying to talk to eff.org”. The server responds with negotiating a connection using eff.org’s certificate. (The hostname may also appear in the request as a Host header, but I believe that’s encrypted.)

Why not encrypt the hostname in SNI? Who do you encrypt it for? SSL is as much about verifying server identity as it is encrypting the traffic, so the protocol starts with the client asking for a specific identity to set up the encryption. I think the hostname could be encrypted in the handshake with a second encryption channel, but I haven’t thought hard about it. And I have no idea how hard it would be to implement in practice, much less get adopted.

Note that HTTP/2.0 doesn’t do anything new about hostnames, it just uses TLS 1.2. The HTTP/2.0 spec mandates SNI support and that the client use it to specify the destination host.

Outside HTTP, your DNS hostname queries are also being sent in plaintext. So your ISP could snoop (or hijack) those. Thanks to Tom Jennings for pointing this out to me. In theory DNSsec or DNSCrypt or something like Dingo could protect against this, maybe now’s the time to get serious about deployment.

While I’m here, a lot of discussion yesterday was along the lines of “well time to use a VPN”. But VPNs don’t really solve the problem and introduce lots of new problems on their own. I only like them when you’re in a hotel with a shitty network or you need a specific private intranet connection.

It’s really a shame IPsec failed.

Two unrelated PS4 gripes

Sony’s online store site requires a login. The login requires third party cookies; logging in to  store.playstation.com requires setting using a cookie at auth.api.sonyentertainmentnetwork.com, so it won’t work if you have third party cookies disabled. This breaks the Brave Browser, which disables third party cookies by default. It also breaks in Chrome if you disable the cookies. I thought Safari prevented third party cookies by default, I wonder if they have a workaround? The error displayed is

{“error”:”invalid_client”,”error_description”:”Bad client credentials”,”error_code”:4102,”parameters”:[]}

The PS4 operating system, or the apps, have a bug where if a game is put in the background the fan gets really loud. Ie, if you open the system menus. I assume instead of suspending processing entirely the game starts spinning consuming lots of CPU or GPU, generating heat, which makes the fan run. It’s dumb. A fan theory is that the games have no framerate cap and so they effectively render at 1000 FPS or whatever, but I think the problem may be broader than that.

 

LA Times and ads

The LA Times is a good newspaper and is currently doing the best political coverage in California. They are also the most aggressive ad shoveling website I have ever seen. Their ad blocker blocker and paywall works, preventing me from reading articles. I even tried installing an ad blocker blocker blocker which doesn’t work.

So I open articles like this in incognito mode, and let it run its ads, and close the popups and mute the videos and try to ignore the visual distraction. But boy that page does not go quietly. Here’s how they reward their readers.

Capture

That’s a timeline of 30 seconds of page activity about 5 minutes after the article was opened. To be clear, this timeline should be empty. Nothing should be loading. Maybe one short ping, maybe loading one extra ad. Instead the page requested 2000 resources totalling 5 megabytes in 30 seconds. It will keep making those requests as long as I leave the page open. 14 gigabytes a day.

There’s no one offender in the network log, it’s a wide variety of different ad services. The big data consumer was a 2 megabyte video ad, but it’s all the other continuous requests that really worry me.

A lot has been written about the future of journalism, the importance of businesses like the LA Times being profitable as a way to protect American democracy. I agree with that in theory. But this sort of incompetence and contempt for readers makes me completely uninterested in helping their business.

Edit for pedantic nerds: for some unfortunate reason this blog post ended up on Hacker News where people raised eyebrows at my 14 gigabytes / day estimate. To be crystal clear: I did a half-assed measurement for 30 seconds and measured 5 megabytes. 5 * 2 * 60 * 24 = 14,400, or about 14GB. That’s all I did.

Yes, I know that extrapolation is possibly inaccurate. If you want to leave a browser window open for 24 hours to measure the true number, be my guest; I’ll even link to your report here. (Hope you have lots of RAM and bandwidth!) I’m a web professional with significant experience measuring bandwidth and performance, I know how to do this right. But that’s the LA Times webmaster’s job, not mine, and I don’t have a lot of confidence that they much care.

3.2 hours is the current record for measuring traffic before something crashes.

Edit 2: for a lot of people visiting my blog I think it is their first view of a network timeline graph like this. Generating your own timeline for any web page is easy if you use Chrome. It’s a standard view in the Network tab in Developer Tools. See the docs, but briefly you open dev tools and click on network and watch the waterfall graph. You want to open it before loading the page so it captures everything from the start. Beware a normal web page will end very soon and be boring; the LA Times is a very special website.

Here’s a larger view of 200 seconds of that same LA Times article page, and a direct link to the full size image. (It’s funny redoing it, every time I look at this page it does some new insane thing.)

Capture.PNG

Upgrading a PS4 hard drive

I just upgraded the hard drive in my Playstation. It was remarkably easy following these very thorough directions. Sony designed the system to be easily upgraded, quite a surprise.

The hardware is super simple; slide off the cover, remove a single branded screw, and slide out the drive tray. Swap in the new drive (4 screws) and slide it back in, done. I replaced it with a 2TB hybrid drive. A full SSD would be faster but costs 5x as much. These Seagate SSHD drives have a 64GB SSD caching the 2TB platter and seem like a reasonable compromise.

The software is also surprisingly simple. Back up the PS4 to a spare external  USB drive, swap in the blank new drive, then boot to recovery mode. You can then reinstall the firmware from a download Sony provides, restore your backup, and you’re done. It took all of 30 minutes of my time, plus 5 hours waiting for the backup and restores to copy.

My main reason for the upgrade was more space. The old units shipped with a 500GB drive which after overhead, etc allowed for about 6 games to be installed at once. Significant nuisance; I don’t want to download 30GB a second time for something I want to revisit.

 

Non-ASCII filenames

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.

Anyway, here’s a quick trick for finding non-ASCII filenames

LC_ALL=C find . -name ‘*[! -~]*’

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.

Putting lolslackbot on the back burner

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.

 

Synchronizing Windows directories

I’ve been using Allway Sync to keep my two new Windows machines in sync. It’s pretty good. I sync one machine to an external hard drive, then sync that drive to the other machine. So really it’s three copies. Allway Sync also supports various Internet services for syncing, like Dropbox or its own cloud service.

The sync algorithm seems relatively robust. It’s a bidirectional sync, so changes on both sides can propagate at the same time. There are safety features like a sanity check if too many files changed. It tracks metadata and deleted files so deletes can propagate. It also keeps old versions of things in a hidden _SYNCAPP folder. I haven’t delved into details of how it handles a single large binary file that’s only partially changed, I don’t know if it has binary diffs or if it just copies the whole file over.

The UI is pretty awkward. Mostly it’s just ugly. But it’s also a bit confusing. I believe you have to define a new job for each folder you want to sync. (There is a way to sync one source folder to multiple destinations.) I finally found that if you enable the toolbar, there’s an icon for “sync all jobs at once”. I haven’t tried the automatic syncing yet, it seems to rely on a service watching for change file events and/or on a timer.

The trick now is figuring out what all in Windows I can safely sync. My Steam apps folder is safe to sync, and saves me from having to download a 30GB game twice. Syncing my Documents folder seems to work too and propagates some app settings, game save files, not to mention my actual work output like source code and text documents.

The part I’m on the fence about is syncing my Roaming profile. That should keep many more app settings in sync, and my first time copying it seems to have worked OK. But there’s a lot of random stuff in there that doesn’t quite seem like it should be copied, like Slack’s cache files. OTOH the Roaming profile was designed to be copied from one machine to another, so it should work? Edit after trying it I think syncing the whole Roaming profile is a bad idea. Parts of the folder, like Microsoft, seem to be treated specially. Also it makes the most sense to sync when nothing is open that writes to that directory, ie before you log in, and that’s awkward.

It’s free, but there’s a limitation on the number of files. The license is $26 but that’s for a single machine. $16 for a second one.

There’s a bunch of other sync options too. For a long time I used Unison to sync file systems. It works great and I’d still use it for a Unix command line. There are Windows build but I couldn’t get the GUI version to work. I also get nervous using Unix tools to manipulate Windows filesystems.

 

Windows: backing up a failing disk

Ken’s Windows 7 machine has a hard drive failing. Some errors, a few corrupted / lost files. We’ve already bought a replacement drive but are having a seriously hard time getting useful data off the old disk. The disk mostly works; he runs it with Windows for hours at a time (I know, bad idea). But it has some bad sectors.

Simple task: just make a backup. Copy all the files off of it. Windows Backup doesn’t seem to work with no useful feedback why. Casper, a third party disk imaging tool, gives up the moment it encounters a read error. Acronis True Image, another cloner, is free for Western Digital drive owners but the installer doesn’t even run. PCmover isn’t really a backup tool and isn’t backing up complete data. It’s a fucking clown show. I’m about to bust out a Linux system just to run ddrescue. I did find a suggestion that HDD Raw Copy Tool might work.

Hard task: set up the new PC. Ken would very reasonably like to migrate his own data and settings from Windows 7 to a new Windows 10 install on a new disk. This proves to be very difficult from a working disk and nearly impossible from a failing machine. Windows 10 abandoned Easy Transfer. Microsoft did a deal with PCmover but the software is a joke, most of what it moved doesn’t work on the new system. A specific problem is his username changed on the new Windows system and everything seems to have hardcoded the pathname of his old username, not just %user%.

Windows is such garbage.

 

Parsing fixed-width files in Python

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.

Further reading: Extract, transform, and load census data with Python.

 

HD FM Radio

My new car supports HD Radio. What is that? It’s a US standard for radio stations to broadcast a digital sideband adjacent to their audio frequency. The FM version is a 100-150 kbit/sec digital stream that encodes data in HDC, a proprietary standard that is similar to AAC. In theory there can be multiple HD streams on one channel, and a station could be digital-only. I haven’t seen that in practice.

The audio quality definitely seems better than analog FM. It’s also better than the low bandwidth Sirius XM channels like their NPR channel, that thing is awful. The big bummer is that since it’s a sideband the digital FM broadcasts don’t really offter the opportunity to free up any spectrum. Not that the TV spectrum process has gone very well.

 

 

2017 Audi A3 vs SD cards

My new car has a fancy stereo from Audi / Bang & Olufsen that can play audio (and video!) off of SD cards. Awesome! So I loaded up a 128GB SDXC card with my music collection, inserted it, and watched it crash as it indexed. But it seemed to work anyway after rebooting. Only some music is missing.

Looking more closely I figured out music started being missing right around Johnny Cash. But nothing wrong with those Johnny Cash files, they work on a new card just fine. A bit more googling and head-scratching and I learned the Audi might only read 64GB of an SD card. This limit is baffling; the big limit on SD is 32GB, the SDHC format. The car’s manual explicitly says it supports up to 128GB cards. I found this other post that claims > 64GB cards work, but only with FAT32, not exFAT. There may also be limits on the number of files / directories / etc, but it’s vague.

Anyway, on my exFAT SDXC card everything after Johnny Cash is unreadable. At first I thought that was the 64GB limit but counting carefully really it’s like 69GB in. I’m also at about 9800 files before I hit the Js, so maybe it’s actually a 10,000 file limit?

Another mystery is the indexing system. It definitely scanned the SD card the first time it saw it, for several minutes before crashing. Now when I put the card in it doesn’t index it. I’m not positive if it’s detecting changes in the drive or not. (I think so?) Where is it storing the index? There’s a file on the root of the SD filesystem named “WMPInfo.xml” that it placed there, some Windows Media Player junk. But it’s only 296 bytes. The car has its own dedicated hard drive with a partition for a “jukebox” I can copy music to. Perhaps it has another partition for databases and stuff. It’s got a copy of the GraceNote database built in somewhere!

 

OpenAddresses / population

Justin Meyers did an awesome treatment of OpenAddresses data. He put all the points in QGIS, then binned them by county, then put the shapefile in a repo. Nice! I wanted to see what the data looked like normalized by population, so I did two treatments. One is kinda sorta logarithmic, the other is a simple linear scale capped at 2 addresses / person.

Logarithmicish

output.png

Linear, capped at 2

linear.png

I’m not quite sure what this visualization really shows. I was hoping it’d be a proxy for data coverage; like naively I expected there’d be one address per person, more or less. But that’s clearly not what I’m seeing here. The Montana outlier is particularly baffling, there’s 10 addresses / person in many counties.

 

routes at my WISP

I continue to be baffled by my WISP’s networking. Last few days I’ve had frustrating small outages, like 1-2 minutes at a time. But only during working hours. Support told me they were doing “some maintenance that might cause that” one of the days. I fear they think even an occasional 2 minute outage while they reboot equipment is OK, but happening 5+ times a day is getting really old. I do have some sympathy for them though. It’s a fixed wireless network, my house is connected via at least 2 radio relays at other customers’ houses before reaching a wired network. That’s gotta be hard to manage.

Anyway, I realize part of my confusion now is that traceroute is lying to me. Here’s an mtr report after running about 25 minutes.

                                       Packets               Pings
 Host                                Loss%   Snt   Last   Avg  Best  Wrst StDev
 1. OpenWrt.lan                       0.0%  1606    0.4   0.3   0.3   0.5   0.0
 2. sbbgateway.lan                    2.6%  1606    2.2   2.3   1.6  24.6   2.0
 3. 173.195.183.1                     0.0%  1605   35.7  39.6  16.0 136.5  15.0
 4. 173.195.188.45                    0.0%  1605   33.3  37.5  14.4 139.4  14.9
 5. 173.195.188.21                    0.0%  1605   46.1  39.7  17.2 142.3  15.5
 6. 173.195.177.1                     0.0%  1605   29.0  36.9  18.0 128.5  15.1
 7. 173.195.177.254                   0.0%  1605   37.8  39.0  17.5 145.9  15.3
 8. v122.core1.fmt2.he.net            0.0%  1605   39.1  51.3  28.0 176.6  14.3
 9. 10ge7-1.core1.sjc2.he.net         0.0%  1605   57.3  51.2  27.4 128.1  15.7
10. 72.14.219.161                     0.0%  1605  104.7  47.6  28.2 155.5  16.3
11. 108.170.242.81                    0.0%  1605   57.0  49.5  27.5 142.6  15.9
12. 216.239.49.103                    0.0%  1605   55.2  50.6  28.3 146.1  15.8
13. google-public-dns-a.google.com    0.0%  1605   49.0  47.2  27.4 158.4  14.3  

Hop 1 is my router. Hop 2 is the wireless antenna on my property. Hop 8 is Hurricane Electric, a network provider in California, and beyond that is the public Internet.

But what’s going on between hops 3 and 7? I used to think this was the wireless nodes in my WISP, that hop 3 was the first radio and hop 4 was the second and so on. But looking at that average ping time I realize there’s no latency between 3 and 7. So now I think that hop 3 must be the first bit of wired infrastructure at my ISP, and that hops 2-3 are the sum total of all fixed wireless links. Perhaps they are acting as bridges, transparent at the IP layer. That’s how my own Ubiquiti nodes operate, I actually have 2 Ubiquity M2s running between hops 1 and 2 that are invisible to mtr.

FWIW the boxes at hops 3-5 look to be running MikroTik RouterOS. That’s also consistent with wired infrastructure; my wireless antenna at hop 2 is a Cambium device. No idea what 6 and 7 are. I don’t want to freak out my ISP by probing too hard.

One reason I’m looking at this so closely is I’m trying to understand the 2.3% packet loss shown at hop 2. That looks like it’s to my own equipment and I should be able to fix that. But every test I’ve done directly shows 0 packet loss to that device, the Cambium antenna up in my tree. Now my theory is the packet loss is actually in the wireless network between hops 2 and 3, the WISP’s wireless infrastructure. MTR can’t report it directly because those devices aren’t visible at the IP layer, so it just credits the packet loss to the last IP hop in the route, hop 2.

I think I see a similar thing when I mtr backwards back into my router at the WISP from a public Internet host; there’s no latency in my ISP’s network on the way in until a high latency gap at the last hop. The route back is different from the route out, which makes direct comparison a bit trickier.

Latency

I did a ping test to 173.195.177.254, the edge of my ISP’s network.

51 packets transmitted, 51 received, 0% packet loss, time 50076ms
rtt min/avg/max/mdev = 17.645/38.194/84.315/14.119 ms

I also asked my neighbor to do one.

52 packets transmitted, 52 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 17.737/29.401/53.861/8.731 ms

So his latency is 9ms better than mine. Significantly less jitter and worst case, too. I believe the difference between us is one radio hop. He has a radio link directly to Twin Cities Church. I think I have two hops, one north to a house and then from there south to the church.

I’d thought the church was where the wired internet began, it’s a major hub for the WISP. But those latency numbers suggest there’s possibly more wireless. The WISP’s office is down in Alta Sierra. The distances involved are so short I don’t think signal propagation time matters; it’s at most 20km, or 0.07ms at the speed of light. Not relevant. Processing time on the antenna relays though, not to mention congestion, those matter. Perhaps it’s 9ms per wireless hop, based on my measurement of my own link. We have ~20ms of latency unaccounted for, that suggests there are two more wireless hops from the church to the wired infrastructure.

Exede satellite Internet

A Metafilter discussion introduced me to a type of Internet access I didn’t know about before; Exede satellite Internet, part of ViaSat (and WildBlue). It seems better than the Hughesnet satellite Internet which is so slow, metered, and high latency as to be nearly useless. Although I took a brief look at Hughes and they seem to have improved their offering somewhat, not sure if Exede is significantly better.

If you’re in the right regions Exede offers Liberty Internet, 12/3 Mbps, or even 25/3, for $70-$150 a month. The problem is after you go through 12-30GB that month they drop you down to a lower service which is only 1-5Mbps, or maybe worse. If you’re in the wrong area all you get is Classic service, 5/1 Mbps, for $50-$130/month. That comes with a 10-25GB monthly cap and I can’t tell if it’s a hard cap or another slowdown.

It’s still high latency though. Their FAQ is full of mealy-mouth bullshit about “web accelerators” and how latency is better, but the what to expect page confesses 700ms latency and that gaming won’t work. That’s the incontrovertible problem with geosync satellite systems; it’s 240ms just getting to the satellite and back, not to mention all the other work that has to be done.

The other part of Exede that got my attention is it’s bidirectional; you’re sending signals back to the satellite via the antenna. Old Hughes installs relied on a phone line for uploads. Hughes now advertises up to 1Mbps upload speeds though, so maybe they have a satellite option now.

I was baffled why the 12/25 Mbps service was available in San Francisco, but only 5 Mbps in Grass Valley. It’s satellite, why does it matter where I am? Well it turns out they’ve broken up the US into cells with different “beams”. I found a good map and technical detail. It looks like most of the western US isn’t served by ViaSat-1 at all, but instead by Anik-F2.

beams.JPG

 

beams 2.JPG

 

Windows metered network connections

My ISP is down again so I’m back to Verizon tethering. Setting up the network connection I noticed Windows has a metered network option. The docs are very vague, but basically it’s a flag to tell the OS and applications “hey, this network isn’t free”. Windows itself will be a bit more careful; only downloading priority updates for example. There’s also configurable options to not sync OneDrive or download device drivers.

In theory third party apps could also inspect this setting and be smarter on a metered connection. Specifically apps on the new “Universal” platform. In practice I wonder if many apps are that smart. Dropbox isn’t, apparently. It’s all a bit confusing really, and most of the search results you see on Google about metering are “why isn’t stuff updating how do I turn off this metered connection thing?”

Also TIL that Windows 10 enrolls your computer as a peer to peer server in uploading Windows updates to other Windows computers. Yes, by default Microsoft assumes you want to use your upstream bandwidth to serve other customers. That’s some fucking bullshit.

 

Ah, Windows, ye olde errors

Bloom is off the rose with Windows. Or at least, Civilization 6, one of the games I switched to Windows to be able to play well. (It runs on Mac but 50% slower, and I wanted higher end graphics hardware.)

The whole system often freezes when exiting the game to desktop. Well that’s not quite right, Ctrl-Alt-Del still works and you can reboot or log out. But Alt-Tab doesn’t work to switch apps, which is odd because it works fine while the game is running.

GSync also doesn’t work. That’s the fancy variable framerate stuff. All sorts of screen tearing unless I enable VSync.

Both of these bugs could be specific to Civ 6. But it’s the kind of thing you’d think the OS and its graphics drivers would take care of uniformly for all games. Ha, as if.

 

Windows S.M.A.R.T.

Windows doesn’t seem to have built in S.M.A.R.T. support! After reading this guide and this Stack question I think the best option is CrystalDiskInfo. It used to have some bundled adware but the author promises he removed it all, and there’s a portable version for download (ie: no installer). I took a chance and it seems to work.

Capture.PNG

That’s my USB drive. Ignore all the junk and focus on “Health Status: Good”. Its heuristics seem reasonable; at least it shows my two new drives healthy and identifies errors in a failing drive that look plausible.

Gripe

Why the fuck doesn’t Windows have basic SMART error monitoring and notification? It’s the first line of detection for a failing drive, popping up errors for the user would save countless amounts of lost data. (And ignore the advice to try Windows’ wmic; at least on the drive I know is failing, it shows “OK” even though it’s not.)

And why are SMART tools so bad? Note the same user-hostile display table at the bottom as every other SMART tool in the world shows. What’s the temperature? 123? 111? No, it’s 00000000001D, which for some reason is being displayed in hex with leading zeros. At least this program translates it to 29C. No idea what the spin up time might mean though. I don’t even know what “Current” and “Worst” are supposed to mean. Linux smartmontools shows the same nonsense.

Speaking of smartmontools, I tried installing like four versions of it for Windows from dodgy SourceForge binaries. They all sucked, many couldn’t even find my drives. So much terrible Windows software out there.

Ken’s computer is showing signs of a failing hard drive. Last CHKDSK randomly found about 30 files corrupted. The machine is about five years old, just in time for a shitty consumer hard drive to fail. Ugh.

 

An example ugly Windows font

I’ve complained about Windows font rendering but was hard pressed to have a good example. Well here’s one, from a Bloomberg articleCapture.PNG

Look at how ugly that is! The kerning in “To” is wrong. The “m” and “r” and “u” and “n” are all broken, by which I mean literally broken like white pixels in the middle of the letter. The tail on the “9” has visible jaggies. I’m not just nitpicking, I find this really difficult to read.

The font is a web font, TiemposTextWeb, at 18px. Maybe it’s just a spectacularly bad choice? But Bloomberg is a big publication, clearly someone thought it was a good font. That sample is rendered in Chrome; it looks the same in Edge. I have ClearType turned on with more or less default settings in Windows 10; I used the tuner to pick a very slightly heavier rendering at some point but I don’t think that’s the problem.

It looks much better in the PDF specimen. Here’s some sloppily-made images of the PDF and then Chrome / webfont rendering the same text, to show the spindly nature of Windows’ rendering.

pdf.png

ttf.png

Another example

Another example, Gentium Basic, an SIL font popular because it has support for a lot of scripts. The lowercase “a” is entirely broken, even at 30px.

Capture.PNG

I mean that’s some fucking garbage right there. It looks a bit better if install a TTF and render it with Paint.  It still looks bad, but at least it’s not broken, just ugly-ass.

Capture.PNG

On the same page there’s a “Gentium Plus” that looks a little better still. It’s not great, but it’s at least not embarassing. So maybe font quality is part of the story, but something very bad is also happening in Windows’ font rendering.

Windows customizations

I’ve now set up a second Windows box. I was in a hurry and didn’t take notes, but from memory here are some of the specific tweaks I made in addition to installing normal application software.

I sure wish Windows had a clean way to store these customizations and copy them to a new machine. MacOS is much better; almost everything is localized to your home directory and Time Machine will help you set up a new Mac.

I thought I’d be clever and copy my roaming profile over to the new computer. That worked for some things like Discord and Slack. But lots of configurations are stored in other places. Cmder still stores its config files right in the program directory for instance, which seems like a good idea if you’re using it as a portable app but otherwise is not a good thing. And some applications settings are buried in the registry and I don’t know of an easy way to extract the ones you can safely copy over.

Windows 10: separate speaker and headphones

I have both headphones and speakers plugged into my motherboard’s analog output jacks. It’s a pretty standard Windows desktop setup, the motherboard does HD Audio which has 5 analog jacks which can be programmed to do different things like speakers, headphones, line-in.

Also pretty standard, my computer had the RealTek HD Audio Manager installed, an ASUS skinned one. This does a nice job of popping up a dialog when the user plugs in new speakers and asking them to configure it. Unfortunately it also seems to have a behavior where when I plug in headphones it automatically silences the speakers. In fact both analog outputs show up as a single “Speaker” device in Windows, there’s no way to use them independently.

In theory the Realtek driver has option settings to reconfigure this behavior, to let you use the rear and front jacks as separate devices. But my version didn’t have those settings, no “Playback Device” section at all.

Following some cargo cult advice I solved this problem by just uninstalling Realtek entirely. Goodbye 500 MB of stupid reverb effects I’ll never use. Turns out Windows 10 itself can manage the audio hardware with no problems. I did have to unplug and re-plug the devices for Windows to detect them, but now my speakers and headphones show up as separate sound devices.

Capture.PNG

While I’m here, a little theory on how this all works in Windows. Each sound device is an independent output channel for apps to play to. Most apps just play to the “Default App”, which you configure in the Sound control panel or with a program like SoundSwitch. But some apps let you choose a specific output device, particularly games, and you can use that to play different sounds simultaneously through different apps. There’s also a notion of a “Communications device” separate from the usual default, I think for VOIP apps like Skype to use a headset always.

I’m still confused about what drivers are involved. Device Manager tells me stuff is being managed by Microsoft’s Driver 10.0.14393.0, which I think is just Windows 10. But Sound tells me that there’s also a RealTek Controller which a RealTek Driver 6.0.1.7910. I wonder if Microsoft ships that, or if I didn’t uninstall that driver when I uninstalled the Realtek Audio Manager?

Update: this stopped working after I rebooted.

Update 2: a reader wrote to suggest

The problem is that Windows 10 reinstalls the Realtek driver automatically (in the background without asking no less...). To stop that you can open the device manager and open the “Sound, video and game controllers” list (not “Audio inputs and outputs”, there it doesn’t work). There you will see that your audio device is a Realtek device again. Open properties, go to the driver tab and click on “Roll Back Driver...”. Now you will get the Windows driver and it wont reinstall the Realtek driver.

Garage door remote radio

Spent way too much time today learning about how radio garage door openers work. Good articles on Wikipedia: remotes and rolling codes.

Most garage door openers work on a radio signal in 300-400MHz. There are various identification / code systems in use to uniquely pair transmitters and receivers.

My San Francisco garage works by having the transmitter and receiver share a single 10-12 bit key that is programmed via DIP switches. Presumably they also have to agree on which frequency they speak. (Two gate controllers also work via DIP switches.) Note this kind of system is terribly insecure, it’s easy to build a universal opener that just sends all codes.

My Grass Valley garage has Intellicode, a rolling code. This works by the transmitter having a secret key. You put your receiver in “learning mode” and it memorizes the secret key. Then there’s a simple PRNG-like crypto protocol where the transmitter is generating one time passwords that the receiver recognizes. This is more secure than a fixed code, although there are attacks against it too.

There’s a variety of “learning remotes” that you can use to duplicate a garage door opener, to make a new transmitter. Fancy cars tend to have HomeLink systems. I just bought a Clicker battery powered remote.

HomeLink seems to work by first listening to a working transmitter, then copying it. Presumably it’s figuring out what frequency to use. And if it’s a fixed code, it learns the 10-12 bit code that otherwise you’d set with DIP switches. If there’s a rolling code you have to do an extra step of having the receiver now learn the HomeLink’s key.

The Clicker seems to work by me manually identifying which type of transmitter I’m trying to clone. It’s got a library of ~15 types, which presumably tells it what frequency to use and what kind of code it needs. Then there’s either physical DIP switches to set and memorize or for a rolling code, you have the receiver learn the Clicker’s key.

There’s also a new modern world of Internet-enabled garage door openers where you just tell it to open via a smartphone app. I’m told you can retrofit these as new receiver units wired into an existing working motor drive unit.

 

rsync to exFAT USB

Ran into a weird bug trying to rsync my music collection to a USB drive on a Linux box.

mkstemp function not implemented

This blog post has an explanation for the problem; rsync -a wants to set file owner, group, etc and exFAT doesn’t support those filesystem features. And apparently the Linux FUSE driver doesn’t just fail gracefully? Also not clear why it shows up as an error for mkstemp, except I imagine that libc function is also trying to set permissions.

Anyway trying the cargo cult solution which is not to use rsync -a, but instead just the options you really need, which are -rltD.

 rsync  --delete -rltDW --info=progress2

The -W is a bit of lagniappe, it’s supposed to help USB speeds. info=progress2 is a reasonable display for rsyncing 120GB of music files.

I’m seeing roughly 30±10MBytes/sec writing large files, . The destination is a USB 3.0 adapter for an SD Class 10 card. The card promises 80MB/sec reads and “somewhat slower write speeds”, so that seems reasonable.

 

Lightweight NTP clients for Unix

NTP is important, it sets your system clock. A proper Unix machine with an ordinary network connection should be within 10ms of true time. The problem is the traditional software we use to do this, ntpd, is old and complicated and has had a lot of security problems. It also does way more than your typical server needs, supporting obscure protocols and funky hardware you’ll never access.

I think a modern Unix machine just needs a simple network only time setter. Poll the time from ~4 NTP servers, discipline the clock to ~10ms, implement leap seconds correctly. That’s about it. I’m on the fence about client-only; if it’s not a big deal to be a simple server, that’d be better. I’m also ignorant about security, the historical crypto stuff in ntpd is pretty woolly.

A lot of other people think there should be a simpler time settings, there’s a bunch of alternatives now.

  • chrony is the best alternative I know of. It seems to do time correctly, and it has some clever accommodations for running in difficult environments like a VM or on a machine like a laptop that’s asleep a lot of time.
  • NTPSec, a big effort to first simplify the old ntpd code, then port it to a safe language like Rust or Go. The project has some problems but they are getting ambitious work done. Keep an eye on it.
  • systemd-timesyncd is everywhere now thanks to systemd. It’s too simple though, really just an SNTP client, and can’t discipline the clock nearly accurately enough to be useful for good time.
  • ntimed, see the blog. This project was looking promising but seems to have stalled out.
  • openntpd, the OpenBSD rewrite of an NTP daemon. It has a lot of problems including good clock discipline and leap seconds and is not really suitable.
  • ntpd! The venerable classic. Despite the problems the bugs are being fixed and it’s still the daemon I suspect powers most of the world’s Unix machines.

Chrony has a very useful comparison of chrony, ntp, and openntpd. The Performance numbers at the bottom are what’s most interesting to me (those numbers are microseconds).

End of the day, I think ntpd is still a decent choice. Chrony looks like the best alternative. I don’t have experience with it to comment on. I have no way of knowing if it’s more secure than ntpd. It’s also in C and has had some security problems.

34″ ultrawide monitors: Asus vs Acer

I’ve had occasion to try out two fancy gaming monitors recently; the Asus ROG Swift PG348Q and the Acer Predator X34 bmiphz. They are nearly identical. Both are great. Buy whichever one is cheaper. Last few times I’ve looked one has been $1100 and one has been $1200. If it’s a coin flip, I think the Acer X34 is slightly better.

Both monitors have identical panels and specs, as you can see in this comparison. They’re both 3440 x 1440 monitors in a 34″ package (109 ppi), they both support NVidia GSync, they’re both IPS panels. They both have an “overclock” feature to run up to 100 fps. I think there’s no meaningful difference in the display. This one review found slightly better color fidelity in the Asus but given it’s the same panel I think that’s probably individual item variance or testing error, not a real thing. They sure look the same to me. The difference is in the extra electronics and details.

For electronics, they both have speakers that can be driven via USB, but the Asus PG348Q has absolute garbage 2W speakers whereas the Acer X34 has merely awful 7W speakers. Also the Acer is 100% better in that it has 4 USB outputs, not just 2. The Asus has slightly nicer buttons and OSD menu UI but you will use those things once at setup and never again.

I like the Acer stand better; it came preassembled and doesn’t have an unusable cable management feature. Also it’s not some ugly asymmetric weirdo thing like the Asus. Both monitors have stupid decorative LED lights shining down that you will immediately turn off. The Acer monitor has the word “PREDATOR” prominently on the front bezel which is sort of sinister, but it’s easy enough to ignore it or put some tape over the branding.

They’re great monitors. The 34″ 21:9 form factor is the first monitor big enough I haven’t felt any need to have a second monitor. The screen quality looks very good to me and I haven’t missed my old iMac screen at all. But I don’t have exacting color fidelity requirements. I will say both the Asus and Acer screens look a bit hot to me, even after fiddling with color calibration. They also both have suspiciously garish default color settings and weird “gaming modes” I don’t understand.

ConEmu + ubuntu on windows: bell

I’m pretty happy with how my Unix setup on Windows is working. But there’s one horrible thing; the awful bell sound in the terminal emulator. Every time I hit tab in bash to complete it plays a good old ASCII 0x7 BEL, and it’s some earth-farty three tone loud sound that is just awful.

The solution is simple; go to the volume mixer and set the volume for “Console Window Host” to 0. Now your shells won’t make any audible noise. Of any kind. Peace and quiet.

What I really wanted was to reconfigure the bell sound. PuTTY has a whole set of options for this. I think it’s not really possible though. ConEmu can’t or won’t do it, as the author angrily keeps telling users. Apparently his code isn’t playing the bell at all, it’s being passed through to a lower level Windows console handler of some sort. There is an option for intercepting the bell but it’s not working for me for some reason, at least not on Ubuntu-on-Windows. It does seem to work for msys.

Another option often suggested is to configure your Unix programs not to use a bell for alerts. You can set it in bash, and GNU readline, and vim, and less, and... that way lies madness.

It turns out the sound is actually being played by Microsoft’s software, somewhere deep in their version of Bash or WSL or something. And it’s apparently not configurable. But you can find it in the volume mixer and cut off its air supply.

God that sound was awful.

Keeping time, time, time,
In a sort of Runic rhyme,
To the tintinnabulation that so musically wells
From the bells, bells, bells, bells,
Bells, bells, bells --
From the jingling and the tinkling of the bells.

Update: the plot thickens. The sound that’s being played is supposed to be a honest-to-good beep, the one generated by the motherboard with its integrated trashy speaker. Not your fancy stereo sound system. Modern hardware doesn’t have speakers, and starting in Windows 7 there was a special “beep driver” written to intercept this low level beep system ability and replace it by playing a wav file.

The sound Windows 10 seems to be playing is the sound event “Critical Stop” which is set to play “Windows Foreground.wav”, that horrible sound. I replaced it with “Windows Ding” and it’s better.

Chrome: open links in new window

New computer, old problem, I want Chrome to open links in new windows, not a tab in some existing window that may be minimized or on another desktop. I fixed this on a Mac with AppleScript; in Windows it’s easier, you just have to modify a registry setting.

Long story short, you want to modify the Default key at HKEY_CLASSES_ROOT\ChromeHTML\shell\open\command to include the argument “-- new-window”.

This all reminds me I should set it up again so CapsLock searches Google. So far I’ve been putting off installing AutoHotkey. I can probably also use it to create some keys to change system volume and switch audio output devices.

Modern screen refresh: beyond 60hz

One of the fun things about my new gaming setup is it can render at frame rates other than 60Hz. I’ve now got it set up to run at 3440x1440@75 and it seems to be working well. Of course it won’t matter much for desktop work, but it does have an effect on game rendering. Can a human perceive it? Lots of folks say so, and this blind test confirms it.

The hardware I have is an NVidia GTX 1080 graphics card hooked to a Asus RoG Swift PG348Q display. It’s hooked up via DisplayPort 1.2, the 2009 standard. In theory there’s enough bandwidth to run 3840x2160@75, but for some reason my monitor only will show up to 60Hz unless I enable “overclocking”, where it will then display up to 100Hz. The overclocking didn’t work with the first decent quality cable I tried, but it did work with the cable included with the monitor.

The neat thing about this setup is it doesn’t have to be a constant 60Hz or 75Hz. The hardware all supports Adaptive Sync, a technology where the graphics card tells the LCD when a new frame is ready to be displayed. So games, etc can run at any speed; 20fps, 27fps, 60fps, 75fps and it displays without screen tearing. This is way better than the Vsync hack that we’ve been stuck with since the ancient days of CRTs. No more triple buffering required, no awkwardly being stuck with display rates that share common factors with the number 60, no tearing or stuttering. Just draw a frame when it’s ready.

gsync

Unfortunately this variable sync rate comes in two flavors, G-Sync and Freesync, and monitors seem to only one or the other. NVidia does G-Sync so that’s what I’m using, and fortunately the higher end monitors seem to favor G-Sync as well. G-Sync requires that an expensive NVidia scaler be installed in the monitor (and may not technically be DisplayPort Adaptive Sync at all.) Freesync is the open / cheaper standard DisplayPort, but only AMD video cards support it so far, and AMD is way behind. Hopefully this will all get better in a couple of years.

Indus Script

Fun article in The Verge about deciphering Indus Script using statistical methods. I used to play with this stuff with the Voynich manuscript. But that text is sort of a honeypot, a largely irrelevant medieval European one-off, and quite possibly a hoax. Indus Script matters, there’s thousands of unreadable objects with Indus writing on it. The Harappan civilization is important to human history and so little is known about it.

Mostly I just wanted to make a note that Indus Script was proposed for Unicode in 1999. About 250 code points. It’s still pending.

jbareham_170124_1415_getty_02

Capture.PNG

Unix environments for Windows

One thing I miss about my Mac is having a usable Unix environment. Now I have two on my Windows machine, with different significant flaws. MacOS isn’t a great Unix, but it’s perfectly adequate for basic stuff. And it’s really handy having tools like rsync and command line ssh around. Windows has its own command line world with the venerable CMD.EXE (DOS) and the newer PowerShell. But screw that, I want Unix. Here are options.

Ubuntu-on-Windows (WSL)

This is the new hotness from Microsoft and is very nice. It feels like a legitimate Ubuntu environment. Except so far it doesn’t support networked filesystems.

WSL sits as its own OS on top of the NT kernel, just like Windows is an OS on the NT kernel. There’s not a proper Linux kernel running, instead Microsoft has emulated the Linux kernel at the syscall interface. The userspace then runs stock Ubuntu, actual Ubuntu x64 binaries unmodified. It’s an impressive piece of work.

The drawback is not everything works. ping doesn’t work unless you run bash as Administrator. (Some docs I’ve read say ICMP isn’t implemented at all.) Filesystems are limited. USB drives don’t work. Network file shares don’t work. There’s no NFS support in the Linux image, nor is there FUSE support. The view of the underlying Windows filesystem (in /mnt/c) is a bit strange too, like I can’t see a proper view of my Desktop folder. In general stuff that works seems to work right, and the Microsoft team is moving fast in adding new features. I’m tempted to join Windows Insider just to start running betas, but I think I have to get a whole new Windows version, not just an upgrade to WSL.

There is an honest /sbin/init process running in WSL, PID 1, but its only child by default is the bash shell you start the thing with. So no init scripts / systemd running services. You can open multiple bash processes that can all see each other and share a filesystem. But if you close the last bash, you lose the whole WSL environment, which makes daemons a bit awkward.

Other names for this system are Windows Subsystem for Linux (aka WSL) and “Bash on Ubuntu on Windows”. Note these make for awkward search terms on Google.

Cygwin

The granddaddy of Unix emulation for Windows. I haven’t tried it in a few years, but I used to hate its package manager and its approach to Windows integration. Weird path names and environment. But it works pretty well and has a significant set of tools. MobaXterm bundles Cygwin in with an X server and terminal emulator.

msys2

The other venerable Unix option for Windows, some evolution of msys / msys2 / MinGW / mgwin32 / MinGW-w64. It has some Cygwin roots in it too, I’m not sure how much, but the mingw philosophy is to make things more like Windows and less like Unix. The result is a lighter weight Unix environment with some compromises. For instance symlinks aren’t supported because they wouldn’t work in Win32 apps. So instead creating a symlink makes a copy of the file, which is pretty damn broken but you can live with it. The crazy neat thing is the Unix programs like make are actually Windows executables like MAKE.EXE and will work fine in Windows, without bootstrapping a Unix environment. Handy for ssh.

There’s no visible init process, you just have a naked bash running according to ps, although its PPID shows as 1. Software is managed via pacman (as used in Arch Linux), there’s a large variety of packages and a toolchain for building your own. I’m not wild about the package and software versions and a bunch of basic stuff isn’t installed by default (like tar). Also some of the tools have idiosyncracies. And I have some problems like Ctrl-C not interrupting IO bound bash scripts. But it’s definitely a usable Linux environment, just not Ubuntu.

Git for Windows (aka msysGit)

This shows up as a recommended Unix option. It’s a tight, easy to install bash shell plus enough related utilities to run git. It is based on msys2, some of the history is here. It does not include much though, like there’s no rsync. And no compiler toolchain, no package manager for installing more stuff. It’s great for providing a git command line though.

Terminal window

Unix programs really want to be running in an xterm/vt100 emulator. There’s a bunch out there. I’m liking Cmder, which is an enhancement wrapper for ConEmu. mintty is another option, that’s what msys2 uses by default. wsltty is a customization of mintty for WSL. MobaXterm is also popular. Note that PuTTY/SecureCRT is not really needed any more. They are a combination of terminal emulator + ssh, but now you can just use a simple emulator plus OpenSSH command line. Still working on a good ssh-agent solution though.

History

As a historical footnote, WSL is not the first unmodified Ubuntu to run on Windows. There’s also andLinux, based on coLinux, a cooperative VM. There’s some other Unix-alike Windows options out there too, I think mostly abandoned. See also Interix and Windows Services for UNIX.

Windows 10 gripes

I’m now a week into switching from Mac to Windows and have mostly settled in. Here’s a list of gripes I have about the Windows experience. Compare to a similar post I wrote in 2011 when I switched to the Mac. Honestly mostly the Windows machine is fine and I think this change will take permanently. But you notice things when you try something new.

Operating system problems

Windows is actually not a bad operating system, the NT kernel is pretty good. But there’s still a lot of warts.

File paths are still broken in Windows. Stuff installs and writes files all over the filesystem: Program Files (two versions), root directory, various user directories. The fact that I need to know about a pathname like C:\Users\Nelson\AppData\Roaming\Sublime Text 2\Settings is terrible.

I have two GPUs: the motherboard and a fancy gaming card. It’s really unclear to me which GPU is used when. In theory I can use the motherboard plug but it still uses the card? I couldn’t make that work reliably, so I just used a plug on the card.

There’s no way to make Windows re-open programs you had open when you reboot and log in. And if you want a program to start when you log in, it’s a hideous process of opening one of two magic folders and creating and dragging shortcuts. Seriously, I have to make a shortcut and put it in C:\Users\Nelson\AppData\Roaming\Microsoft\Windows\Start Menu\Programs. That’s handy.

Legacy problems

It’s remarkable how 30 year old DOS software still works on Windows 10. But that legacy support comes at an increasing cost.

There’s an uncomfortable mix of Windows 7 and Windows 8 philosophy in Windows 10. For instance there’s two overlapping sets of system settings: Control Panel (Windows 7) vs Settings (Windows 10). Also there’s too many backup options. The Windows 10 things are better, but they aren’t complete so you need the legacy Windows 7 sometimes too.

Windows still comes in a 32 bit version! That’s nuts. Worse, applications are also distributed in both 32 bit and 64 bit builds. OMG why? I wonder how many users choose the right one? And they’re installed in separate folders. “Program Files (x86)” is a very awkward name for a folder. There’s uglier stuff hiding under the covers too, like file system redirection.

Windows 10 still expects DOS newlines in files. Files have both CR+LF to end a line, and tools like Notepad won’t display a file correctly if it only has LF like everyone else in the world. This continues to cause headaches when using Windows tools to edit Unix files.

UI problems

Windows 10 is ugly. MacOS is so calm and harmonious.

The biggest problem is the UI still seems designed for 75ppi screens. Modern LCDs are 100+ppi, so everything is too small. System tray icons are 16x16! A lot of apps default to 8 or 9 (points? pixels?). I get a headache from squinting and leaning close.

Microsoft has created display options to scale everything; 125% does look more or less the right size. But apparently every single app has to be smart about scalings; if they don’t, it goes blurry like it was up-sampled with a bicubic filter. Many apps are OK. But Electron apps like Slack and Discord have this problem right now, apparently a fix is on its way. Also Chrome up-scales all the images in a web page to 125% as well, which is entirely unacceptable and makes the scaling setting useless.

The fonts are ugly. They look spindly, thin. I’ve tried tweaking ClearType to make things better with not much success. Font rendering for CJK fonts is so bad a bunch of users have created alternate font renderers like MacType. But their installation is spooky and the English documentation is not great so I’m not using them.

So many apps play sound notifications. For instance, social apps like Adium and Discord love to make noise when people join/leave. You can turn these off in each app. But it’s hard to find which app is making noise. The Volume Mixer program will show you but the window is small and modal and not really practical to leave running all the time.

The default sound set in Windows 10 is goofy, too light and ethereal. I’m particularly missing a way to have a good clean beep sound for the BEL character in ttys.

The mouse scrolls backwards! This is actually Apple’s fault; they were the ones to reverse things in the first place. But now I’m used to it and switching back is annoying. There’s hacks to reverse it in Windows, but I’m soldiering on.

Mouse scrolling doesn’t feel good on Windows. The “scroll 3 lines at a time” hack in the driver seems dumb. And sometimes the wheel scrolls backwards at the end of a gesture, either through hardware flakiness or my fingers being inaccurate. Either way I never noticed a problem on a Mac.

It’s awkward that Windows uses Ctrl-C for copy and Unix uses it for terminate process. In general I prefer the Mac’s use of the Cmd key and wish Windows used Alt the same way. And don’t get me started on Windows’ apps love of Ctrl-Shift-Win-X type hotkeys.

Missing features

Here are some things from my Mac I miss on Windows.

I miss auto-correct for typos. I’m confused because this is built in to Windows 10, and does work for me in MSIE Edge. But it doesn’t work in Notepad, or in Chrome, or many other apps. Apparently Chrome does its own thing. Also autocorrect only works for UWP apps, ie new things. Notepad seems like a strange oversight.

I miss the MacOS/iOS way of entering “special characters”. Hold down the E key and instead of uselessly repeating the E, it pops up a little GUI for you to choose É or the like. Windows doesn’t really have this (I wonder if Apple has a patent?). The best alternative I’ve found is the Touch Keyboard, which has a similar UI with the mouse.

I miss the emacs editing keys in text areas, particularly Ctrl-E for end of line.

I miss Keychain. I didn’t use it much on the Mac, but having a central system for secrets is really smart. The specific thing I miss using is the SSH agent.

I miss iMessage. It was great getting my phone text messages on my desktop. Apple seems uninterested in opening iMessage to anyone else.

I miss having a brightness control for my monitor from software. There’s no volume hotkeys either. Actually I miss everything about how the iMac integrates display, etc in to the computer. I now have no webcam and no microphone. OTOH my new external monitor is lovely. Better be, it cost half as much as an iMac!

Good things

So those are the gripes. Here’s good things about the Windows switch.

Gaming. That was the #1 reason I switched back to Windows, I wanted to dip back into PC gaming. Apple is simply not competitive in desktop gaming, not in hardware and certainly not in software. Microsoft’s lock-in strategy with DirectX succeeded.

The hardware itself is better and faster. Apple has neglected the iMac line and fallen behind. The GPU is the main thing I have that a Mac can’t do. But it was also nice being able to build a machine with Kaby Lake parts the second week they were available retail. I was also surprised that it was relatively easy to spec a clean, quiet piece of hardware; that used to be a big PC drama. It wasn’t much cheaper than Apple hardware though, particularly when you consider the display.

Network file shares work better. I gave up on using SMB on my Mac when Apple dumped Samba for their own broken SMB implementation. Of course SMB is quite nice on Windows. NFS worked on the Mac but was awfully slow and didn’t include an authentication solution. SMB is grody but seems to work.

My Network printer just worked. I had to do literally zero setup; it was discovered and configured automatically. Not so lucky with the scanner though.

Ubuntu-on-Windows is shaping up to be a good Unix environment, certainly better than MacOS. Here’s a post about it.

 

 

River flow map

Via my friend Amit, I think someone has finally built the map I wanted so long ago. Rivers in the US colored by stream flow. I’m not quite sure what the data is, at least some of it must be models rather than measurements. But it’s good.

The map is at the NWS Enhanced Data Display. It’s some clunky Windows-GUI-in-Javascript thing. But the data is great! The layer we want is under “More Layers / Rivers / Nat. Water Model - Stream Flow”. I set the base map to ESRI Light Gray to see the river layer better.

Capture.PNG

New Windows gaming PC

After five years of running Macs I’m going to try Windows again. I only use the computer in front of me as a fancy terminal, web browsers and SSH sessions mostly. And gaming. But I’m not really using the OS as a real computer, so I can suffer with Windows. Also I’m fed up with a bunch of stuff related to Macs. MacOS is not a very good Unix, I went back to doing all my real work on Ubuntu last year. Mac gaming is just awful. And Apple has apparently abandoned the idea of updating iMac hardware.

Anyway, I ordered a PC. I went full max spec with brand new Kaby Lake parts because I intend to use this machine for 4+ years. Top end CPU, top end GPU, 16GB RAM, 500GB SSD, and some fancier cooling / quiet components. Here’s the parts list.

  • Motherboard:  Asus Z270-P
  • CPU: Intel Core i7-7700K 4.2GHz
  • GPU: EVGA 08G-P4-6286-KR NVIDIA Geforce GTX 1080 FTW
  • RAM: C769-V16B Corsair CMK16GX4M2B2800C14 16GB (2x8GB)
  • Drive: Samsung 960 EVO 500GB PCIe NVMe M.2 SSD
  • Power supply: Corsair CP-9020092-NA RMx RM750X 750W
  • Case: Fractal Design Define R5
  • CPU cooler: Noctua NH-D15S
  • Monitor: Asus ROG PG348Q 3440x1440

So far so good! The motherboard was a compromise, it doesn’t support SLI. The CPU and GPU are too far up on the price vs. performance curve but I was feeling spendy. The case is nice, it has sound baffling. The CPU cooler is absurdly huge; I don’t intend to overclock, but large = quiet.

Shopping for the monitor really made me appreciate what Apple has done with the iMac displays. It’s very hard to find something that quality for PC parts. I decided not to go with the 4k/5k/Retina high density displays, too expensive and no GPU can fill that many pixels in a game.

There’s some neat new things in PC hardware. The M.2 form factor for SSDs dispenses entirely with the history of hard drives, the SSD looks something like a RAM module. (Which begs the question; why are PC cases still so giant? Cooling.) And GPUs have a nice new feature called G-Sync or Freesync. For 20+ years we run the screen at 60Hz and hope the GPU can keep up with 60fps vsync interrupts. Now the GPU just renders frames as fast as it can and the LCD only updates when there’s a new frame to draw.

I had Central Computers build it for me, a local screwdriver shop. They did a great job on the quote and build process for $80 labor plus maybe a 10% markup on parts. The computer priced out about $2150, the monitor $1100. Expensive! But I use this literally all day every day, and like I said I don’t intend to upgrade for a long while.

 

Rendering 10M+ points from S3 to a map

Michal Migurski is working on a new project, rendering previews of OpenAddresses datasets in slippy maps. We’re using S3 to store stuff and trying for stateless servers. He just described the architecture plan to me, I’m writing it up here. He’s doing all the work, currently in a test git repo. The fun part is a FUSE file system for MBTiles on S3. Read on.

OpenAddresses is a collection of address data points. Big CSV files full of latitude, longitude, street name. We collect the data from government sources. Every time someone finds a new government source they create a pull request like this one for Luzern with metadata for the source; stuff like the URL and how to parse it into our format. Mike has some GitHub integration hooks that look at the pull request and renders a preview image of the data file. It looks cool, but it’s also a useful debugging tool. We’d like to transform that static preview image into a slippy map. Here’s how it’s going to work.

  1. GitHub integration hook: use Tippecanoe to boil down the address points into a tiled dataset. Write the resulting MBTiles file to S3 somewhere. Note this hook and processing is on a transient server that disappears once the processing is done.
  2. Web page: slippy map using Leaflet or the like to request OpenAddresses tiles and render the points in the browser.
  3. Tile server: persistent Flask server that uses TileStache to serve the MBTiles file to the web browser.
  4. Tile server: a FUSE filesystem that mounts the S3 MBTiles file and provides it to TileStache.

 

It’s that last step that’s particularly clever. Serving an MBTiles file locally is easy. But what do you do if your MBTiles file is on S3 somewhere? It might be quite large, 10 million points or 100 megabytes. But each map view only needs like 16 tiles or a megabyte of data. You’d rather not have to copy the whole thing from S3 first.

So instead of caching the whole file locally, Mike has written a simple read-only FUSE driver to remotely mount the S3 file. To normal Linux processes it just looks like a file, but behind the scenes read requests are being turned into HTTP Range-restricted requests to get the bytes and return them.

Why go through the hoops of FUSE? The challenge here is MBTiles are actually Sqlite databases, and Sqlite really wants to open an actual file down in the depths of its highly optimized C code. So we give it a file.

The big question here is performance. It seems to be OK on first testing! Sqlite should be pretty efficient about reading data. I’m a bit more concerned about llfuse, the Python FUSE driver framework Mike is using. It seems to have a single global lock so only one S3 read request can be active at a time, maybe per mounted MBTiles device. So this might not work so well; in practice multiple tile requests are happening in parallel, even for a single user looking at a single slippy map. But we don’t imagine many users so it may not be too bad.

 

League of Legends server IPs

Just writing this down so I don’t lose it. I haven’t verified these. But most of the old lists I’ve seen are no longer valid since Riot started doing its own peering.

  • NA - ping 104.160.131.3
  • EUW - ping 104.160.141.3
  • EUNE - ping 104.160.142.3
  • OCE - ping 104.160.156.1
  • LAN - ping 104.160.136.3

Source is this Reddit discussion about yet another ping checker. I wish Riot would build a small network diagnostic into the client, before a game starts. Many of these third party tools don’t measure round trip time correctly and none that I’ve seen measure packet loss.

Also I was curious so I just did an mtr to the NA address. Average response to the end is 92ms, which is about the same number the league reports as ping. Standard deviation is 12ms, best/worst is 73/140. That’s with ICMP probes, I don’t get responses from UDP probes.

Verizon tethering for real

I’m glad I did that tethering experiment; I had to use my cell phone for Internet in anger today after yet another local WISP outage. Big storm, power outages, but also some robustness problems in equipment and/or service. I do have sympathy, the ISP depends on $300 wireless devices installed in trees scattered all over the county.

Anyway my iPhone worked fine for tethering. I put it in an east-facing window. Only one or two dots of service, but my Mac through it was reliable and seemed fast. I didn’t measure but it felt 10Mbps fast, at least. I quickly forgot I was tethered.

Doing my ordinary daily routine my iMac alone seems to use about 100 MB / hour. Call it 1GB a day. My data plan is only 2GB, but with another 2GB carryover that’s good for 3-4 days before it costs money. Overage charges at Verizon are $15/GB, but you can also avoid overage by adjusting your data plan size; no switching cost and it’s retroactive for the whole month. The plan price is about $5/GB.

It’d be $135/month if I wanted to just buy 30GB a month. But I really use more like 100GB / month once you factor in other devices, discretionary downloads, etc. That’d be $450/month (!).

The plan flexibility makes Verizon a pretty good low cost backup option.

 

Overwatch netcode

I’ve been playing a lot of Overwatch, on PS4. It’s fun! Also it feels super responsive and reliable on the network, I almost never perceive lag. Blizzard is uniquely good at building games like this so it’s no surprise, but what are they doing to make an Internet game feel like real time?

This video from Blizzard developers is good info (but outdated; keep reading). It goes into detail into server prediction, client prediction, and perceived lag. I think they’re mostly doing what other games have in the past, but there’s a lot of choices and tradeoffs they make. One choice they say is new is they make the assumption that most clients have reliable, fast networking. That means they don’t need to buffer nearly as much. Specifically they say that with most games you may be buffered 4 ticks (or 80ms), but if they think your network is good they’ll buffer you just 1 tick (20ms), so it feels even more real time.

The server runs the simulation at 62.5Hz. When that video was posted, clients got network updates at 20.8Hz. In August they pushed an update so PC clients get updates at 62.5Hz. PS4 and XBone also got the faster tick rate on September 13. The rate is adaptive, so your client will drop down if you have low bandwidth.

The game is a UDP protocol. I’m not sure about bandwidth usage. Back in the 20.8Hz days this post claimed it’s about 60-100Kbps in both directions. So maybe triple that? Bandwidth consumption was the reason Blizzard originally went with the lower tick rate.

I’m really curious why it’s 62.5Hz and not the obvious 60Hz. Maybe you want the network updates to be just a bit faster than the screen updates for smoothness?

For comparison, League of Legends runs at 30 Hz on the server. I’m not sure about the network / client update rate, it may be the same. CS:GO is 64Hz (or even 128Hz).

Internet in the mud

This is what happens when my Ubiquiti wi-fi antenna outside falls off its mast into the mud

The network was surprisingly useful in the bad period. I didn’t really notice for basic web stuff, although I did notice video streaming was unreliable. The main thing I could measure was my ping time to the antenna (as measured by mtr) had a standard deviation of 28ms. 5% packet loss too. So something was wrong, but the hardware handled it robustly. What’s with the delayed pings, btw, is there some retransmit logic involved somewhere? In the wireless devices?

“In the mud”, btw, mostly meant on the ground. Fortunately it fell facing my house. But with little or no line of sight to the house. Mind you the other antenna in the house is literally behind a wall; it works well enough I’ve never bothered to mount it in the window.

Local stream flows: Yuba and Deer Creek

We’re about to get a lot of rain, and like every year I get interested in the local rivers and waterflow around Grass Valley, CA in Nevada County. Here’s some rough notes and resources.

Yuba River, particularly the South Fork

  • Yuba River at Marysville: flow history and forecast. This is below Englebright Dam, so includes the choices of how much water they’re releasing there. But is excellent data from NOAA.
  • South Yuba at Highway 49: flow history, forecast. From Dreamflows.
  • Yuba River at Jones Bar: flow history. From CDEC. This is either the exact same sensor Dreamflows is showing at Highway 49 or else is a mile downstream.
  • Yuba River flow history along the whole river. This is California state data (CDEC) and the website has lots of neat stuff.
  • Watershed map
  • Wild and Scenic River Act protects the river from Lang Crossing to Bridgeport. This is the much loved stretch of scenic river with lots of swimming holes, etc.
  • BLM management plan

Deer Creek in Nevada County

This ArcGIS map of World Hydro Reference Overlay does a good job showing labelled rivers against towns and major roads.

Where did source code merging come from?

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 article seemed 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, .

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”.

Update 2024

Interesting discussion about the 50th anniversary of diff which resulted in Rob Pike getting a comment from Doug McIlroy

‘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”.’