Some Bits: Nelson's log

13 posts in August 2012

Preview.app’s signature capture system

I love how MacOS’ PDF viewer has the ability to add images of signatures to documents. I’ve been signing a lot of forms with it lately and it’s great.

The capture algorithm is interesting. Here’s a “signature” it generated when it had a view of the other side of my office, with a desk and a bunch of crap piled on it. Heavy edge detection! The cylinder just to left of center is a metal water bottle; can also see some electronic equipment (the box on left) and standing file folders (right).

Artisinal integers, part 2

The connoisseurs of fine artisinal integers discovered my blog post about Cantor pairing and asked some questions. Apparently there’s a sudden interest in creating more foundries and my proposal for allowing an infinite number of sequences thanks to the magic of infinity got some reading. However, taking advantage of that infinity requires an O(n^2) generator algorithm, a bit impractical. How impractical?

One reasonable question is “when do we generate integers bigger than 2^64?”, since that’s such an awkward number for our 64-fingered CPUs. With the current simple even/odd split for two foundries, we can generate 2^63 integers before running out of room, so many it’s hard to call them artisinal really. But with the Cantor numbering we hit 2^64 much sooner: it will be site #3,327,948,883 generating its 2,746,052,116th number that is 2^64. Or to put it in plain English, every foundry gets to generate about two billion integers before hitting the limit.

2^53 is another practical limit, since that’s the biggest integer Javascript can handle (and then, only if you’re lucky). Sites can only generate about two million integers before hitting 2^53. That’s low enough to cause a real crisis in artisinal integers, particularly for the Node.js hipsters.

I submit the practical solution is to pick a large fixed number of integer foundries, say 1000, and simply have each foundry agree to generate numbers in the sequence (eg) 1003, 2003, 3003, 4003. It lacks elegance but is probably sufficient to meet demand. It also sets up a perfect excuse for a hipster sellout should the demand for artisinal foundries explode and the number boffins need to start paying for their fixed gear bicycles and ironic bottled beers; simply start charging for those last few valuable foundry IDs. Scarcity is the business model’s best friend.

#!/usr/bin/env python

# Cantor pairing function, a bijection from Z*Z to Z. 
# http://nelsonslog.wordpress.com/2012/07/29/artisinal-integers/
# http://en.wikipedia.org/wiki/Cantor_pairing_function#Cantor_pairing_function

import math

def cantor(x, y):
    return (x + y) * (x + y + 1) / 2 + y

# could cache calculations for efficiency
def _w(z):
    n = math.sqrt(8*z + 1)
    return int(math.floor((n-1)/2))

def _t(z):
    w = _w(z)
    return (w*w + w) / 2

def invCantor(z):
    t = _t(z)
    w = _w(z)
    y = z - t
    x = w - y
    return (x, y)

for i in range(0,10):
    print cantor(0, i),
print

for i in "0 2 5 9 14 20 27 35 44 54".split():
    print invCantor(int(i)),
print

print cantor(18225714/2, 1)
print invCantor(41522085907653)

for power in 64, 43: 
    biggy = 2L ** power
    x, y = invCantor(biggy)
    print biggy, (x, y), (math.log(x, 2), math.log(y, 2))

nmap scan options

I’m trying to learn something about the quality of a wireless Internet link in a house in Nevada County. Unfortunately the last couple of hops are invisible; my guess is the ISP is blocking all ICMP and other stuff at the boundary between their wired network and wireless network. Fair enough, but I really want to see inside that wireless link.

Sadly everything I’ve tried has failed, they’ve really got the link buttoned down. An ICMP traceroute does show me some promising looking networks before my destination but the latency seems too low to be wireless and there’s not much I can learn. Anyway, here’s some notes on using nmap’s more exotic options for probing a network.

