Some Bits: Nelson's log

64 posts in 2018

PC gamepads: DirectInput vs XInput

I bought a crappy cheap game controller to use for a few weeks and ran into the total compatibility nightmare which is Windows game controllers.

Long story short, there’s two completely separate APIs. DirectInput and XInput. Old controllers (like my cheap PS3 knockoff) used DirectInput. Starting ~2005 Microsoft introduced XInput as a new API with better support for advanced controllers. It had drawbacks and some game controllers were slow to adopt it. Around 2011 Microsoft deprecated DirectInput, so everyone’s supposed to use XInput now. Despite that you can still buy new controllers that do DirectInput. Some controllers have a hardware switch to toggle modes.

What’s dumb is not all games still support DirectInput. (Looking at you, Dead Souls). Worse, Microsoft’s drivers don’t support some compatibility shims so a DirectInput device can be used via the XInput API. So you have to do something third party if you have an old DirectInput controller and want it to work with XInput. There’s three options I found:

x360ce is a thing that emulates an X360 controller and looks like an XInput driver but takes its input from DirectInput devices. I’m not sure it really is a driver, the hack includes its own XInput.dll you have to drop in to some games’ folders to fake it out. I didn’t try this, but it’s the usual old school gamer recommendation for solving this problem. It seems very flexible and hacker friendly. There’s newer binary builds on the GitHub page.

ScpToolkit is similar to x360ce, but emulates a Playstation controller. I did actually install this and found it didn’t work and uninstalling was spooky. I ended up using Windows’ rollback to remove it.

Steam Big Picture mode also includes an XInput emulator that seems to work well. I can’t find official docs for it and its confusing, but the Internet is full of badly written guides and videos on how to use it. This is what I ended up using. Setup is a bit fiddly; for awhile I was telling it to be “Generic” and it was sort of working but what I really wanted was “Playstation”. I’m still not clear if that means it’s emulating a Playstation controller, or if it is using this cheap controller I bought thinking it is a Playstation controller. Or both. Whatever, it seems to work.

mosh behind NAT

I wanted to give mosh a try to see if the fancier remote shell program would work around this crazy Berlin Internet that terminates idle connections in < 5 minutes.

Turns out mosh doesn’t work if the server you are connected to is behind NAT. It relies not only on connecting to TCP:22 for the ssh, but also a second server running on UDP:60001 or nearby to do its magic. Worse, the mosh server doesn’t seem to have any support for NAT traversal. The advice of the docs is “set up static port forwards for these 1000 ports”. I appreciate the optimism about a pure 1990s Internet, but in the modern environment that’s ridiculous.

The solution I found is to use this 2012 shell script. It’s a wrapper for mosh-server that uses miniupnpc first to request the port be forwarded. Seems to work for me with my Ubiquiti router. You arrange for it to be invoked by putting the server wrapper script in your PATH on the server, then doing “mosh -server=mosh-server-upnp” on the client you’re connecting from to cause it to be invoked.

There’s also this recent Ruby script which might be a better choice, but I couldn’t be bothered to look up how to install Ruby scripts.


Kiwix: Wikipedia offline

Just a shout-out to Kiwix, the software plus database for reading Wikipedia offline. It’s incredibly helpful to have on your cell phone when you’re traveling and don’t have a data plan. Also nice just to have lightning-fast browsing of Wikipedia. They now have clients for iOS, Android, Windows, MacOS, and Linux.

You have to download the data separately. Their ZIM format seems well thought out, compressed tight and general purpose enough you can get other document collections like Stack Overflow posts, TED talks, etc. English Wikipedia is an enormous 35Gb, 80Gb if you get images too. There are various Wikipedia subsets but no “top articles” opton I see. (Be careful not to download a Simple English version by accident.)

The most interesting thing to me is Kiwix is now partnered with Wikimedia Foundation. A nice cash infusion, but also gives Kiwix some legitimacy. I’m hoping that gives a second wind to the editorial project to produce a Wikipedia subset that’s smaller and well selected to be sufficient.

There are some other offline Wikipedia readers on the Apple app store. I used Wiki Offline for years but the company that produced that seems to have disappeared (again). There’s also Minipedia which does have a nice small subset you can download. I think all of these alternatives found it hard to produce regular updates with the most recent Wikipedia content. Kiwix seems to be doing quarterly releases.


x265 transcoding

I continue to re-encode video I get into x265. It’s much smaller, which helps both with storage and bandwidth. And it looks fine to my tin eye.

My script has evolved over time. This is what I do now:

ffmpeg -i “$1” -map 0 -c copy -c:v libx265 “${1%.*} x265.mkv”

In theory this leaves all the audio and subtitles alone, just copies them, but re-encodes the video in x265 with default settings.

I was in a hurry today and so got fancy with resizing the video to 360p and using a faster / less accurate encoding setting.

ffmpeg -i “$1” -map 0 -c copy -vf scale=-1:360 -c:v libx265 -preset faster “${1%.*} x265.mkv”

Quality definitely suffers for this, but I can encode at 3-4x playback speed on my CPU this way.

Linux: adding a drive, UUIDs

I replaced a 7 year old drive in my Linux server. The drive had been complaining about bad blocks in SMART forever (which still mystifies me; drives should be able to just remap those). But I was seeing other signs the drive might be failing, so better safe than sorry.

The thing that made this complicated is I wanted to be sure I understood how device names worked so I didn’t screw up which drive was mounted where. Old school names like /dev/sdb1 seem fine, but those names change if you remove drives, add new ones, etc. So I read up and learned the new hotness is to mount drives by naming their UUID, some stable unique string based on the drive partition’s geometry. /etc/fstab will take a UUID in the first column instead of a device name and happily mount it for you. That’s it, pretty simple. In particular udev is not involved and there are no symlinks required anywhere. I have no idea how mount finds the device named by UUID but it works, so I’m happy to remain ignorant.

I replaced the old 7200 RPM WD Blue with a 5400 RPM WD Blue. That’s kind of a cheap drive for a Linux server but I’m only using it as a backup volume. I keep being tempted to get an SSD for the main system volume.

Here’s the steps I followed for the new drive, mostly following this guide.

lshw -C disk: find the new hard drive. Easiest way is to match it via serial number, or other characteristics like size and model name. My new disk got named /dev/sdb, which awkwardly was what the disk I just took out was named too.

smartctl --smart=on /dev/sdb: turn on SMART for the disk. Honestly I don’t exactly know what this does but it seems like a good idea.

fdisk /dev/sdb: partition the disk. fdisk is the old school MBR partitioning, which is limited to 2TB maximum. My disk is 2TB so that’s OK. Newer systems use GPT (an EFI thing) and parted. I just made one large partition for the whole disk.

mkfs -t ext4 /dev/sdb1: make the filesystem. There’s some options here you could consider setting to get a bit more disk space or add checksumming to metadata but I stuck with the defaults. Fun fact: I was taught in 1990 to print out the list of superblock backups because if the disk failed it was the only way you were going to find them backup block IDs. I assume recovery tools have improved in the last 28 years. (Or more realistically, that the disk will be a lost cause.)

blkid | grep sdb1: find the UUID for the new partition

fstab: edit fstab to mount the new disk named by UUID.

All very easy really.


Flickr exports, fixup tool plan

Ahead of the Great Deletion, Flickr has a decent export tool built in to the user settings page. You click the export button, wait a day or two for an email, and then get some ZIP files to download.

I posted a little summary of what’s in the exports on Metafilter. Long story short, I think it’s pretty much all the data and metadata Flickr has. Here’s an expanded version of it:

Photos

  • 4 zip files are my photos
  • Photos are in JPG format with EXIF tags. I’m not positive but I believe these are the original bits I uploaded from my camera, or something similar. There is a lot of EXIF data intact.
  • Filenames are the title of the photo (downcased) plus the photo’s Flickr ID
  • File timestamps are bogus dates in 2013/2014

Metadata

  •  1 zip file with a bunch of JSON files
  • Most of the JSON files are one file per photo that includes Flickr metadata. Photo title, description, time, tags, geotags, comments on the photo, etc.
  • Several other JSON files with things like all the comments I’ve made, JSON data for my photo albums (a collection of photos), etc

Edit: a caveat on the geo top level field. This seems to be set even if the photo was never properly geotagged via the Flickr map tool or with EXIF tags. It looks like it’s set to the location of the computer that uploaded the photo?!

Conversion tool plan

I’m not aware of any tools that do much with this Flickr metadata, but I haven’t looked hard. I’ve considered writing my own minimal one with an eye towards extracting all the most important metadata from the JSON and stuffing it in EXIF tags. Ideally the resulting JPG files would then look reasonable when imported into Google Photos and/or Lightroom. Some specifics:

  • Set the JPG filename from the JSON photo title more nicely than Flickr did
  • Set the JPG file timestamp to the creation date in the EXIF data. If there is no EXIF timestamp, then take something from the Flickr JSON.
  • Insert Flickr’s JSON geotags from the photo into an EXIF geotag (if one doesn’t exist). I geocoded a bunch of photos by hand in Flickr, I’d really like to preserve that data
  • Insert Flickr’s JSON name and description tags into the EXIF in appropriate textual fields.
  • Insert Flickr’s tags into the EXIF; is there an appropriate field?
  • Capture Flickr comments from the JSON into the EXIF?
  • Flickr JSON has a “people” tag but I don’t think I’ve ever used it.

Update

A year later I never got around to doing this “right”. Instead I just took the _o original files from the Flickr export and renamed them a bit, turning the dash and underscores into spaces. Then uploaded. Google Photos seems to have done an OK job fishing dates, geotags, and some sort of descriptions out of whatever EXIF data Flickr had given me. I’m sure I lost any Flickr-specific data, like hand geocoded Flickr photos, comments, etc. Also there’s some problem with “photos already in Google Photos”, I’m not sure if it picked up any extra metadata. But mostly I got my pictures online.

Logs of Lag outage

Oh boy did I screw up. Back on September 1 I pushed a tiny change to Logs of Lag, an old service I still run for League of Legends players. It was such a simple change, just adding an HTML link, so I didn’t test it carefully. Turns out I made that change on top of the master branch which had some other changes I’d committed but never tested or deployed back in 2015, and that new-but-old code didn’t work. The site’s been broken for 7 weeks now and I only found out when a user wrote me.

I love this commit comment past-me wrote:

Potentially breaking change: webapp use new stats. This change has not been tested manually, hence the warning in deploy.sh

I did read the commit log before pushing again, but apparently I didn’t read back far enough. Also I didn’t use my deploy script to deploy the server. Talk about shooting yourself in the foot. I even have a tiny bit of monitoring on the service but it didn’t show this kind of error, not that I pay attention to the monitor anyway.

The real problem is that I’ve abandoned this project; I haven’t done real development on it in 4 years. It’s kinda broken now too as the file format the code parsers has changed over time and I haven’t kept up. I’m now 100% fed up with League of Legends and Riot Games, given how sexist and awful that company is. So I have no motivation to do more. But the tool is still useful so I’ve tried to keep it online. (Past me did one thing right: the site is mostly just running static files, so it’s not hard to keep running.)

The site doesn’t get a lot of usage, my estimate last year was 50-100 unique users a day with about ~450 uses of the tool a day. Here’s a graph of the rate of usage; you can see an organic falloff over the whole year, then it falls sharply Sep 1 when I broke the site. I wonder if it will recover.

logsoflag2-year.png

PS4 6.02: more external storage woes

As I wrote in an earlier post, on a PS4 there’s no way to make a copy of a game’s download files to an external drive. You can move the files to a drive but they are then deleted from the source. Which is a huge PITA when the game requires a 90 GB download.

But it gets better. If you plug an external drive with a copy of a game into a PS4 that already has a copy of that game, the software freaks out. It insists you delete one of the two copies before you can use the external drive. There’s no way to tell it to ignore the duplicate to, say, let you get at some other game on the external drive. You must delete first.

So not only can you not create copies of games, but if you screw up you’ll be forced to delete a copy you downloaded. Argh!

(I reiterate; none of this is about copy protection; the PS4 online DRM will prevent you from playing the game if your login doesn’t have a license for it, whether you have a copy on the drive or not.)

PS: the external drive copying is awfully slow. a 50GB game image is taking 18 minutes, or about 50 MB/s. That’s just about USB 2.0 speeds. The drive, cable, and the PS4 itself are all supposed to support USB 3.0. Maybe it’s the spinning drive speed limiting things.

Yet more Python ORMs

I continue to fail to use ORMs with Python. They’re just so complicated and mysterious. But maybe that’s really just SQLAlchemy and I should look elsewhere.

PeeWee popped up on my radar recently, an ORM explicitly designed to be small and simple. It looks pretty good. Also have heard a couple of people mentioning PonyORM recently. It seems far too magic.

Going even simpler, I should circle back and spend more time with requests and/or dataset. They’re not even really ORMs, just convenience wrappers for database rows, and that seems fine by me. Still bugs me they both depend on SQLAlchemy even if the actual interaction is minimal.

 

PS4 5.50+ USB hard drive, copying games

A tale of failures. I wanted to copy a PS4 game I have off the internal hard drive onto a USB drive, so I could copy it onto a second console instead of redownloading 60GB+ worth of stuff. This turns out to be impossible.

Since version 5.50 the PS4 has gotten a lot friendlier about supporting USB drives. Among other things you can relatively easily plug in a USB drive and copy user data (like game saves) to and from it. The PS4 will do this with any exFAT or FAT32 disc, like your garden variety flash drive.