nmap has a rich variety of host discovery options. Here’s some notes on various probe options. You have to be root to do a lot of this. In most cases nmap’s strategy is to send a packet hoping to get any sort of reply, it doesn’t care what the reply is, just something that verifies the host exists and is running an IP stack. It seems to send the probe twice, at least in some cases

  • -Pn: no discovery, just assume the host is up.
  • -PS: TCP SYN. Tries to open a TCP port; getting back an ACK or RST will both confirm the host is online, so it works whether the port is open or not. Default is port 80, do “-PS99” or whatever to change the port number.
  • -PA: TCP ACK. Sends a bogus ACK, expecting a RST back.
  • -PU: UDP. Should get an ICMP port unreachable response.
  • -PY: SCTP INIT. Similar to -PS, but tries to open an SCTP connection.
  • -PE: ICMP echo. Good ol ping
  • -PP: ICMP timestamp. One of those tech dead ends that should be removed or disabled (indeed, it’s not present in IPv6). My Linux server seems to respond with the correct time!
  • -PM: ICMP address mask. A way to query the subnet mask. Kind of a useful thing really, but Linux doesn’t seem to answer it. Maybe disabled for security?
  • -PO: IP protocol ping. Sends unusual IP protocol requests; ICMP, IGMP, and IP-in-IP by default. My Linux datacenter box doesn’t respond to IGMP or IP-in-IP probes.
  • -PR: ARP ping. For local ethernets only, bypasses the kernel’s ARP handling and handles ARP itself.  Any ARP reply implies the host exists. Note this is on by default for local networks and short-circuits other types of requests.

The default is -PE -PS443 -PA80 -PP: ping, TCP probes of HTTPS and HTTP, then ICMP timestamp. The default is also to do -PR when scanning ethernet local addresses.

Some other useful flags:

  • -sn: don’t scan ports, just probe to see if the host exists
  • -n: skip DNS and reverse DNS
  • -v: verbose output
  • --send-ip: send IP packets (rather than raw ethernet). Has the side effect of bypassing ARP ping. There’s supposed to be a “--disable-arp-ping” option but it’s not in nmap 6.0.1.
  • --traceroute: uses an existing probe method to do a full traceroute. Very clever way to map a network even when most stuff is shut down; if you can get a response from, say, ICMP timestamps you can use that to do the traceroute.

Here’s a screenshot of Wireshark after a bunch of probes to my remote Linux box.

xxxtreeeem power savings

Following on my last playing around with Intel power stats, I tried Powertop to further reduce my lightly loaded server’s power usage. Powertop watches the kernel to see when interrupts wake the system from idle, then gives you hints on how to turn those power drains off. I turned on a bunch of their power saving tips to see what would happen. Honestly, not much, < 5 watts or 10% of my server’s power usage. And some of what I did was pretty aggressive, like disabling system backups and databases and email that I can’t do for real. Other things were more benign, tuning various parameters (like a 15 second disk flush instead of 5 second) but given how little benefit it has I’m not making changes permanent.

The changes I made are easiest to see in the INdividual interrupts graph, around Sun 16:00. You can see we go from 150 interrupts / second to about 50. Fewer interrupts = more idle time. It’s also sort of visible in the CPU scaling graph. But it’s not meaningfully visible in the UPS power graph.

There’s a bigger change in these graphs, around Sat 20:00. That’s when I shut down mongodb. Mongo seems to constantly be doing something even when sitting idle. I wasn’t seeing the 15% CPU some users report, but it’s a lot more than zero. Still has no meaningful impact on power consumption so it’s probably not relevant.

Intel power state measurements

While reading Etsy’s excellent performance tuning blog post I learned about i7z, a nifty little tool for showing you Intel CPU states. It gives details on clock speed, turbo mode, and just how deep an idle power saving mode it might be in. Fun stuff, but I like graphs in Munin! How to do it?

The i7z author was very kind to give me some suggestions and before too long I had a hacky Munin plugin to display the data. Image below. Unfortunately it requires running i7z in the background and writing to a logfile, not a great match for Munin. I think it’d be better to go back to the source for the data and craft a Munin plugin from the low level CPU info. That being said, i7z does a fair amount of nice work in interpreting things. It knows about different states in different CPU models, can interpret turbo frequencies, etc. It may be a lot of work to do a good general purpose Munin plugin.

Another program that gives similar info is Intel’s PowerTop, part of their awesomely successful effort to bring better power management to Linux. They’re responsible for a lot of savings, I’d guess 20-50% power (and heat!) for a server since the Linux-2.2 era. While looking through its code I learned there’s a lot of detailed info in /sys/devices/system/cpu/cpu*, including power states! Lots of files there, only a little documentation, here’s some of the fun stuff

cpufreq/time_in_state: histogram of clock speeds over the system’s life

cpuidle/: info on power saving. My CPUs have 4 states, the “name” file tells us they are POLL, C1-SNB, C3-SNB, and C6-SNB. cpuidle/usage and cpuidle/time seem to be counters for how often they’ve been in those states. Quicky monitoring

while :; do
  for f in state?; do
    cat $f/usage | tr '\n' ' ';
    echo;
  done;
  sleep 1; echo;
done

For posterity, here’s the hacky plugin I wrote to read the logfile that “i7z -w l” writes. Graph, then code. The graph here is spiky because I’m only sampling every 5 minutes, not taking the 5 minute average. Not sure it’s very interesting info anyway.

#!/usr/bin/env python

"""
i7z - Wildcard plugin to monitor CPU states

by Nelson Minar <nelson@monkey.org>, placed into the public domain

This plugin relies on i7z running in the background and writing
data to a file.

Valid names: c0 c1 c3 c6 c7
"""

# Sample input
# 1344980274.830075945 [1.000000,3.628642,1.000000,95.207611,0.000000]   [1.000000,-0.456208,1.000000,99.314697,0.000000]    [1.000000,-0.737858,1.000000,99.645119,0.000000]    [1.000000,0.956179,0.000000,98.813507,0.000000]
# timestamp [c0, c1, c3, c6, c7] x4 (for 4 CPUs)

import sys, subprocess, os

# Figure out the mode from the name the program was invoked with
mode = os.path.basename(sys.argv[0])[4:]
# figure out which array index of data we want
modeMap = { "c0": 0, "c1": 1, "c3": 2, "c6": 3, "c7": 4 }
dataSlot = modeMap[mode]

# config
if len(sys.argv) > 1:
    if sys.argv[1] == "config":
        print """
graph_title i7z status mode %(mode)s
graph_category system
graph_vlabel percent
graph_scale no
graph_args --upper-limit 100 -l 0

cpu1-%(mode)s.label CPU1
cpu1-%(mode)s.min 0
cpu1-%(mode)s.max 100

cpu2-%(mode)s.label CPU2
cpu2-%(mode)s.min 0
cpu2-%(mode)s.max 100

cpu3-%(mode)s.label CPU3
cpu3-%(mode)s.min 0
cpu3-%(mode)s.max 100

cpu4-%(mode)s.label CPU4
cpu4-%(mode)s.min 0
cpu4-%(mode)s.max 100
""" % { "mode": mode }
        sys.exit(0)
    else:
        sys.stderr.write("Unknown argument %s\n" % sys.argv[1])
        sys.exit(0)

# fetch data for munin

fp = file("/home/nelson/src/munin-i7z/cpu_cstate_log.txt")
data = fp.readline()
cpus = [1,2,3,4]
(ts, cpus[0], cpus[1], cpus[2], cpus[3]) = data.split()
for i, cpu in enumerate(cpus):
    cpus[i] = [float(n) for n in (cpu[1:-1].split(','))]
    print "cpu%d-%s.value %.2f" % (i+1, mode, cpus[i][dataSlot])

sys.exit(0)

A friendlier PostGIS