You can also move a game from the internal hard drive to a USB. Key point there: move, not copy. Copy is explicitly not allowed. You can only move a game to disc if the disc is formatted as “extended storage” for the PS4. I thought I’d be clever and move the game to an external drive, make a clone, then move it back. But you can’t do that easily. The extended storage volume doesn’t even have a meaningful partition table, no filesystem I can mount. I suppose I could make a block level clone of the disk but that’s too much trouble. (It’s probably just some slightly bent version of a standard FreeBSD or Windows filesystem, but I’m not going to waste time researching that.)

One last option PS4 supports is to back up your whole console to an external disc, then restore it to a different console. You can also clone one PS4 to another directly over a LAN. However in both cases the destination PS4 gets entirely wiped and reconfigured, it’s not suitable for making a copy of a game.

The stupid thing about all this is Sony probably still thinks it’s doing some useful copy protection. It’s not, the copy protection is entirely keyed now to your online account. They’re just making it awkward for power users to do reasonable things.

 

Linux I/O schedulers

My Linux server is mostly idle, but every few hours I run a backup and then the disks get very busy. I’m also trying to rebuild a corrupted Duplicati database now, a second heavy I/O load. If both run at once the system does not run very well. Worse, interactive performance it terrible; like 30 seconds to log in and get a shell.

I think a fix for this is changing the Linux I/O schedule. I checked and all my hard drives were set to the deadline scheduler. I changed them to CFQ and interactive performance seems better, although I didn’t test carefully.

I’m not clear why CFQ isn’t something you’d just use all the time. I guess there’s some overhead associated with it vs. noop but I have to think it’s not very much under normal workloads. Deadline seems like a bad idea unless you’re in a very special environment. But I don’t really understand this stuff.

Zip codes vs census tracts

A lot of digital maps use zip codes as a binning feature. Election maps, property value maps, pollution maps. But while zip codes are convenient and familiar there’s a much better set of polygons for mapping most US data: census tracts. Zip codes are pretty unusual polygons(*), drawn mostly to make the process of mail sorting and delivery simpler. They are quite arbitrary. Census tracts are lovingly and carefully drawn to respect demographic and political reality.

I have a great example of the difference: River Oaks in Houston, one of the wealthiest neighborhoods in America. It’s the place where Saudi princes buy a 10,000 square foot house and glass in the backyard so they have air conditioning. Also plenty of local Houston money, mostly old money.

But you’d never know it looking at zip code averages. Because River Oaks shares 77019 with a bunch of people who live east of Shepherd, in a significantly denser, less wealthy, more diverse neighborhood. It also includes big chunks of the Fourth Ward which used to be quite a poor neighborhood and was recently redeveloped. By contrast River Oaks is almost perfectly described by census tracts 4112 and 4114. (Not exactly; the chunk in the SW of 4114 is not technically River Oaks, nor is it in 77019, but demographically it’s quite similar to the rest of 4114.)

Census tracts are part of a hierarchy of census polygons. Census tracts aim to have about 4000 people in them, (zip codes average 8000 people, but vary greatly). Block groups are smaller and have ~1500 people each. Census blocks are the smallest division, about 40 blocks per group, but unlike census tracts they are highly variable (in terms of statistical demographics). There are 11M census blocks in the US, although nearly half of them are uninhabited.

Census tracts are frequently named by 4 digit numbers like 4112 or 4114, with a county name or something else to disambiguate them. But some tracts have numbers with decimals or other complicating factors, like 32 or 204.01. (I believe canonically census tracts are named with 6 digit numbers, with the decimal and leading zeros frequently omitted).

FIPS codes are the larger naming scheme; the full name of 4112 is sometimes given as 48201411200. 48 is Texas, 201 is Harris County, 4112 the census tract, and the 00 is the block group. Census blocks get their own 4 digit number at the end, making for a full 15 digit code to name the most precise polygon.

(*) technically speaking zip codes are actually just lists of points. The polygons are properly called zip code tabulation areas and there are some important differences.

Ubuntu 18, Samba, and ntlmv1

I have a security camera that writes videos to my Ubuntu 18 machine, mounting the disk via Samba. it stopped working recently. Turns out Bionic Beaver shipped a tiny little security patch which includes this:

  * SECURITY UPDATE: Weak authentication protocol allowed
    - debian/patches/CVE-2018-1139-*.patch: Do not allow ntlmv1 over SMB1
      and add tests.
    - CVE-2018-1139

They’re not wrong to change this; ntlmv1 is a terrible ancient insecure authentication protocol. But it’s just the kind of thing some old firmware is likely to require, like my camera.

The simple workaround is to restore ntlmv1 by adding this to the smb.conf:

ntlm auth = yes

Don’t do this if you don’t trust your network. For that matter don’t run Samba at all if you don’t trust your network. I mean it’s supposed to work, but I sure wouldn’t.

 

Munin and NVMe SSD drives

Summary: Munin seems to have no support for monitoring the life of NVMe SSD drives.

NVM Express is the new hotness for SSD drives.  Those are the little M.2 cards you plug in that are actually hard drives, but with more direct access to the system bus than the usual SATA interface. They are fast and compact and great. I’d like to use Munin to graph some stats on my drives, to see how busy they are and how close they are to wearing out.

Munin has an excellent SMART plugin for monitoring important drive health measures. Unfortunately it doesn’t work for NVMe drives. smartctl only started supporting NVMe drives at all last year, and they did so with a brand new output format that looks totally different from the old tables that smartctl knows how to parse.

Update: see smartctlcvt for a solution.

It’d be simple enough to make a new plugin to grab data from the new format. Main thing holding me back is I don’t really understand what all the values in the SMART report really mean. I think “Available Spare” and “Data Units Written” are probably the most interesting fields along with the various error columns, but I dunno.

Here’s an example output

 # smartctl -A /dev/nvme0
smartctl 6.6 2016-05-31 r4324 [x86_64-linux-4.15.0-23-generic] (local build)
Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF SMART DATA SECTION ===
SMART/Health Information (NVMe Log 0x02, NSID 0xffffffff)
Critical Warning:                   0x00
Temperature:                        33 Celsius
Available Spare:                    100%
Available Spare Threshold:          10%
Percentage Used:                    0%
Data Units Read:                    16,973 [8.69 GB]
Data Units Written:                 488,334 [250 GB]
Host Read Commands:                 463,571
Host Write Commands:                16,861,501
Controller Busy Time:               19
Power Cycles:                       13
Power On Hours:                     80
Unsafe Shutdowns:                   1
Media and Data Integrity Errors:    0
Error Information Log Entries:      0
Warning  Comp. Temperature Time:    0
Critical Comp. Temperature Time:    0
Temperature Sensor 1:               33 Celsius
Temperature Sensor 2:               33 Celsius

Firefox Sync

Firefox Sync is nice. Nice enough I’ve switched to using Firefox on iOS. Almost entirely for the ability to send a tab to my mobile device. This happens to me all the time; I have something interesting or useful on my desktop browser and I want to look at it on my iPhone. Now instead of emailing myself a URL awkwardly I can just send the tab to the iPhone and it’s done.

The other feature I like is the ability to open URLs that are or were recently open in another browser. That way I can grab something of interest on my iPhone even if I forgot to send it from the other computer. This feature’s less useful to me since I tend not to leave tabs open. Also the sync seems to be minutes out of date, so sometimes what I want isn’t available.

Firefox Sync shares a lot of state: bookmarks, saved passwords, browser history, installed addons, etc. It all seems pretty useful and it all seems to work well.

Update: by default it syncs every 15 minutes. You can configure it.

Twitter streaming API workarounds: lists and following

Twitter is shutting off their streaming API. After months of warning, the actual deadline is in three days, Thursday the 16th. If you were using the streaming API to follow at most a few thousand accounts, there’s a workaround: Twitter lists.

The idea is you create a Twitter list containing all the accounts you want to follow. Then you poll lists/statuses for the timeline of tweets. Polling isn’t awesome but the default rate limit is once a second, so it’s not too bad. Twitter lists are limited to 5000 accounts, so if you need more than that this won’t work (but consider multiple lists).

The main thing you’ll lose this way is replies; Twitter lists don’t include replies not to list members. (Or maybe not to people you follow, I’m confused on that point.) But otherwise it seems to work. If you’re working with old Twitter code be sure you understand about extended_tweets; you almost certainly want to be getting them.

One wrinkle: creating a list of thousands of people isn’t easy. It looked to me like there was a hard limit of adding 1000 users to a list every day. Also maybe a soft limit of hundreds in a short period of time.

The other option I tried was instead of a list, create an account and follow the users of interest. Then look at their home timeline. This doesn’t work as well for various reasons. First, Twitter mucks with a home timeline more than a list timeline, more risk of reordering and stuff. Also the rate limit is lower (once a minute). Finally it seems harder to quickly follow thousands of new accounts, I ran into more draconian rate limits.

One more wrinkle: listing or following a user notifies them you are interested in them. Following people via the streaming API was completely passive, now users have a hint they’re being watched. It’s not a big deal but some users may choose to block you when they get listed / followed.

Standard Notes

I’ve been using SimpleNote for a long time. It’s a great simple cloud-synced notepad and a very nice free service Automattic maintains. Type some text at it and it remembers, you can access it with a nice desktop app or a nice mobile app or any website. The problem is SimpleNote isn’t built for much security. They store your notes in plaintext on their servers. That’s probably OK but if they ever have a security breach we’re in trouble. And oddly, my notes turn out to have some pretty secure content in them. In particular I often temporarily save a password or SSH key to them. Not permanently, but with undo it’s not clear you can ever really delete anything.

Enter Standard Notes. It looks to be very similar to SimpleNote in concept, but it has end-to-end encryption built in, so it’s more secure. (Also you can never recover your notes if you lose your password.) It’s free and open sourceish, looks like they have a Freemium business model where you pay for extra features like fancier editors with formatting, reskinning the UI, etc.

Notes are tagged; in that way it’s a little like Notational Velocity / nvAlt.

The Windows desktop app is Electron and looks to share code with the web interface. The UI is a bit funky, it does not look like a native app, but it’s totally usable. Not sure how the iPhone app is implemented (I’m guessing Javascript as well) but it looks fine.

Trying it out is easy, there’s an import from SimpleNote that works OK, main wrinkle is all my deleted SimpleNotes showed up again.

I love the voice of their help page. Someone very opinionated (in a good way) is building this product. I particularly like this quote:

Your data is a liability to us, not an asset.

 

Door King 1812 programming notes

I have a gate at my house. It’s driven by a LiftMaster Miracle 1 motor unit, which in turn is commanded by a Door King 1812 gate controller. This was all installed around 2000 but the design probably predates that. I got deep into the setup of these things trying to make the gate do what I want, and failed. Mostly because I don’t understand the Miracle 1.

The Door King 1812 is still sold today, still supported. The manual is here, I reference it by section number (like 2.2.1 for master code).

Programming it seems daunting. I tried at first to get it working using the PC software and a modem, but that requires a monthly $$ subscription to use and seemed pretty rickety anyway. Instead I used the touchtone programming interface. This is overwhelming at first, but really not so hard.

The key thing here is the gate controller is wired into my phone line. It’s listening in-line and can be programmed to work as an intercom using the phone wires, to synthesize a ring on my phone line, and even to answer and make phone calls. I talk to the controller via my phone; just pick up and press *7 at the dialtone to get the gate’s attention and it answers with a beep.

One wrinkle: some steps require you press 0 and # simultaneously to end programming. (I write this as 0-#). I found neither phone keypad I have is able to send two tones at once. I ended up having to use the gate keypad to program things so I could enter 0-#.

Here’s some stuff I learned:

Master code. You need this to do anything else. Old ones had a default of 9999, newer ones have a default of the last 4 digits of the serial number. Someone had written mine down on a sticker inside the keypad box. See 2.2.1 for setting a new master code; you open the keypad box and flip a switch. I’ll use “xxxx” to stand in for this code later.

Attention. The gate listens for a code, *7 by default. It beeps when it responds. All commands to the gate start with that. See 2.2.2 to change the number 7. You can inspect the state of the gate relays with this attention command, as described in 4.11. After a brief delay the gate will beep at you to tell you which relays are open.

Basic operation from house phone. *7 9 to open the gate. In detail: the controller is programmed to respond to simple commands on digits 1-9, described in 4.13. *7 gets the gate’s attention, and then it’s sent the command 9. These commands are called “tone open numbers” in the manual and their programming is explained in 2.3.2.

Basic operation from keypad. #zzzz to run an entry code program, described in 4.4. Typically this is something to open the gate. You program codes (like #1234) and give them to friends who you want to get in.

Program strike time. Described in 2.3.1. Various commands tell a relay to operate for N seconds before turning off again. That’s how you have it open the gate for N seconds, then close it again automatically. I believe my gate was programmed to do this for 2 seconds (much less than the time it takes to swing the gate). I think this is the way the Door King signals the motor controller; a short pulse on the relay.

Program tone open number. Described in 4.13 and 2.3.2. *7 *05xxxx 1* 987#* 0-#. This is super complicated. I’m telling relay 1 that when I press 9 I want “momentary activation” for the strike time, when I press 8 I want “hold open”, when I press 7 I want it to deactivate, and nothing for the 4th command (#).

I’ll be honest and say I’m confused about what I ended up with. *78 seems to cause the gate to hold open. Then *78 again will cause it to hold closed. *77 doesn’t do anything?

Program entry codes. Described in 2.6.1, see 4.5 for definitions of “momentary” and “hold”. I entered *7 *02xxxx 18* zzzz* 0-#. That sets up the new entry code zzzz to location 18, a “hold” location. That should cause it to hold the gate open when #zzzz is entered, then close when #zzzz is entered again. If I’d set it to a “momentary” location again like the number 11 then it would only open the gate for the strike time, then close it again.

Security hardening. The controller can answer and make phone calls. I don’t want that. Sections 2.3.5, 2.5.1, 2.5.3 all seem relevant things to turn off.

Garage door remote. My gate also comes with garage door buttons to open. The Door King doesn’t have anything to do with this; it’s wired directly to the Miracle 1.

There’s more the gate controller can do. You can set it so some codes only work at certain times, or certain days. You can program it to accept and make calls. Etc etc. I didn’t do any of that.

The relay and the Miracle 1 motor. This is key to the whole programming. All the Door King is doing is turning a relay off and on. What does that mean to the motor?

I got lost here. The Miracle 1 isn’t really programmable, but does have a few configurable options. I believe ours was configured so that a signal from the relay means “open the gate, wait 45 seconds, close the gate again”. What I want is a signal to open the gate, then a second signal to close it again. The Miracle 1 manual suggests that’s not really possible but I know it used to work that way, so it must be. But in the process of tinkering with it I got the gate in a state where I couldn’t even make it open reliably. It may be that something’s wrong with the limit switches or the power supply. I got fed up and quit.

Two factor authentication overview

Bit of kerfuffle this week around Reddit, which had a security breach despite having two factor authentication enabled. Some basic introductory notes for folks wondering what’s going on.

  • Two-Factor authentication (or 2FA) is any login protocol that requires a second thing for logging in besides your password. Passwords are a terrible form of security, you should use 2FA for any account you care about. Definitely your email account and your bank. Also whatever is important in your job: your Amazon Web Services account, or your Twitter account, or whatever.
  • SMS (text messages) are often used as the second factor in 2FA: the website text messages you a one-time code you type in to the login page. You give the website your cell phone number to set it up. But SMS is not secure; it’s far too easy to convince a mobile phone company to hijack a cell phone number. SMS is better than no 2FA, but if you have any other option at all don’t use SMS. Note many accounts have a backdoor SMS recovery option that you only use if you lost your password; these are also insecure and seem to be what tripped up Reddit. SMS 2FA is also vulnerable to phishing and MITM attacks.
  • TOTP / HOTP, one-time passwords, are also a common 2FA option and are pretty good. App generates codes every minute / every login and you type them into the page. You set it up by scanning a QRCode when you set up the login, then run an app like Google Authenticator, Authy, or 1Password to generate a number that you type in to log in. It’s what I use in practice. Not positive how safe it is to use 1Password to store both passwords and this second factor in the same system, so mostly I don’t use that. These are still vulnerable to phishing and MITM attacks.
  • U2F / Yubikey is the new hotness in 2FA. You have a physical device, a little USB key, and a special protocol that lets web sites authenticate through your browser to the key itself. The hardware is designed to be secure. Also the second factor that’s used is phishing resistant. Yubikeys are quite common in the tech industry but does require software support that’s not available everywhere.
  • Push-based 2FA, where you have a custom app on your phone that pops up a confirmation dialog. You press a single button to approve the login and you’re done. It’s very convenient. I first saw this in the Blizzard Authenticator. Duo Push is a product you can use to implement push-based 2FA on your own sites. Apple’s iCloud 2FA also does a variety of push 2FA along with also requiring you type in a code. I don’t know how secure push-based is but I’m guessing pretty good, at least the obvious phishing attacks won’t work.

tl;dr: use 2FA on important accounts. Avoid SMS if you can.

Using a modem in 2018

I’m wanting to program my Door King gate controller. It’s hooked into our phone line and can be programmed via touchtones or with a modem. So why not? I bought a modem. $16 for a USB 56kbps modem. I even made an unboxing video.

I plugged it in to my Windows 10 box and it was just recognized, no driver futzing at all. It even seems available for use for faxing and dialup. But that’s far too new-fangled, so I looked around and found that Tera Term still exists and can be used as serial port console software. Also found at least one dialup BBS online. A few half-remembered Hayes AT commands later and we have connection! Not sure why it only connects at 26400kbps, but I’ll take it.

Screenshot_1.png

 

Having a bit of trouble finding the modem to connect to it. Tera Term seems to think my modem is COM3 and worked first time I tried it. Windows Fax & Scan sometimes identifies a fax device, sometimes doesn’t. And the Door King software is not identifying any modems although I can manually tell it to use COM3.

Worse, the Door King software seems to require an account that I pay for in order to use the programming software. I got as far as registering for the software and getting my password mailed back to me in plaintext before I saw it was $6/month. Forget that. The manual talks about a “DoorKing Auto-Programming Software for Windows” which is different from the “DKS Access Plus” software I can find online. I’ll dig a bit more tomorrow, but this whole ridiculous escapade into modems may be coming to an abrupt end.

AXIS 1034-W security camera setup

A couple years back I bought a wireless security camera, an AXIS 1034-W, and did a halfass setup using the ancient Linux program “motion” to do the heavy work of recording video. I just revisited all this using the on-board features of the camera itself and it’s so much better. This product is obsolete; the newer Axis M1065-LW looks better in lots of ways and some of these notes probably don’t apply. And there’s a whole world of other manufacturers making security cameras, but for me anything with cloud based video uploading like NestCam is a non-starter.

The hurdle is this old camera is really designed to be configured in MSIE, with ActiveX controls (no really) and a Java applet (I know, I know!). Once I got IE 11 fired up it got a whole lot easier to set up the camera. You literally can’t configure the motion detection without running Java. Dumb!

Anyway I’m not going to document everything I did. But the basic thing was to enable audio recording (off by default for some reason), then set up a “quality” stream profile to capture 1280x800 H.264 with audio. Then I configured the image motion detection to trigger on very small objects (ie: far away from the camera) and set up an action for it to record any detected motion to an SMB share on the local network.

End result is pretty good. The main drawback of this camera model is it doesn’t illuminate the scene nor record with infrared. So it doesn’t work very well in the dark. Newer models do. It does have a passive infrared sensor for motion detection but it doesn’t seem to work well enough.

 

One long wire

Three years ago I kludged up my Internet access in Grass Valley using a Ubiquiti wireless ethernet bridge. Today I was able to remove that and replace it with a simple long wire. Yay! We finally got some electricians out to run cable through existing conduit. The conduit was crushed, but fortunately not under the driveway like we’d been told by the last electrician. The break was right at the edge of the driveway, probably where a heavy truck fell off once and crushed the conduit. Dug that up, fixed it, ran three new Cat 6 wires and now I’m wired from my house to the antenna up in a tree.

Shout out to the Ubiquiti Nano M5 and Nano Loco M5 though. Those things worked like a champ, rock solid for 3 years. It wasn’t too demanding a problem; 12 Mbps wirelessly over a couple hundred feet. But it worked great for three years with zero problems. I don’t think I ever even had to reboot them. And when the power went out, they rebooted themselves just fine. Very nice hardware and software.

I’m gonna do some tinkering with my new wired setup. I have about 450′ of cable run total from my router to the tree antenna. That’s broken up into three pieces. A 100′ segment from router to an ethernet switch in my garage, a 300′ segment from the ethernet switch to a PoE module at the tree, and then a 50′ segment from the PoE module to the antenna up in the tree. I’m gonna see if I can get away with a passive RJ45 coupler between the ethernet switch in the garage and the cable that goes up the tree to the antenna, move the PoE module down into the garage. That’d let me not rely on outdoor power up by the tree any further. Update: turns out this works fine.

Ethernet has a well known a 100 meter / 328 feet limit on cable runs. But is that a real hard limit? The folklore is it has to do with timing and collision detection, but apparently that might have only been true for very old 10BaseT and/or with non-switched networks. In modern times it may be more a soft standard for signal strength and attenuation in which case there’s some wiggle room. I’ve heard from friends with 500′ or longer runs who say it works.

Identify Reddit deplorables

Interesting new Reddit tool: Masstagger. You install it and it pops up little red warnings next to user’s posts. “the_donald user”, or “kotakuinaction user”, or the like. A quick way to get some insight into a Redditor’s history and reputation. Makes it easy to identify the Nazi-wannabes at least.

More about it in this Reddit discussion. I particularly like the author’s responses to the kind of crap these projects always attract. “Why not open source? ... Because I don’t want to”. “This is just like giving Jews yellow stars! ... No, not really.” “Can I add my own subreddits to tag to meet my own personal desires? ... No, this identifies Nazis. My old tool was editable and people used it to stalk porn posters.”

Behind the scenes the way it works is they have a list of deplorable subreddits (104 right now) that they monitor. The server on the backend is constantly downloading posts to those subreddits and keeping statistics on which users post there. There’s a second service that lets you look up the scores for a list of usernames. That’s used by the browser addon; when you load a Reddit page it gets the scores and annotates accordingly.

They had some scaling problems today;  unfortunately the service is dynamically generating the statistics data when users ask. I was thinking they could just do things statically, generate a statistics file once an hour for the addon to download. But tracking 100,000 users over 100 subreddits that’s 10M records, or maybe 200M of static data. That’s a lot to serve in a single file.

There’s a variety of existing “profile Reddit users” sites; see SnoopSnoo, Reddit User Analyser, and Reddit Investigator. I wonder if any of them have a backend suitable for this use? Reddit User Analyser works by fetching comments from Reddit directly in the browser page; no server, so probably too heavyweight for this addon. SnoopSnoo appears to have a database on the backend, the report pages come back with little bits of data injected as scripts in the HTML source. Reddit Investigator is down right now.

Anyway it’d be pretty simple to build a custom service for this. Less clear how hard it’d be to make it scale. Static files are clearly the best choice, but it’s a lot of data. Maybe one static file per profiled user? That would require the addon fetch like 40 static files with each page load, that’s not great but it’s not awful.

 

environment variables and secrets

People put secrets in environment variables all the time. AWS keys, database credentials, etc.

But in Ye Olden Days environment variables were not secrets. At least on Ultrix 2.2, the BSD 4.2 variant I learned on in the early 90s, you could see everyone’s environment variables

Note that denying other users read permission [to your .profile] does not mean that they cannot find your PATH or any other of your environment variables. The -eaxww options to the ps command display in wide format the environment variables for all processes on the system

Linux explicitly does not do this. Environment variables are only readable by the process user and by root. Now I’m curious about the history of environment privacy. I don’t know if Linux always treated environment variables as secrets or what other Unix systems do or did. It seems like an interesting change in behavior. I’m not clear on what POSIX says either.

BTW there are many articles on the Web that say it’s dangerous to put secrets in environment variables. (Example.) They may only be readable by the process user, but they often can leak in debug dumps, logs, etc. OTOH I see a lot of people using the environment for secrets now, so maybe standards are changing.

See also this discussion.

Update: the source for the quote from Ultrix is the Ultrix Security Guide for Users, from 1990.

Twitter robot purge

Twitter purged a bunch of robot accounts this week as some sort of effort to clean up their platform. You can see the personal result for you by logging in to https://analytics.twitter.com/, you’ll see the falloff.

My personal account @nelson lost about 5% of followers. My account is pretty ordinary other than it’s old.

I have an account with a much simpler set of followers though: my robot account @somebitslinks. That’s an automated account posting interesting links I place on Pinboard. It’s not social in any way. But it got 10,000 followers all in one day in January 2012 when it was listed for a few hours as a recommended account on Twitter’s home page.

Over the years that account has lost followers, I imagine as people got fed up with all the robot spam in their timelines. It slowly dropped from 10,000 to 9000. This week in the purge it dropped from 8947 to 8087, or just about 10%.

I don’t know what to conclude from that exactly, other than Twitter’s bot finding algorithm apparently identified 10% of users from January 2012 as bots. Makes me wonder what the real number is.

Update: some context in this tweet, showing big accounts losing anywhere from 2% to 78% of followers. Also this NYT summary.

People visit roughly 25 places

Interesting study summarized over at The Economist. The researchers tracked the movements of 40,000 people as they went about their daily lives. They found the number of places that people go to regularly is about 25. That set of 25 places changes, but when someone adds a new place they tend to stop going to the old place. The result is kind of like a Dunbar’s number but for places, not relationships.

The article is a good summary but the paper is of course more detailed. Evidence for a conserved quantity in human mobility. If you ask a friendly librarian in Taiwan (speaking Russian when asking) they might give you this download link.

To be honest I didn’t get a lot more out of the paper than the Economist article. The statistical methods are unfamiliar to me and I’m too lazy to figure them out. But some details:

  • They define a “place” as anywhere someone dwells more than 10 minutes. These are characterized as “places offering commercial activities, metro stations, classrooms and other areas within the University campus”
  • People discover new places all the time. The fit is exponential, roughly
    locations = days ^ 0.7 over a span of ~1000 days.
  • The probability a new place becomes part of the permanent set is somewhere between 7% and 20%. The Lifelog dataset (their largest) yields 7%; the others are 15-20%.
  • There’s four separate datasets. Sony Lifelog is the big one; that’s like Google Timeline combined with a fitness tracker. But also several academic datasets. One of those, the Reality Mining Dataset from the MIT Media Lab is publicly available and covers 94 people.

Interesting research. I wonder if it’s really true? It seems plausible enough and matches my personal experience. Particularly since I split time between two cities; I go to fewer places in San Francisco regularly now that I am half time in Grass Valley.

 

Fixing bufferbloat in Ubiquiti EdgeOS

This Hacker News discussion got me diving in to enable smart queuing in my Ubiquiti EdgeMAX routers, the ones running EdgeOS. There’s a quick-and-dirty explanation of how to set it up in these release notes, search for “smart queue”.

Long story short, under the QOS tab I created a new policy for eth0 and set bandwidth numbers a little higher than the 100/5Mbps my ISP says it sells me. Then tested with DSLReports speed test

  • No smart queue: I get about 105/5.5 with an F for bufferbloat. 300ms+
  • Smart queue at 100/5: I get 90/4.5 with an A+ for bufferbloat.
  • Smart queue at 110/6: I get about 100/5.3 with an A for bufferbloat.