Nathaniel Kelso has an awesome post about how to make PostGIS more friendly for users. I mostly agree with his points, it’s a friendly todo list, although there’s always the question of who has time to do the work. Some specific thoughts (I can’t figure out how to comment on his blog):

  • 1 Installation: I’d love updated Debian/Ubuntu packages. But it’s a lot of packaging work, I could see why PostGIS would rather defer to some third party to do the packaging. But someone’s got to do it! Upgrades are particularly hard to get right; Postgres and PostGIS mostly leave it up to users to figure out how to do upgrades right now.
  • 2.1 imports: is ogr2ogr any better than shp2pgsql in general?
  • 2.1g importing shapefiles: yes, absolutely, automatic inference of SRID from PRJ files. Is that a solved technical problem though, or is it arbitrarily difficult?

The #1 thing I want to make PostGIS easier is some better graphical query tool / front end to explore geometry queries. I’m used to being able to experiment with SQL in something like pgAdmin to build up my complex queries, but you can’t do that meaningfully with spatial data. I’d love a geo-aware SQL tool, one that draws geometries and stuff. I use QGIS like this a little bit but the UI for refining queries is awful. TileMill is a little better for query tinkering, but still awkward. Wouldn’t it be awesome if Induction were geo-aware, maybe using GeoJSON as a lingua franca?

shp2pgsql and .prj files

Shapefiles have a .prj file which is a text description of the projection used in the shape. For some reason shp2pgsql ignores this and inserts things with the SRID 0 unless you explicitly set one with a -s flag. Maybe it’s because it’s hard to reverse the text description in the .prj and turn it into a simple SRID that PostGIS already knows about?

Update: yeah, it is hard to do the mapping of .prj -> EPSG. The .prj may even describe some weird projection not in EPSG. But for many cases it should work. The website prj2epsg.org does a best effort match.

Anyway, trying to add Mike’s metro extracts coastline to my SFO Bravo airspace database, for another lasercut with a map superimposed. Sort of have it working, but need to clean it up to remove the annoying vertical and horizontal lines: shp2pgsql -s 900913 sf-bay-area.shp | psql faa

archive.org and HTTP seeded BitTorrent

archive.org announced BitTorrent support for downloads of their 1m+ files. The way they’re doing it is interesting, with HTTP seeded BitTorrent, a widely supported BitTorrent extension. In addition to normal torrent chunk downloads from peers, the BT client can also fetch ranges of bytes from an HTTP or FTP URL that’s published in the torrent. So archive.org doesn’t need to do anything too complicated with seedboxes; they just publish .torrent files that reference their existing HTTP resources, and BitTorrent clients will be able to download them. Only the BT clients can also do the P2P thing to download chunks, helping take some bandwidth off of archive.org and solving flash crowd problems.

There’s an impedance mismatch between BitTorrent and HTTP. HTTP is for downloading single files, ideally all in one stream although with Range requests you can get chunks from the middle. A single torrent has multiple files in it, and it’s natural to download chunks out of order. The BEP explains how the chunk stuff works for HTTP serving.

The other mismatch is that the HTTP contents located at a particular URL can and do change. The file contents located in a particular .torrent can’t really change; they are named by a checksum of their content, so if you change the content then the torrent is invalid. archive.org punts on this problem and just says that sometimes they change the HTTP contents and so you need to use a fresh/up-to-date .torrent. Expedient, if not particularly clean.

 

dynamically loading javascript

As near as I can tell, Javascript lacks a function to load more Javascript from a URL. There’s eval(), but that takes strings so it’s a bit of work. The usual hack is to add a <script> tag dynamically to the document which as a side effect causes the page to load the referenced script. Here’s a wrapper function for that, courtesy of this July 2009 writeup:

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

It’s overkill, but it’s cut and paste.I needed this to add jQuery to a page so I could then dump the URLs out of it with $("a").each(console.log(this.href))

Mike tells me he uses this bookmarklet to add D3 to pages. Node.js has the require() function. If you’re serious about dynamic code loading in browsers then requirejs looks good.

SFO Bravo cut back

I got my SFO Bravo airspace lasercut back. It’s pretty good, but not awesome. A great prototype.