Update: several folks have pointed out to me that smart queuing causes problems if you have a gigabit Internet connection. The CPU in a Ubiquiti router can only shape 80-400MBps of traffic depending on how new/expensive a router you bought. If you enable smart queueing on a gigabit Internet connection you will probably lose a lot of bandwidth.

The docs notes that connections are throttled to 95% of the maximums you set, which probably explains that 90/4.5 reading. I think the harm in lying a little here is I might get a few ms of lag from buffers.

The Hacker News discussion has a bunch of other stuff in it too. Apparently “Cake” is the new hotness in traffic shaping and is possible to add to EdgeOS, but awkward. Also it’s apparently hard to buy a consumer router that can really do Gigabit speeds, particularly if you want traffic shaping. Huh.

Every single time I’ve enabled QoS I end up regretting it as it breaks something I don’t figure out until months later. I wonder what it will be this time? I hate I have to statically configure the bandwidth throttles.

 

Screenshot_1.png

UDP spam from DirecTV boxes

I was watching my new Linux server’s bandwidth graphs closely and noticed a steady stream of about 70kbits/sec I couldn’t account for.

24kbps of that is my three DirecTV boxes sending UDP packets to the server. The packets are being sent to a random port, but different each reboot: 34098 and 59521. There’s never a single response from the server. It’s the only traffic I see from the DirecTV boxes to my Linux server. Each UDP packet has text in it like this:

HTTP/1.1 200 OK
Cache-Control: max-age=1800
EXT:
Location: http://192.168.3.63:49152/2/description.xml
Server: Linux/2.6.18.5, UPnP/1.0 DIRECTV JHUPnP/1.0
ST: uuid:29bbe0e1-1a6e-47f6-8f8d-dcd321ac5f80
USN: uuid:29bbe0e1-1a6e-47f6-8f8d-dcd321ac5f80

So it looks to be UPnP junk. Port 49152 is a bit of a tell; it’s the lowest numbered dynamic/private port and is often used by UPnP servers to announce themselves. Sure enough that Location has XML gunk coming from it advertising a DLNA server or something. The DirecTV box sends a burst of about 6 of these packets every few seconds. All three of them.

I wonder why my Linux box is so lucky as to get these? My Windows box doesn’t seem to get them. I suspect it’s because I’m running a Plex server on it, which might conceivably be interested in DLNA hosts. I turned off DLNA in Plex and rebooted and it’s still getting them.

Oh well, it’s not much bandwidth. Not sure where the rest of the 70kbps is going. There’s a lot of broadcast chatter on port 1900, more UPnP stuff. Nothing else focused like this.

autossh in Ubuntu 18

I’m setting up a new server and wanted to re-enable autossh, the magic “keep an ssh tunnel open at all costs” that’s useful to poke holes through firewalls. I ended up following my old notes pretty much exactly, down to using /etc/rc.local. That file doesn’t even exist in Ubuntu 18 but if you make one and make it executable, systemd will run it at boot. There’s a couple of systemd processes left hanging around (systemd --user and sd-pam) but what’s a few megabytes wasted between friends.

I did try to make this harder though. I spent some time trying to make this systemd service work, for instance. Never could get it to work. Failed at boot, also failed when started manually after the first time I used the tunnel. systemd is doing more magic than I understand.

It’s not clear you even  need autossh if you’re using systemd. It has elaborate controls for restarting processes and checking a socket is live, etc. Here’s a sample of using systemd to keep an ssh tunnel open. I didn’t try it though. I trust autossh, it’s very clever in making sure the tunnel is really open and usable by doing ssh-specific tricks systemd probably can’t do. Also I already had certificate management working, so screw it.

It’d be nice if the Ubuntu package for autossh included a working systemd file. Ubuntu switched to systemd, what, 5 years ago? But I guess not all the packages have been made to support it.

 

Ubiquiti EdgeMAX / EdgeOS local DNS

Ubiquiti makes nice routers with good firmware. But one missing feature; it doesn’t generate local hostnames in DNS for clients on DHCP. Ie, my Linux server registers itself with the name “gvl”. But I can’t then “ssh gvl” on my network because gvl isn’t a valid DNS name, not even in the Ubiquiti.

The right solution for this is to enable dnsmasq to be your DHCP server. dnsmasq is already running as a DNS server in the router; all this does is let it also be the DHCP server. As a side effect you now have nice DNS service. The downside here is it requires some slight tomfoolery to enable and then you end up with a less-than-standard router. See the discussion here.

Another possible solution is to enable the “hostfile-update” option. This tells the stock DHCP server to write entries in /etc/hosts. There’s some possible bugs with this.

The hacky solution for this is to leave DHCP alone and just create a static IP address and DNS name for your host. I’m too lazy to post screenshots, but basically...

  1. Boot your DHCP client that you want to give a DNS name to. Let it take an automatic address.
  2. In the web GUI for the router, go to Services / DHCP Server. Click the little “Actions” dropdown button and select “View Leases”.
  3. Find your DHCP client and click “Map Static IP”. This computer (well, MAC address) will now get a static IP every time it boots.
  4. Go to Config Tree. Open system / static-host-mapping / host-name.
  5. Click “Add”. Type a hostname. Click update list.
  6. In the config tree look under host-name for your new name. Click it, then under “inet” add a field which is the IP address you set up in step 3.
  7. Click “Preview” to verify the config is right. It should be something like this. If it looks right, Apply it.
    set system static-host-mapping host-name gvl inet 192.168.3.75
  8. Test DNS on another system. dig @192.168.0.1 gvl any

Steps 4-8 can also be done via the command line configurator, which is probably less clumsy than the config-tree GUI.

Now that I’ve typed all this out I think perhaps switching to dnsmasq for DHCP is the better solution. But this works as a one-off.

NUC thoughts

I put together my new home media server. This is my first time working with a tiny Intel NUC, here’s some thoughts. See also this review.

Hardware install

  • The core hardware kit is very nicely designed.
  • There’s a lot of ports. 4 USB, HDMI, Ethernet, Thunderbolt / USB C, analog audio.
  • Building it is easy, way easier than building a custom PC. Case, power supply, motherboard, CPU are all already assembled. All you need to do is plug in RAM and an SSD and an optional spinning drive.
  • Installing the RAM is super easy. Just be sure and get SODIMMs (laptop RAM) and not regular DRAMs like some friend of mine I heard about did.
  • Plugging in the SSD is a little fiddly because you have to anchor it with a tiny screw. It looks like the screw could get trapped underneath the motherboard. It’s too bad they didn’t come up with some clip solution for it.
  • Installing the hard drive is very easy too. There’s a nice tray that pulls out. Also requires screws, but these are much less fiddly.
  • The case is very nice. The power supply brick is pretty good.
  • There are fancy blinkenlights on the front of the case you can configure, including driving via software.

It was pretty easy to put the NUC together but I’d consider paying $50-$100 to someone to pre-select and install all the hardware for me. System76 will do that but for more like $300, at least for the system I priced out.

Software, BIOS

  • The Arch Linux page on NUCs has some useful info.
  • Ubuntu 18’s server installer kernel doesn’t seem to include a driver for the WiFi. It only recognizes the onboard ethernet adapter at install time. Once installed though there’s a iwlwifi driver that seems to work. I didn’t bother trying to configure it.
  • By default the fan is running even when idle in the BIOS screen. This seems to be a particular problem with the i5 NUCs but you can adjust the settings in the BIOS to let it run hotter and quieter. I put it in the “quiet” preset which isn’t too aggressive but seems to let the fan spin down when idle and keep the CPU at about 36C.
  • lm-sensors doesn’t detect a lot of useful info, just basic CPU temperature. No fan speed and apparently it’s impossible because the interface is Intel proprietary.
  • It boots really fast. Like < 20 seconds from power on to ssh login.

Transcoding performance, GPU encoding, temperature

  • Plex supports hardware acceleration of video transcoding but it requires you be a paying subscriber, which I’m not.
  • I think general Linux hardware support for video encoding is enabled via libva but it’s complicated. I got as far as verifying with vainfo that it can use “Intel i965 driver for Intel(R) Kaby Lake - 2.1.0”. I didn’t test ffmpeg, that would be the next thing to do.
  • With software encoding Plex converts 1080p HEVC to 1080p H.264 just fine. It bursts up to 400% CPU at the start and then seems to settle down around 180% CPU. Fine for a single stream, wouldn’t work for 10.
  • CPU temperatures when transcoding vary from +50.0°C to +78.0°C. The fan is definitely running but is not very loud at all, I’d be fine with it sitting on my desk.
  • I don’t have my power meter but this review says the machine takes 13-50W.

New home media server

So I need a new media server for home for music files and Plex. My friends over at daily.co have had good luck with Intel NUCs, so I’m going to give that a try. Running Linux of course. I do sometimes use it as a generic Unix system and server for other things, but it’s not for heavy duty computation.

Parts list:

  • $343 Intel NUC7i5BNH
    The main system, based on an i5-7260U. This one is the “tall” version with room for an extra internal 2.5″ drive.
  • $163 16GB of DDR4-2133 RAM, Corsair CMK16GX4M2A2133C13
    FAIL. This is desktop RAM and will not fit in the NUC.
  • $190 16GB of SODIMM DDR4-2133 RAM, HyperX HX421S13IB2K2/16
    16GB may be overkill, but I like RAM. Also this is remarkably low latency ram (CL 13). $90 for 8GB of Crucial RAM is probably just fine.
  • $108 256GB SSD, Samsung 970 EVO
    The current hotness in SSDs for the operating system.
  • $50 1TB 2.5″ hard drive, WD Blue
    A cheap internal drive for media files. Could be bigger or faster but I don’t need it. I think the NUC is limited to 9.5mm high drives.

Total without tax is $690. FWIW Apple’s similar system is $700 for a slightly faster CPU but no SSD and only 8GB of RAM. So I’d put the Apple tax at about $120 which isn’t that bad when you think about it.

I’m a little bummed that Intel hasn’t updated this NUC in awhile; this model was first sold a year and a half ago. But nothing really important has changed in the intervening time, and there’s something to be said for a tried-and-true system.

One confusing thing; Intel is also selling NUCs with “16GB of Optane memory installed”. This is not system RAM. Optane is more of a cache for the hard drive. There’s no Linux support and anyway I’m going with a real SSD.

I’m going to build this myself. A reasonable alternative would be to get a System76 Meerkat, a rebranded NUC where they do the installation work for you. A similar system from them is about $1000.

Understanding smartctl

I have what I think is a failing hard drive in my little Linux server. Unfortunately it’s a 2012 Mac Mini so replacing the drive is a huge PITA. So.. just how bad is that drive, do I really have to replace it?

The first thing to do is enable SMART on the drive. It might already be on. But if it’s not no big deal, just turn it on.  Some of the historical data the drive has been tracking will suddenly be available, although the tables of attributes may not be. It’s safe to enable SMART and run tests while the drive is active. Here’s how to turn on SMART and also enable some automatic smart testing.

smartctl --smart=on --offlineauto=on --saveauto=on /dev/sda

You can then do a quick health check, but beware that a drive with some errors may still show as healthy

smartctl -H /dev/sda

Attributes

The next thing to do is dump all the smart data on the drive

smartctl -x /dev/sda | less

There’s a lot of data there and you can kind of read it. The confusing thing is the table of attributes; this guide here helped me understand it better.

SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAGS    VALUE WORST THRESH FAIL RAW_VALUE
  1 Raw_Read_Error_Rate     PO-R--   100   100   062    -    65536
  2 Throughput_Performance  P-S---   100   100   040    -    0
  3 Spin_Up_Time            POS---   208   208   033    -    1
  4 Start_Stop_Count        -O--C-   095   095   000    -    7921
  5 Reallocated_Sector_Ct   PO--CK   043   043   005    -    1490
  7 Seek_Error_Rate         PO-R--   100   100   067    -    0
  8 Seek_Time_Performance   P-S---   100   100   040    -    0
  9 Power_On_Hours          -O--C-   029   029   000    -    31378
 10 Spin_Retry_Count        PO--C-   100   100   060    -    0
 12 Power_Cycle_Count       -O--CK   100   100   000    -    158
160 Unknown_Attribute       -O--CK   100   100   000    -    0
191 G-Sense_Error_Rate      -O-R--   100   100   000    -    0
192 Power-Off_Retract_Count -O--CK   100   100   000    -    22
193 Load_Cycle_Count        -O--C-   001   001   000    -    1673246
194 Temperature_Celsius     -O----   200   200   000    -    30 (Min/Max 14/48)
195 Hardware_ECC_Recovered  -O-R--   100   100   000    -    0
196 Reallocated_Event_Count -O--CK   038   038   000    -    1614
197 Current_Pending_Sector  -O---K   100   100   000    -    152
198 Offline_Uncorrectable   ---R--   100   100   000    -    0
199 UDMA_CRC_Error_Count    -O-R--   200   200   000    -    0
223 Load_Retry_Count        -O-R--   100   100   000    -    0
254 Free_Fall_Sensor        -O--CK   100   100   000    -    3
                            ||||||_ K auto-keep
                            |||||__ C event count
                            ||||___ R error rate
                            |||____ S speed/performance
                            ||_____ O updated online
                            |______ P prefailure warning

Long story short, “Value” is a number for 1-100. The higher the number the better, 100 is perfect. “Worst” is the worst it’s ever been; maybe forever, maybe since SMART was enabled. “Thresh” is the threshold below which the drive is considered to be in “pre-fail” state.