Some thoughts on what to change for a second run:

  • It’s big! 9″ diameter, 2″ thick. It’s just a little too big for me, hard to comfortably hold in the hand. I think I could use the P2 Ponoko sheets and get a 6″ diameter object that felt better in the hand. OTOH that screws up the scale even more; the actual airspace has a 30:1 ratio (60nm diameter, 10,000′ thickness). Maybe I could drop to thinner sheets too, 3mm instead of 4.5mm
  • I don’t love the material (4.5mm light blue acrylic). The translucency is visually distracting and hard to photograph. It’s reflective and a lot of live light inside. And the mirror surface shows fingerprints and smudges from the paper backing glue like you wouldn’t believe. I’m wondering if this wouldn’t work better as a flat white solid material. Or maybe wood, or even metal.
  • After I took the photos I realized I kinda prefer it upside down. Ie: put the surface ring on the top of the object, the 10,000′ ring at the bottom. You can’t just flip it over, you half to flip each sheet (mirror image) to keep east/west correct. But looking top down all you see is one big sheet, no detail. You have to look from the ground to see the detail.
  • Assembly is a little challenging, particularly the 4000′ ring which has almost no detail, just symmetry. If I’m making these as kits I should engrave some notes on each disc. That’d work even better if it’s opaque material.
  • The square spindle hole in the middle with a lasercut matchstick to hold it together doesn’t work well. Has about ±5° of wiggle, either from imprecision in the hole or flex in the stick itself. Really needs to be glued together, I suspect, need to read up on that.
  • The actual cut lines are great. Really worked out well. I don’t think I need to do anything more with the geometry, really.
  • I should engrave a map on the top of the biggest disc. Coastline + airports + major roads, maybe. It’d be neat to engrave some map stuff on the bottom of the discs, too, but it’s a bit tricky with the overlaps.
  • Took about 45 minutes to put together, most of that time peeling the backing off the discs. Would take longer if I cleaned each disc properly and even longer if they’re glued.

Ken suggested making a shape that’s more like a bowl; just the hull of the object. That’d be neat because you could see inside it, too. 3d printing would be the natural way to do that.

Setting default print options on a Mac

My mostly-nice color inkjet has two tanks of black ink; a big one for B&W documents, a small one for color documents. By default my Mac sends all its jobs in color and the printer isn’t smart enough to realize that the whole document is monochrome so really, the cheaper big tank will work just fine. I want to default printing to grayscale.

Irritatingly, you can’t do this with the obvious way in a Mac. You can create new printer option sets and save them as new profiles, but there’s no way to change the default profile.

But there is a way, via the CUPS web interface hiding underneath MacOS. It never occurred to me that this would be there! The instructions in the linked blog post worked just great for me, I even have the same kind of printer. Two wrinkles.. I had to choose the second of the two printers, the first had no print options associated with it. And the “Greyscale Printing” option appears twice, I had to set both to make it work.

This may save me literally dollars a year.

 

sources.list.d

I love apt, the binary package manager for Debian and Ubuntu. It is fantastic. The only drawback is it’s always a bit scary to add extra repositories to the sources that it draws from. In particular I don’t care for editing the single global file /etc/apt/sources.list.

There’s a better way! In addition to /etc/apt/sources.list, apt will also read files in /etc/apt/sources.list.d. It only loads files named *.list for some reason, but it will append all those files to its group of sources. So you can keep the main sources.list file pristine from the distro and then add your custom repositories as separate files. Yay!

There’s also an extra tool for managing apt repositories from the command line, add-apt-repositories (aka addrepo). It has shortcuts for adding PPAs, also seems smart about getting signing keys.

Walks cut back from Ponoko

 

I got back my second Ponoko cut of my walks. It came out pretty well. The etching of my most popular tracks came through really nicely; can’t see it in the photo but the burnt area in the middle is also quite deep. Could be deeper actually. And I love the ragged outline of the shape, it’s quite nice.

What didn’t work well is the burning of the wood on the edges of the cut, like around the bottom edge. That’s a common enough problem when lasercutting wood and in some cases it can be quite pretty. But here its uneven and blotchy and distracts from the fine line cuts. I suspect there’s no way to control this through Ponoko and I’d be better served with some other material.