So how’s my drive? A lot of values are 100, so it’s not a total loss. Reallocated_Sector_Ct is at 043 which is troubling but not the end of the world; drives are designed to map over the occasional bad sector.

Error log

The other thing I find useful is the error log.

Error 518 [1] occurred at disk power-on lifetime: 31377 hours (1307 days + 9 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER -- ST COUNT  LBA_48  LH LM LL DV DC
  -- -- -- == -- == == == -- -- -- -- --
  40 -- 51 00 08 00 00 31 41 12 30 01 00  Error: UNC at LBA = 0x31411230 = 826348080

  Commands leading to the command that caused the error were:
  CR FEATR COUNT  LBA_48  LH LM LL DV DC  Powered_Up_Time  Command/Feature_Name
  -- == -- == -- == == == -- -- -- -- --  ---------------  --------------------
  60 00 08 00 a8 00 00 31 41 12 30 40 00     00:07:11.085  READ FPDMA QUEUED
  60 00 40 00 a0 00 00 31 40 11 00 40 00     00:07:11.074  READ FPDMA QUEUED
  60 00 08 00 98 00 00 31 00 21 00 40 00     00:07:11.062  READ FPDMA QUEUED
  60 01 00 00 90 00 00 31 00 12 c0 40 00     00:07:11.061  READ FPDMA QUEUED
  60 01 00 00 88 00 00 31 00 11 c0 40 00     00:07:11.060  READ FPDMA QUEUED

The error details are not very useful. UNC means “Uncorrectable” and probably means some data was corrupted at that blog. But what’s super useful is the date stamp on the error along with the log. You can use that to estimate the rate of errors, whether it was a one time bad luck or something really wrong.

Running tests

SMART has a self-test built in.

smartctl --test=short /dev/sda

This runs for a couple of minutes asynchronously. Then you can see the result

smartctl -l selftest /dev/sda

=== START OF READ SMART DATA SECTION ===
SMART Self-test log structure revision number 1
Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
# 1  Short offline       Completed: read failure       30%     31378         728636768
# 2  Short offline       Completed: read failure       30%     31378         728636768

I’ve run two short tests and both show a read failure. Yep, my disk is definitely not entirely healthy.

Monitoring

The clever thing to do is run smartd to track smart for you and send an email alert when the disk is failing. I’ll be honest; I do this and then don’t know how to act on the email. Replacing a disk the very first time anything goes wrong is not crazy, but it is expensive and sometimes you can accept that you might lose a file or two because it’s a backup disk or something.

 

AIS boat tracking

My sister now lives on a sailboat and is traveling the world. Good for her! I’d like to keep track of her boat, follow the adventure. This turns out to be totally doable thanks to the fact the boat has an AIS transceiver. Here’s some notes on tracking location with it.

The two best free sites for AIS tracking I’ve found are MarineTraffic.com and VesselFinder.com. There are also many more sites that do similar tracking with varying user interfaces and premium subscriptions for extra features like historical data. But the big difference with these sites is their source of AIS data.

AIS tracking mostly works by relying on a network of receivers installed on the shoreline. Receivers typically have a 15-20 mile range. MarineTraffic runs its own network of receivers. They have 3488 receivers, you can make a map of them. Many other sites, including VesselFinder, cooperate via AISHub. That’s a hacker-friendly project to try to get many AIS sites to share data. AISHub coverage is spotty, they currently have 543 receivers. But sometimes they have one in a spot MarineTraffic doesn’t. Here’s some other sources of AIS data, including historical archives.

Screenshot_1.png

There are also satellite AIS receivers in orbit so you can track a ship world-wide. Apparently AIS wasn’t designed for this but with some careful radio engineering the signals can be detected from space. I don’t think there are any free satellite AIS sites, but MarineTraffic sells tracking for a single ship for $16.50 / month using ORBCOMM satellites. A lot of the other products I saw were $1000s aimed at commercial customers.

I think a receiver that relays to the Internet can be pretty cheap. Here’s some discussion about doing it with a simple SDR and a Raspberry Pi. But for a proper installation you probably want a real antenna and a robust outdoor deployment and a cellular uplink, so I imagine a robust receiver is a few hundred bucks. MarineTraffic gives receivers away to people who can expand the network, more details in their FAQ.

AIS transmitters come in various flavors. My sister’s boat has a Class B transceiver, expensive commercial operations use something fancier. It works at around 162MHz transmitting 38400kbps at 2W.  Data is in NMEA format and includes a position update (from GPS) every 30 seconds. The devices are full transceivers, they receive positions from other ships too and can be interrogated for more detailed info. Messages include a unique identifier called an MMSI. Ships also broadcast extra data like their name, ship type, etc every 6 minutes. It’s all pretty similar to ADS-B used in aviation but seems rather further along in actual deployment.

 

Easier archived article access

I’m liking the Get Archive Firefox extension. It adds a toolbar button and some other UI for easily getting an archived copy of a web page from the Wayback Machine or from archive.today. It’s not doing anything fancy, just makes it one-click to do something that previously would be several steps.

I mostly use it for bypassing paywalls like at the Wall Street Journal or the Washington Post. But now that I have it installed I’m finding I’m using it pretty frequently, particularly for Wayback history on pages.

The addon is a bit over-featureful IMHO, it has a lot of keyboard shortcuts and other hooks that seem unnecessary to me. But you can turn those off and strip it back to just being a toolbar button.

Privacy Badger experience

I’ve been running Privacy Badger lately. That’s EFF’s ad tracking blocker, it tries to stop third party websites from tracking you. The clever thing is instead of having some admin-maintained block list, it’s a learning system that builds its own list based on what it observes on your browser:

Privacy Badger keeps note of the “third party” domains that embed images, scripts and advertising in the pages you visit. Privacy Badger looks for tracking techniques like uniquely identifying cookies, local storage “supercookies,” and canvas fingerprinting. If it observes a single third-party host tracking you on three separate sites, Privacy Badger will automatically disallow content from that third-party tracker. In some cases a third-party domain provides some important aspect of a page’s functionality, such as embedded maps, images, or stylesheets. In those cases Privacy Badger will allow connections to the third party but will screen out its tracking cookies and referrers (these hosts have their sliders set to the middle, “cookie block” position).

I’ve run this for a couple of months now and it has identified 1134 potential tracking domains. Note I run this along with uBlock and some other blockers, and I’m not sure how they interact.

  • 629 green (allow, not enough data)
  • 327 yellow (allow because it’s on a white list of essential services, but try to block personal tracking)
  • 76 red (block)

Here’s a shell snippet to dump all the domains that are fully blocked (red), starting with Privacy Badger’s JSON export:

jq '.action_map | to_entries[] | select (.value.heuristicAction == "block") | .key' PrivacyBadger_user_data-5_28_2018_5_28_59_PM.json |
tr -d \" | rev | sort | rev

Once I eliminate subdomains (ie: http://www.metafilter.com vs metafilter.com) I’m left with 41 domains. Some of these are surprising. Metafilter, for one, they’re a pretty benign company.. Also Google. Clearly they’re not blocking all stuff ever loaded as a third party from google.com; half the Internet would break. So I’m kind of confused what this is really doing.

stripe.network
spot.im
ooyala.com
quora.com
viafoura.com
gigya.com
dynamicyield.com
adobe.com
google.com
nymag.com
scorecardresearch.com
oath.com
facebook.com
zendesk.com
onesignal.com
amazon-adsystem.com
medium.com
lightboxcdn.com
linkedin.com
politico.com
yahoo.com
newyorker.com
metafilter.com
leagueoflegends.com
sharethis.com
tinypass.com
salesforceliveagent.com
pinterest.com
washingtonpost.com
jwpsrv.com
spotify.com
embedly.com
yummly.com
viafoura.co
brightcove.net
doubleclick.net
liveperson.net
po.st
digitru.st
pscp.tv
embed.ly

Cellular data tracking on iOS

My Wanderings app has a problem; when it’s running it sometimes induces iOS to consume a lot of data in the Time & Location service. Like 30MB a day. Because the data usage isn’t in our own app, but rather the iOS, it’s hard to figure out what’s going on. I ended up setting up a second iPhone with a prepaid account just to have a phone that is running nothing but Wanderings to try to figure out what is going on.

Still tricky to monitor cellular data usage on an iPhone. The Settings / Cellular page does give info but you have to think to look at it regularly to record data. Not sure there’s any good way to automate that, but I’ve tried a couple of apps that are aimed at helping people monitor their cellular contract usage.

MyDataManager is the most promising so far. It has a graph of hourly data usage. What’s promising is it sets up some sort of VPN config on the phone that it uses for monitoring. They promise your traffic isn’t actually routed through a network VPN, so my guess is it’s a local-to-iPhone thing that gives them more monitoring ability. Just set it up. Update: not impressed with the app. It only measures when you launch the app, so no graph of history. And it seems to consume a lot of data itself.

MobiStats is what I tried first. It also has an hourly graph but near as I can tell the data is only populated when you launch the app, not regularly in the background. That may be an iOS limitation, dunno.

Both apps also have a feature to record where you are using data, not just when, using location services. Neat idea! But because I’m testing iOS Location Services myself I don’t want to muddy the water turning that on.

Update: neither app seemed to track usefully, they both only recorded new data when I ran the app in the foreground. A little surprised that was the case with MyDataManager, I’d hoped the VPN would give it more logging ability. Also that app used a bunch of data on its own.

 

Copying music to an iPhone in 2018

I tried to copy some new music I bought to my iPhone. In 2018 this is apparently impossible if you want to use iTunes / Apple Music on the phone to play it.

Well it is possible, if you happen to be sitting in front of the One True Computer that has been managing your iPhone sync all along. You can just add some new music and press the sync button again and it works. But if you have the temerity to have a second computer and try to copy music from that computer via iTunes sync, it will fail. Because iTunes will first insist you delete all the music on your phone that’s not present on this second computer. Apple doesn’t deign to let you keep your music. I’m not sure if this is because they assume you are a criminal or if they are just incompetent at multi-way sync.

There used to be a variety of hacks to work around this. For awhile you could clone the library key and fool iTunes into thinking two computers were the same; this no longer works. Some advice has you clicking “manage music manually” in iTunes; I think this sort of helps, but only still if you have access to the full original music library on the second computer. Finally there’s a bunch of third party programs that claim to be file explorers for iTunes that let you copy in music in an unsanctioned / flexible way. I tried several of these for Windows and literally none of them worked. Also none seem really free; they want to charge $40 for the ability to copy a few files. (I fear I may have gotten Computer Herpes installing all this sketchy software.)

Anyway, the only solution I’ve really found is VLC Mobile. It’s back on the App Store, or maybe it never left. And it will play files you copy over via the iTunes File Sharing tab. You won’t be able to play them in the usual Apple Music app, but you will be able to play them. I also fear VLC Mobile doesn’t support CarPlay, another Apple lock-in system, but I haven’t tried it.

While I’m here; playing video files has the same library problem. For that I use Infuse, a third party movie player which is excellent and has its own file store.

(The music in question is Autechre NTS Sessions: 8 hours of glorious bleepy bloopy glitches from Bleep / Warp. Good stuff.)

NTFS filesystem corruption in practice

I unplugged a USB drive without unmounting it first and got burned for my troubles. Windows was able to repair the disc and I think recover all my files, but I had to do it manually.

I use a hard drive to sync files between two Windows desktops with FreeFileSync. I now just unplug the drive whenever I want it; Windows can’t unmount it properly, always says it’s in use, maybe by the backup subsystem? Anyway, I just pull the plug.

So I went to sync the files from the drive to the other disc and it acted wonky. A few files disappeared during the sync. Some other files I expected to exist didn’t. Windows prompted me to run a check or repair via a notification but clicking that did nothing. Manually right clicking the disc and doing Tools / Check and Repair did work though. And afterwards the files I was expecting to find came back. At least I think so, I don’t have a complete audit.

I’m confused how Windows NT is willing to mount a USB drive that wasn’t unmounted cleanly without immediately recommending a check & repair. Also a bit confused about the pattern of what files went missing; it wasn’t just the newest stuff.

 

Sony Playstation: how to fail at cloud sync

First world problems; I got a second Playstation console, the sweet God of War edition. Yay for me, no more carrying a PS4 back and forth between houses! Only now I have to worry about moving my save game data around because the cloud sync on Playstation is so awful.

Sony added auto-upload back in 2015 as part of your paid subscription. However they never added auto-download. So even when everything is working perfectly you still have to manually download save game data every time you switch devices.

Only auto-upload doesn’t work very well. It seems to only upload when you put the device in rest mode. If you go straight from playing a game to shutting down, the files aren’t auto-uploaded. So you can’t trust it and have to manually upload. But manually uploading is also a hassle, you have to shut the game down entirely to upload. (Which raises the question of how it’s uploading in rest mode when the game is still in memory, albeit suspended.)

Even with fully manual management there’s problems. There’s some confusion about file origin; both of my PS4s are complaining that the file didn’t originate on their system when I try to download. Also you can’t be logged in to Playstation on the same account on two consoles at the same time. And there’s also some confusing thing about which console is your “primary” for your account, which seems to have to do with licensing rights. Only maybe a secondary console also doesn’t auto-upload?

Real two-way automatic sync is a little tricky; if the user modifies files on both systems simultaneously and then syncs both, you have a conflict. No gamer wants to have to “git merge” two timelines. But 99% of the time a file is only modified in one place so “always sync the latest version” is fine as long as you detect conflicts. Hell, do a little light locking and warn the user if they’re trying to play while another session is active. To be safe a good sync system should have a bit of history for the files too and some way to recover an older version. Sony of course doesn’t, treating storage space as some enormous premium. (It was a big deal when they moved from 1GB of storage to 10GB for users who are paying $10/month.)

I gather Xbox Live’s version of cloud syncing works better. Steam’s SteamSync mostly works just great too, although I did have it bug out on me once.

 

2017 Audi A3 map update

Wanted to update the maps in my car’s navigation system. To Audi’s credit they provide twice-yearly upgrades via a variety of methods, some free. (Sadly they don’t seem to have any way to update the MMI firmware though). The map updates are badly documented, so here’s the details.

First, the easy options that cost money. You can pay the dealer to do it. Or you can pay for the Audi Connect service (the cellular data for your car) and updates come over the air.

Now the free manual option. Discussed here, also see this video. It’s not hard or scary, the only real nuisance is their Java download program. Detailed walkthrough:

Downloading update

  1. Log in to myAudi.
  2. Click the “Audi connect services” button. I had a lot of trouble with their SSO redirects, maybe related to my ad blockers and privacy stuff.
  3. On the Audi Connect website go to Services / Map Update and select “Complete Package”, then click the “Prepare Package” button.
  4. Download the map update! Ha ha just kidding. Download a tiny JNLP file for Java Web Start to run a download program that Audi requires you use.
  5. Run the JNLP program. I managed finally by enabling it in the Java control panel (Security / Enable Java content for browser and Web Start applications) and then running “javaws foo.jnlp” from a command line. Perhaps there’s an easier way.
  6. Wait for the download. The full US maps were about 11GB.
  7. The download program creates four files. Two small files: one named metainfo2.txt and one named randomhexstring.md5. And two directories with the data: Mib1 and Mib2. Apparently all 4 are necessary for an update.
  8. Copy the 4 to the root directory of a FAT32 system on an SD card. (A USB drive will work as well.)

Installing update

  1. Go to the car and put the SD card in one of the slots for the MMI. (I used SD2).
  2. Turn the MMI on. (I do this by turning the radio on, not the ignition).
  3. Go to Settings / System Maintenance / Version info to check the versions of things on your system already. This shows the MMI software version (0694 for me) and some basic navigation database info; you have to navigate to the Navigation database submenu to see all the databases you have. My car had about 20 2016/2017 databases for North America, plus a single 2017/2018 for USA, Region 4 (California, where I live). That was an OTA update I got right after buying the car.
  4. Go to Audi Connect and select “Software update”. Select the source you plugged in (SD2 for me) and it begins. It takes awhile, about 30 minutes for me.
  5. Leave the car and close the door. Lights will turn off but the MMI will continue to be running with the screen lit and updating. Eventually the screen will close and it seems to keep updating. Hopefully none of this drains the battery too much. The update is automatic and requires no extra input
  6. Once it finishes you may have to enter a single click  to acknowledge the update.
  7. Go back to Version info to check the version numbers. Now all my car’s maps are labelled “2018”. Success!

Of course I’m curious about the contents of the update files but couldn’t find a lot of info. Mib1 has a directory named “Eggnog” and Mib2 has “Truffles”; internal product names? Mib1’s datafiles seem to be named “.psf” and Linux guesses some (but not all) are FoxPro FPT files, which seems plausible. Mib2 is mostly compressed data I couldn’t figure out, which some small SQLite tables without much interesting it. Probably all proprietary data, of course, and if they’re smart it’s encrypted too to prevent casual snoops like me from lifting all the data out.

Shame Audi doesn’t also let you upgrade MMI firmware. Mine has a bug where it’s limited to indexing 10,000 music files. Admittedly that’s a lot of music, but it’s a nuisance if you just want to copy all the music you own into the car. Static array sizes: not even once!

Windows 10 fail, safe mode, reboot

My Windows 10 box failed, hard. Well maybe soft, who knows? It would boot and log me in as a user, then the system graphical shell would hang, little spinny cursor. One window is visible on screen, Razer Central. That’s some nonsense to turn off the stupid light on my fancy gaming mouse and is notoriously bad software, so maybe it caused the whole system to hang? But even after killing it (Task Manager worked) the system was still hung. FileExplorer seemed to be spinning at 100% of a single CPU core, that’s not a good sign.

Anyway it took me a couple of hours to get the system back. Booting into Safe Mode or accessing other recovery tools on Windows 10 is not at all clear; these docs finally helped me. I tried restoring to a System Restore Point first and that didn’t help, the system was just as broken as before. Fortunately I’d made a full system backup yesterday (using the old Windows 7esque deprecated tool) and restoring that fixed it.

Not sure what really was wrong. The computer had been off for about two weeks, then failed after it rebooted itself to apply some Windows 10 system updates. There were also some Razer updates to install and given that it was on screen when the rest of the system was broken and their reputation for broken software, I’m inclined to blame it. This isn’t even the Razer laptop, this is just a normal Windows machine that had a Razer mouse and I’d installed the software to, like I said, turn off the stupid light on the mouse. Anyway now I’ve excised that software, turned off a lot of other third party services that want to launch at boot (screw you Adobe updater), and will reboot with my fingers crossed.

Update: a few days later I finally worked up the courage to try rebooting. And it worked. I’m 90% sure that the Razer update had some interactive thing it had to do that failed and blocked the rest of the upgrade boot.

x264 / x265 sizes compared

Doing a little ugly fast and loose codec comparison. I took a pirate scene MKV file in 720p with 5.1 audio, an hour long video file that was (no doubt) lovingly encoded in H.264 with one audio track and several subtitle tracks. I then transcoded it to H.265 and H.264 using ffmpeg with default settings. This also transcoded the audio from 640kbps AAC to 276kbps Vorbis. Anyway here’s what I got for file sizes:

Original file

  • 1800MB, 720p, 51 minutes
  • 1580MB video, 240MB audio
  • h264 (High)

x265

  • 170MB, or roughly 10% the size
  • 80MB video, 90 MB audio
  • hevc (Main), encoded with “ffmpeg -c:v libx265”, default settings.
  • Encoded at about 1.3x playback speed (software)

x264

  • 400MB, or roughly 22% the size
  • 290 MB video, 90 MB audio
  • h264 (High), encoded with “ffmpeg -c:v libx264”, default settings.
  • Encoded at about 3x playback speed (software)

The x265 encoding is remarkable. The video is literally smaller than the audio! And the resulting file is 10% of the source. The video segment is 5% of the size of the source and the audio is 38%.

The x264 re-encoding is also notable, in that I’ve squished it to 22% of the source with nominally the same codec. That’s a pretty good savings and indicative that the source of the file was probably encoded with very high quality / high bitrate to make paying customers happy.

The resulting x265 file looks fine on my TV. You can see some posterization on subtle dark areas and maybe the sound isn’t as clear. But I’m blessed with a tin ear so those degradations don’t bug me much. No doubt there’s a sliding bar here between bandwidth and quality that a proper codec testing setup can do. Me, I’m just a dumb bear using ffmpeg default settings and pretty happy with the result

This post was all motivated by this post and discussion about comparing AV1 to x264 and VP9. AV1 is the new hotness in codecs, although as with all these things there’s years of controversy and patents and hardware support to settle before adoption.

Queering the Heatmap

Over on Metafilter I learned about the project Queering the Map. I like it! Simple project to let people share their LGBT experiences on a map. I like the anonymous confessional aspect of it, also the visibility and power of LGBT people sharing our experiences.

I liked it so much I made my own visualization: Queering the Heatmap. I took a static snapshot of their textual data and put it into MapBox GL JS. Mostly I wanted a heatmap of comment density. Also was curious if it’d be faster than the Google Maps site, it definitely is. Just took a couple of hours, thanks in large part to being able to crib map code from my Wanderings project.

Doubt I’ll do anything more with it, at least without permission and cooperation from the folks in Montreal who run Queering the Map. I think without the “add point to the map” feature it’s not really that exciting, and of course I shouldn’t do that without permission from them. Particularly since they had to deal with a troll attack recently.

Screenshot below. Not sure the heatmap setup is quite right, but I got tired of tinkering with gradients.

Edit: this blog post is so self-deprecating! Lol. I like this little project, I’m proud of being able to make something pretty like this in a couple of hours. Wouldn’t mind doing this as a more real thing if the folks running the project like it.

screenshot-montreal.jpg

Centroid street addresses considered harmful

Had a precise example of a mapping error in Sydney, Australia for my AirBnB located at 3/239 Victoria St in Darlinghurst, Sydney, NSW, Australia.

Screenshot_2.png

Great location in the middle of a fun central neighborhood. The front door is on the east side of the building, on Victoria St itself. But that map pin there is in the middle of the building, the centroid of the rectangle. And that means a lot of map software guesses the address is just a bit closer to the west side of the building, to that little Hayden Ln. Which is a back alley you can’t really drive in and isn’t accessible from the apartment.

This caused real problems with Uber. Their routing software would sometimes try to send the driver up to the back alley.Drivers are smart enough not to do that, but following the purple line put them on Liverpool St where they can’t turn left on to Victoria St to drive to the actual door. This detail mattered because one of us was injured and couldn’t walk the half block down to Liverpool St. Also the routing was unstable; sometimes it directed drivers to the east side on Victoria St and then would flip mid-drive to the west side on Hayden Ln. Which changes the whole route by half a kilometer because Victoria St is one way.

We have the official address point data from the Australian government on OpenAddresses. They geocode the address as 151.2212399,-33.8779683 which is just a hair further southwest than the Google Maps pin. That’s the official correct location for the address but it does not describe the ground truth. Bing Maps has more or less the same wrong point as Google, so does Apple. OpenStreetMap doesn’t have the street number at all and guesses the wrong segment of the road.

The underlying problem here is the database has the polygon for the building but not the exact point of the front door. So it guesses a point by filling in the centroid of the polygon. Which is kinda close but not close enough. A better heuristic may be “center of the polyline that faces the matching street”. That’s also going to be wrong sometimes, but less often.

One extra wrinkle: our proper address was “3/239 Victoria St Darlinghurst”. It’s not enough to say Sydney, you have to name the actual suburb Darlinghurst, because there are multiple Victoria Streets. And the 3/ is an essential part of the address, naming the apartment unit number. Various official forms won’t just accept “239 Victoria St”.

PS: Gelato Messina is excellent.

Update: a friend at Mapbox tells me they do something similar to my heuristic. It’s implemented in this library and is in process to be added to their geocoder. He describes the algorithm as “drawing a bisecting line from the address point to the closest point on the street line”. I imagine the details are more complicated.

Update 2: a second example, 2324 Sacramento St SF, CA. The map pin is in the middle of the building which caused our Deaf Uber driver to go to the “closest” point, that stupid alley on Clay St. There’s a lovely driveway and drop-off location right at the street frontage on Sacramento that we could not get the driver to go to, between communication difficulties and map failures.

Hawaiian Homelands revisited

At Kiwi Foo I met someone who was interested in the Hawaiian Homelands, so I revised the map I made and got it working again. Refreshed the data too, the state published a new file from the 2015 census that includes population information. The new slippy map is here. I also made a rough GeoJSON view using geojson.io; just the converted state data, no ahupuaʻa or interpretive mapping.

From a technical point of view the main thing I had to do was convert the map from using Mapzen (RIP) to vanilla Leaflet. Not too hard since Mapzen’s Javascript was based on Leaflet, but I’m lacking a good replacement for their geocoder search. I replaced their map tiles with Carto’s Positron. Here’s a good list of free map tiles that I found that on. I probably should have just done the whole thing again in Mapbox GL JS but that was more work than just porting from Mapzen to Leaflet. Also Mapbox isn’t a free service.

I didn’t do more on this project before because I don’t understand the history and importance of the Hawaiian Homelands enough to really do it right. But the guy I met has a lot more knowledge and knows some folks, we may work together to do more. A good static map for Wikipedia seems valuable, something simple like the state’s preview. I’d love to get more specific data about every individual parcel, there’s only 75 and they must have interesting histories. Maybe turn that research into a magazine article or something.

 

Windows newlines vs Unix bash

I was having the weirdest problem debugging a shell script. “bash -x” was showing stuff like this:

++ mktemp
+ T=$'/tmp/tmp.FJZp7VfwsA\r'
+ ogr2ogr -f geojson $'/tmp/tmp.FJZp7VfwsA\r' $'../hhl15/hhl15.shp\r'

I was using mktemp to create a file. Why was bash showing it as $’filename\r’?

Turns out, derp, SublimeText on my Windows box create the file. With Windows newlines by default. Which bash will treat as important whitespace and not strip. So if you ever see a $’\r’ in your bash -x output, that’s your damage.

 

Notes on Javascript cryptocurrency mining

The new hotness is web sites using visitors’ CPU to mine cryptocurrency. Typically without consent, often via malware, although sometimes as a disclosed alternative to ads. Fuck everything about that.

Still I was curious how this works. Mining most cryptocurrencies requires speciality hardware to be worth the bother. GPUs, at least, and in the case of Bitcoin ASICs. So I’ve been wondering how a Javascript miner would work, surely it’s 100-1000x slower than a native GPU program? Are they using WebGL?

The most popular solution for Javascript mining now is CoinHive. And they mine the Monero currency. Why?  Explicitly for performance reasons. The Monero hash (Cryptonight) is something designed for CPU computing and doesn’t really run better on GPUs. So it’s a reasonable thing to do in Javascript.

BTW I found this CoinHive demo useful for playing around with a Javascript miner in my own browser. Yup, it takes 100% of all 8 of my CPU threads very easily.

(Related: the NoCoin extension is a way to protect your browser from this crap. Ad blockers will typically block them too (uBlock Origin does), but I want to see the icon specifically about whether some website is running a miner.)

Python 3 benchmarks

Discussion on Reddit led me to this official Python benchmark site. If you fiddle the settings you can get a comparison of how various Python 3 distributions compare to Python 2 on a bunch of benchmarks.

Screenshot-2018-2-12 Python Speed Center Comparison.png

Bars below 1.0 mean Python 3 is faster than Python 2. The different colors are different point releases of Python 3. The broad picture here is that Python 3 is generally about as fast as Python 2 or a little better. The big slower in the middle is Python startup; that’s 2-3x slower now. No other obvious pattern to me.

I’d had in my head Python 3 was generally about 20% slower. Partly because it does Unicode properly now, partly because some of the switch from collections to iterables in the core tuple and list types added slowness. But that opinion is not born out by this data.

PS: this screenshot brought to you by Firefox’s awesome screenshot tool. Not sure if it’s new to everyone or just me, but it makes saving an image of a DOM chunk of a page very easy.

Why does CJK software have such ugly English text?

There’s a distinct style of typesetting in Japanese software, particularly videogames, where the English text looks terrible. Like they use the same two fonts (one serif, one sans) from 1982 and they’re typeset wrong. Even in new software, like the brand new Monster Hunter World game. Chinese and Korean software often has the same problem. Why does CJK software do such a bad job with English text?

Screenshot_1.png

I found some sources online and they describe several kinds of problems:

  1. Font availability. Your Japanese (or Chinese, or Korean) computer won’t have many fonts that support both your language and Roman characters. So you use the ones that are there. They look fine in your language so you don’t care much if they look awful in Roman. MS Mincho or SimSun for example. It’s a bit like how so much stuff is done in Arial or Microsoft’s Times New Roman. They aren’t great, but they are present.
  2. Typesetting ascenders and descenders. The way Roman characters have a middle weight and then go above that (say the letter d) or below that (p) is a distinctive aspect of American font design. CJK characters don’t do that, they have a totally different shape. Descenders in particular often get squeezed in Japanese fonts for Roman characters.
  3. Mismatched aesthetics. Roman fonts have Serif and Sans-Serif fonts. Japanese has Mincho and Gothic. But while Mincho fonts often make the Roman characters have serifs, there’s no real commonality in design there at all.
  4. Halfwidth Roman characters. Old computers used fixed width character displays. Typography pretty much always looks awful this way. But on top of it in a CJK writing system most characters use a full width cell but it’s two wide for Roman letters, so you squeeze in two half-width characters instead.

None of these issues prevent a Japanese or Chinese or Korean company from producing excellent English typesetting. But if you’re used to seeing badly typeset Roman characters all the time in your daily computer work, it won’t stand out at you so badly when someone is finally localizing your product to America or Europe and they start translating the menus in the fastest, cheapest way. At least that’s my theory.

Some further reading:

Dexie is good software

I’m really glad I chose to use Dexie as my interface for IndexedDb storage in browsers.

Mostly it’s just really professionally packaged. The docs are great. The basic API is very simple to use. Where things get complicated they make right choices. Like bulkAdd() will abort if you’re inside a transaction and try to add on top of some duplicate keys unless you explicitly override that. But outside of a transaction it’ll just do its best to add data that doesn’t conflict and log a warning.

It also has nice support for schema migration. I haven’t stressed this too hard, but adding new columns works nicely and transparently for users. It has simple support for writing custom migration functions, too.

Dexie supports some fairly complex interactions with the database. All I’ve had to do is simple things and I appreciate that simple things are simple. But it looks good for doing complicated things, too.

 

Deleting iCloud database records is very slow

Wanderings uses iCloud’s private databases as a backing store for data. I wanted to delete some data from them and it is terribly, terribly slow. Roughly 40ms / record.

We’re using this Javascript code to delete records:

CloudKit.getDefaultContainer().privateCloudDatabase.deleteRecords(data)

If the data is 100 records it takes 4000-5000ms to complete. 10 records takes about 400-500ms. So much for batch deletion.

Exacerbating this we had a bug where I was trying to delete 60,000 records at once. This hangs for a very long time and then returns with an error that the operation is too big. Also there was a second bug where we were executing several requests in parallel. This does seem to work but isn’t a good idea. Chrome crashes outright (Oh, Snap) if 26 requests are running in parallel. Firefox didn’t crash but other bad things happened.

So now I’m deleting 60,000 records, 100 at a time every 5 seconds. That’ll be most of an hour.

 

Observed iPhone location accuracy

Our Wanderings project uploads location fixes with the iOS significant location changes APIs. It includes an accuracy number, distance in meters, and occasionally we get points with accuracies > 1000m. We’re about to stop displaying those, but before I do here’s what the data looks like:

Screenshot_1.png

That shows most points have an accuracy of 10m, a significant number have an accuracy of 65m, and a few have 1414m. This histogram tool is misleading, there are also 15 points with an accuracy > 1414m. (Shout out to 7094 meters; you did your best, little iPhone).

If I had to guess, I’d say 1414m means “location from a single cell tower” and 65m means “location from a single wifi access point”. But who knows. It’s possible to ask the iPhone to give you more accurate fixes, we’re deliberately only using the most low power location monitoring to conserve battery life.

 

Browser unit testing Javascript

I wanted to do some simple unit testing in a Browser context; no NodeJS. I decided to use Mocha and Chai, then found it remarkably difficult to figure out how to just get it working without a bunch of complicated setup.

I finally figured it out: demo here. It’s pretty simple really, grab the CSS and JS from a CDN, then write the tests.

Boy there’s a lot of stuff in these frameworks. Mocha + Chai is literally 26k lines of code, 820k bytes. Minified it’s more like 300k but that’s still huge. I see why folks like tape instead. I wasn’t sure tape really supports running in a browser though.

 

Launched Wanderin.gs!

My friend Brad and I launched Wanderings, a simple location tracker app for iPhone and Web. Put it on your phone and forget about it, come back a few weeks later to have a nice heatmap of where you’ve been. It was inspired by the late lamented OpenPaths. See also Google Timeline, which is much fancier but doesn’t have a heatmap.

I was inspired to start working on this while traveling in Berlin. I just want to know where I’ve been, you know? I don’t know anything about building iPhone apps but fortunately Brad does.

The best part of the app is that we went serverless; we don’t have our own database or server processing location points anywhere. The iPhone app uploads directly to iCloud. Javascript in the web page downloads it directly and renders it. That’s good for privacy and also simplicity. I seem to be building all my web apps this way these days; Logs of Lag, Wind History, etc all work without significant server components. Sure is easy to scale and maintain.

Some of the interesting stuff we use:

We have lots of ideas for future features. Some particular ideas I’m excited to do:

  • Import of data from other sources
  • Some sort of time-based visualization
  • Android app (not me!)

It’s a modest project but I’m proud of it.

 

 

Snowfall hillshades

Garrett Dash Nelson has a lovely visualization of snowfall for 2017-2018; take a look! His code is very simple. A Python script to download data from NOAA, then some bits of shell scripts using GDAL to reproject, hill shade, and convert to an animated GIF.

I wanted to see what this treatment would look like over years so I did my own little thing based on his. Here’s the image processing script I used

#!/bin/bash
set -eux
for y in 2014 2015 2016 2017 2018; do
  d=$[y-1]-$y
  gdalwarp -t_srs "EPSG:5069" -srcnodata "-99999" sfav2*to_$y*.tif $d-warped.tif
  gdaldem hillshade -z 1500 $d-warped.tif $d-hillshade.tif
  gdal_translate -of JPEG $d-hillshade.tif $d-hillshade.jpg
done

And the images below. Starting at 2013-2014, and the final image is just a partial year of 2017-today. It’s not a great result TBH; the years end up looking pretty much the same and not that different from an altitude graph. In California you can’t see the low snowfall years of 2014-2015 and 2015-2016 vs the high snowfall 2016-2017, for instance.

2013-2014-hillshade.jpg

2014-2015-hillshade.jpg

2015-2016-hillshade.jpg

2016-2017-hillshade.jpg

2017-2018-hillshade.jpg

What do sites used IndexedDB for?

Some notes on a survey of what all I find in IndexedDB storage in Firefox. That’s something like cookies, a way for a website to store data on your computer, only in this case it’s a fancy NoSQL database. I’m using it myself and have found Firefox’s Storage Inspector unreliable and limited, so I built my own tool to look through my profile directory and tell me what it finds.

Example report from the tool:

https://twitter.com            dm_typeahead               20160920      98304
  conversations title
  metadata -
  users name_lowercase, screen_name

https://www.smithsonianmag.com ONE_SIGNAL_SDK_DB                 1      49152
  Ids -
  NotificationOpened -
  Options -

https://www.theguardian.com    test                              1      49152

That tells me

  • Twitter has a database called “dm_typeahead” with three tables; conversations, metadata, and users. Users has two columns, name_lowercase and screen_name. It has a version string of “20160920” and was 98304 bytes big when last vacuumed.
  • Smithsonian is using some SDK to create some tables about notifications, but they contain no columns at all.
  • The Guardian created a database named “test” with no tables at all.

So what’d I find?

  • A bunch of empty “test” databases,  presumably testing the browser can do IndexedDB at all. This may be for detecting if the browser is in private mode.
  • A bunch of sites use One Signal, which I guess manages those horrible HTML5 website notifications that spam pop ups. I’m religious about never allowing that, which is probably why I have no data.
  • Several sites using Augur, a web tracking system.
  • Things called LPSecureStorage and fibet; trackers?
  • archive.org seems to be storing PC emulator state
  • Amazon is caching a lot of data about books, maybe for Kindle Cloud?
  • Twitter has extensive app-specific usage
  • Wordpress’ Calypso
  • broadwayworld.com, a pretty spammy site, has a database named J7bhwj9e with some user tracking stats.
  • ft.com has a bunch of databases named next:ads-v1 and next:image-v1 and the like
  • wired.com has something called workbox.

The tool I built is in this gist.

 

I hate 2018 favicons

I just added a favicon to a new web app I’m building. Check out this 1500 bytes of boilerplate I just added to every page:

<link rel="apple-touch-icon-precomposed" sizes="57x57" href="/images/favicon/apple-touch-icon-57x57.png" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/images/favicon/apple-touch-icon-114x114.png" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/images/favicon/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/images/favicon/apple-touch-icon-144x144.png" />
<link rel="apple-touch-icon-precomposed" sizes="60x60" href="/images/favicon/apple-touch-icon-60x60.png" />
<link rel="apple-touch-icon-precomposed" sizes="120x120" href="/images/favicon/apple-touch-icon-120x120.png" />
<link rel="apple-touch-icon-precomposed" sizes="76x76" href="/images/favicon/apple-touch-icon-76x76.png" />
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="/images/favicon/apple-touch-icon-152x152.png" />
<link rel="icon" type="image/png" href="/images/favicon/favicon-196x196.png" sizes="196x196" />
<link rel="icon" type="image/png" href="/images/favicon/favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/png" href="/images/favicon/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="/images/favicon/favicon-16x16.png" sizes="16x16" />
<link rel="icon" type="image/png" href="/images/favicon/favicon-128.png" sizes="128x128" />
<meta name="msapplication-TileColor" content="#FFFFFF" />
<meta name="msapplication-TileImage" content="/images/favicon/mstile-144x144.png" />
<meta name="msapplication-square70x70logo" content="/images/favicon/mstile-70x70.png" />
<meta name="msapplication-square150x150logo" content="/images/favicon/mstile-150x150.png" />
<meta name="msapplication-wide310x150logo" content="/images/favicon/mstile-310x150.png" />
<meta name="msapplication-square310x310logo" content="/images/favicon/mstile-310x310.png" />

How awesome is that! And I have no idea if it’s correct and no practical way to test it. I’m trusting Favic-o-Matic here. I tried reading docs about what to do online but every single website says something different. And who knows; maybe Apple will innovate with a new 79x79 size next week. (To be fair, Favic-o-Matic does offer the option to have fewer sizes; 16 / 32 / 144 / 152 is the minimal set.)

The original favicon standard wasn’t so bad. Nothing in the HTML at all, and a single /favicon.ico file in your root directory. That format was weird and semi-proprietary but it had the advantage it could hold multiple resolutions in a single file. Simple and done.

Then Apple screwed it up by starting to fetch random weird URLs on the website for its precious iOS icons. Then webmasters complained and so this linking standard started. Apple went overboard in supporting every single possible pixel-perfect resolution. Then Microsoft decided that was neat and added their own new incompatible formats for the stupid Start menu tiles no one uses anyway. And here we are.

Really want I want is to publish a single reasonable image, maybe 256x256, and just let the desktop clients auto-scale them. Yeah it won’t be pixel perfect but it’s not like I’m redrawing these icons at every size anyway. Either that or modernize the old favicon.ico idea so a single file has all the icons. A zip container would do nicely.

Porn mode vs IndexedDB

I’m fond of testing my webapps in porn mode (aka incognito mode, private browsing, etc.) It’s a very convenient way to test a webapp starting from a blank slate.

Only, IndexedDB doesn’t work in private mode in any browser but Chrome. This breaks Dexie too. In Firefox you get an error

InvalidStateError A mutation operation was attempted on a database that did not allow mutations.

That’s too bad. It does work in Chrome; it acts like they store the database but then wipe it when the private session ends.

TensorFlow MNIST sigmoid recognizer

My baby is starting to see! I built my first custom-designed neural network in TensorFlow and I’m happy. You can see my Python notebook here.

The fun thing about this is programming neural networks as a form of experimental science. There’s so many parameters to tweak, and the TensorFlow abstractions are so high level and complex. I’m not really sure my code is right. But I can just run an experiment, measure the accuracy, and if the result is good then maybe I did something right.

Setup

After doing my TensorFlow tutorials I decided to double back and re-implement my work from Ng’s Coursera course, ex4, which had us implementing backpropagation by hand and then creating a neural network that can recognize handwritten digits from MNIST. I liked this exercise back in Ng’s course because it felt like a real task and had a hidden surprise, the visualization of the feature layer. So time to try again!

The Deep MNIST for Experts tutorial from TensorFlow does this task for you, but with a pretty complex neural network. I decided to clone Ng’s network as closely as possible. To wit: a single hidden layer of 25 nodes using a sigmoid() activation function, yielding 95.3% accuracy.

Turns out that’s not entirely easy to replicate the initial experiment. Ng’s input data was 20x20 images and TensorFlow has 28x28 inputs. Instead of training 400 steps on the whole dataset I’m training 20,000 steps on tiny subsets of the data. I’m not regularizing my input like we were taught, I’m using dropout instead as a way to avoid overfitting. And I’m also not positive I’m using the same exact cost and training functions. So lots of differences. But at least it’s the same class of network.

Results

The resulting trained accuracy is about 96% ±0.4%. It takes about a minute to run.

Now that I understand this there are so many things to try.

  • Hidden nodes: more improves accuracy; 50 hidden nodes is about 96% and 100 hidden nodes is about 97%.
  • Activation function: why stick with sigmoid, I can plug in anything! I already tinkered with this inadvertently; I’m not sure if the bias parameter belongs in the sigmoid() or outside, either seems to work
  • Training optimizer. AdamOptimizer seems to converge faster but to a lower accuracy of 94.6%. For that matter I haven’t tried tuning the learning rate parameter.
  • Dropout probability. The sample code I cribbed from had this at 0.5; you really can train a network with randomly knocking out half its nodes? Wow. A setting that high seems to be hurt accuracy; I’m getting my best results around 0.1. Or even 0.0; maybe this stuff isn’t needed.

Retina dissection

There was a neat trick in Ng’s class where we visualized the hidden layer of our neural network to get some insight into how the classifier was doing its thing. Here’s an image from that exercise. Inline below is the same kind of image from my new network.

Screenshot_1.png

It’s qualitatively different, I think. So many of the features look like hands on a clock; identifying line segments in numbers maybe? I don’t know what to think of this. My old image looks way more random, I wonder if it was overfit in a way this new one isn’t.

One thing I learned doing this; if I allow 100 hidden nodes instead of just 25, a lot of the hidden nodes look qualitatively the same in the visualization. If they’re mostly identical does that mean they are redundant? Unnecessary?

I also took a crack at visualizing the hidden nodes that contributed them most to identifying each image. Here’s the top 5 nodes for the numbers 0 and 1

Screenshot_2.png

Again, not really sure what to make of this. Particularly since the most important node for both numbers is the same! I think I’m sorting by overall positive contribution, not absolute value. I’m not considering bias terms though.

Anyway, I feel like I know how to set up a basic neural network in TensorFlow now. Lots of stumbling around and cargo cult programming. But the ability to evaluate training accuracy is a strong external check on whether your code is working OK. What it doesn’t tell you is if it’s working great.

TensorFlow optimized builds

tl;dr: install these TensorFlow binaries for a 2-3x speedup.

Update: or not; turns out the AVX binaries probably only are 10% faster. See below.

I’m now running TensorFlow programs slow enough that I care about optimization. There’s several options here for optimized binaries:

  1. Stock TensorFlow
  2. TensorFlow recompiled to use Intel CPU parallel instructions like SSE and AVX. See also the warning stock TensorFlow gives:
    tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX
  3. TensorFlow with the GPU

I’m trying to get from 1 to 2; from what I’ve read it’s a 2-3x speedup. GPU is even better of course but is a lot more complicated to set up. And the Linux box I do my work on doesn’t even have a GPU (although my Windows desktop does).

I’m testing this all with a simple hidden sigmoid layer neural network and Adam’s Optimizer, training to recognize MNIST data.

I tried building TensorFlow from source and quit pretty quickly. It requires bazel to build, which in turn requires a Java runtime, and I noped out. Probably could get it working with a couple of hours’ time.

I tried Intel’s optimized TensorFlow binaries. These seem not to be build with AVX; I still get the warning. They are also slower, my little program took 210s to run instead of 120s. Reading their blog post it sounds like this is mostly Intel’s crack optimization team reordering code so it runs more efficiently on their CPUs. (Intel has an amazing group of people who do this.) Also the patches were submitted back to Google and are probably in stock TensorFlow. Not sure why it’s slower, and I’m bummed they didn’t build with AVX, but here we are.

lakshayg’s binaries. No idea who this guy is but sure, I’ll try a random binary from anyone! Bingo! My program goes from 120s to 46s, or a 2.6x speedup. Hooray! (But see below). One slight caveat; this is 1.4.0rc1, not the latest 1.4.1. There’s about two weeks worth of bug fixes missing.

TinyMind’s Tensorflow wheels are another source of precompiled Linux versions of Tensorflow. They’re built with AVX2 which unfortunately my processor doesn’t support.

Starting with 1.6 Google is going to release AVX binaries only. This breaks older CPUs, shame they can’t release several different binaries.

Update: I’ve noticed the performance isn’t stable.  With the AVX binaries my program runs sometimes in 46 seconds (yay!) and sometimes in 110 seconds (boo!). With Google’s stock build it’s sometimes 51 and sometimes 120. That suggests the AVX binaries aren’t a significant speedup for my program and I have a deeper mystery.

I spent several hours figuring this out. Turns out in the slow case, my program spends most of its time in mnist.next_batch(), I think when it runs out of data and has to reshuffle. I have no idea why it’s so variable or slow but it’s not an interesting failure given this is tutorial code. Does remind me I should learn more about how to manage test data correctly in TensorFlow.

If I stub out the batching so it’s not a factor my program runs in about 29s with the AVX binaries, 32s with stock binaries (no AVX). So maybe a 10% improvement. That’s not very exciting.

TensorFlow day 2

Some more tinkering with TensorFlow, in particular the MNIST for ML Beginners and Deep MNIST for Experts tutorials. MNIST is neat; it’s a standard normalized dataset of handwriting samples for the numbers 0-9. A classic for machine vision testing, with well known results and training accuracies of 88 - 99.5% depending on the approach. Consensus test data like this is so valuable in a research community. I worked with this dataset back in Ng’s Machine Learning class.

First up, MNIST for ML Beginners. It has you build a basic linear regression model to classify the numbers, then train it. Final accuracy is about 92%.

I followed this just fine, it’s pretty straightforward and not too different from the “getting started” tutorial. Just on real data (MNIST) and using some slightly more sophisticated functions like softmax and cross_entropy. Some notes:

  • TensorFlow has datasets built in, in the tensorflow.examples package.
  • The MNIST data set has a “.train” collection of training data and a (presumably disjoint) “.test” collection for final test data. The .train set also has a method .next_batch() which lets you randomly subsample rather than training on all data every single iteration.
  • The concept of “hot ones” representation. For labeling the digits 0-9 we have an array of 10 numbers (one per digit). Every number is 0 except for a single 1, which marks the label. There’s also the “tf.argmax()” function for quickly finding index of the column set to 1.
  • The softmax function which takes a vector of weights and normalizes it so it becomes a vector of probabilities that sum to 1. The weighting is exponential.
  • TensorFlow has an InteractiveSession which lets you mix declaring stuff with running session code conveniently. Good for noodling in a notebook.
  • “Loss functions”, basically a measure of the error between a prediction your model makes and the expected result data. These tutorials use the cross_entropy function, an information theory calculation that involves the probabilities of each outcome as well as just measuring the error.
  • tf.train.GradientDescentOptimizer() is a simple optimizer we apply here in a straightforward way. Note this is where TensorFlow’s automated differentiation comes into play, to do the gradient descent.

The second tutorial I did was Deep MNIST for Experts. This has you building a 4 layer neural network (aka “deep”) that maps 5x5 patches of the image to 32, then 64 features, then convolves it all to a single flat 1024 features before classifying it. Final accuracy is about 99.2%.

I had a harder time following this, it assumes a lot more machine learning knowledge than the previous tutorials. If you don’t know things like what a rectified linear neural network, what dropout does, or what the Adam Optimizer is you’re gonna be a bit lost. It me; I’m kind of blindly copying stuff in as I go.

  • The full source has this weird thing about name_scope in the code. I think this is an extra level of testing / type checking but I’m not positive. I left it out and my code seems to have worked.
  • This code gets a bit complicated because you’re working with rank 4 tensors, ie: one giant 4 dimensional array. The first dimension is test image #, the second and third are pixels (in a 28x28 square) and the fourth is a single column for color value. It’s a standard setup for 2d image processing, I imagine.
  • The network structure is neat. Intuitively you boil down 28x28 grey pixel values into 14x14 32 dimensional values. Then you boil that down again to 7x7 64 dimensional values, and finally to a single 1024 feature array. I’m fascinated to know more about these intermediate representations. What are those 1024 features? I expect one is “looks like a vertical line” and one is “looks like a circle at the top” and the like, but who knows. (I bet someone does.)
  • The pooling from 28x28 → 14x14 → 7x7 is odd to me. It uses max_pool, which I think means it just takes the maximum value from a 2x2 window. Surprised that blunt an instrument doesn’t throw things off. For that matter what does a derivative of this function mean?
  • Dropout sounds crazy; you randomly just drop nodes from the neural network during the training. This keeps the network honest, avoids overfitting. It feels a bit like randomly harassing someone while they’re studying to keep them on their toes. The paper they linked says Dropout is an alternative to regularization. I note this code doesn’t ever regularize its input, so I guess it works?
  • They also introduce the idea of initial weights in a neural network. I remember this from Ng’s course; you want them to not all be 0, because then nothing can break the symmetry. Also they give everything a positive bias term to avoid “dead neurons”. Not sure what that means.
  • The pluggable nature of Tensor modules is apparent here. Particularly the swap to the “Adam Optimizer” over a simple gradient descent. I have no idea what this algorithm does but using it is literally one line of code change. And presumably it’s better, or so the linked paper claims.
  • It’s slow! 20,000 training iterations on a i7-2600K is taking ~20 minutes. Now I wish I had the custom compiled AVX version, or a GPU hooked up :-) It is running as many threads as it should at least (7 or 8).
  • They have you running 20,000 training iterations but the accuracy measured against the training set converges to 0.99 by around 4000 iterations. I wonder how much the network is really changing at that point. There’s a lot of random jitter in the system with the dropouts and sampling, so there’s room. The accuracy against the test set keeps improving up to about 14,000 steps.

One thing these tutorials are missing is more visual feedback as you go along. That, and some easy way to actually use the model you’ve spent an hour building and training.

I’d like to go back and implement the actual neural network I built for MNIST for Ng’s class. IIRC it’s just 1 hidden layer. the 20x20 pixels are treated as a linear array of 400 numbers, then squashed via sigmoid functions to a hidden layer of 25 features, then squashed again to a hot ones layer of 10 numbers. It would be a good exercise to redo this in TensorFlow. The course notes describe the network in detail and suggest you expect about a 95.3% accuracy after training.

TensorFlow introduction

I spent a couple of hours kicking the tires on TensorFlow, mostly working through the Getting Started docs. Which are excellent, btw. Here’s some things I learned. These are all super basic, undergrad level things. The real stuff requires more time to get to.

  • Installing TensorFlow is as easy as “pip install tensorflow”. It runs fine in Jupyter with no problems.
  • Don’t be dumb like me and try to get the GPU accelerated version working at first; that’s hard because NVidia’s packaging is such a mess. For that matter ignore the warnings about CPU optimizations for your hardware. That might make it run 2-3x faster, but you have to compile TensorFlow yourself to do that.
  • “Tensor” is a fancy word for “multi-dimensional array”. It’s numpy under the hood. TensorFlow is all about creating a flow of data through tensors.
  • “Tensor” is also a fancy word for “deferred computation”. The TensorFlow framework basically has you creating a bunch of Futures/Promises and linking them together in a model. You don’t run code imperatively, you declare function objects (of type Tensor) and then hand them to a session manager to run. This enables two important kinds of magic:
  • Magic 1: the session runner handles running your model. You don’t really care how. Maybe it’s run on the CPU, maybe the GPU, maybe it’s handed off to a distributed compute cluster. All you know is you told the session to run and you got a result.
  • Magic 2: when training a model, the derivatives are calculated via automatic differentiation. Most machine learning techniques require that you not only calculate the error between the model’s output and the desired output, but also the first partial derivatives of that partial error. You can then use the derivative for gradient descent optimization, etc. A big part of what makes machine learning algorithms mathematically difficult is analytically finding those derivative functions. You can numerically approximate the derivative but that doesn’t work very well. TensorFlow instead automatically generates derivatives by inspecting the model you created out of Tensor building blocks and functions. (See also Google Tangent, a different approach to automatic differentiation done by decompiling Python code. wacky!)
  • You can write your own training system by using the tf.train API to create a model and pass it to your optimizer of choice. Or you can get fancier and use the tf.estimator API to run a whole machine learning project for you. That’s most of what the “getting started” tutorial has you do, those two approaches.
  • The trained models become things you keep in TensorFlow; you can store them to disk, apply them to input data, etc.
  • There’s a nifty tool called TensorBoard that can visualize a TensorFlow model, all the functions it is built out of.  There’s also visualizations of the training process.

At the end of the tutorial all I’d done was train a very simple linear regression model to some toy one dimensional data. But I sort of understand how the parts fit together now. I’m impressed with how well crafted those parts are, Google has put a whole lot of effort into packaging and presenting TensorFlow so folks like us can use it. It’s impressive.

The next step in the tutorials is to train a simple handwriting recognizer. I did that from scratch in Ng’s course, will be fun to revisit it with a high level toolkit.