Pumpkins all Pumpkiny

It is a bit late for a Halloween post, but insert lame excuse here. Consider it a counter-balance to the force that causes Christmas decorations to show up in stores in September.

IMG_4305 This year I chose Toopy and Binoo, a Canadian children’s cartoon pair that you have probably never heard of, as subjects for my pumpkin carving. Unfortunately, the pumpkins shriveled quite quickly, and the designs didn’t lend themselves well to preservation, so by Halloween, they grew a toothpick scaffolding to maintain their facade. Next year, I believe I’ll try not cutting all the way through to avoid such issues. (I’m not sure what that technique is called, but some of the more artistic neighbors employed it to great effect.)

5 minute pumpkin Improvised pumpkin light Inside these gourds I used little battery-powered LED lights made for the purpose instead of actual candles. While LED lights don’t look nearly as nice as real candles, one need not care so much about potentially setting things on fire. On the evening of the 31st, as a few groups of kids had already arrived and absconded with their hard-earned treats, I found myself with a third pumpkin untouched by blade, but no light (or candle) to go in it, should I decide to carve it. Then, I remembered my extra spools of SMT LEDs from the cabinet lighting project. I calculated that a 9 volt battery could power three such LEDs for about 10 hours (that estimate was conservative by a factor of 3, it turned out – I need to go back to EE school). Thanks to various other projects, I already had some speaker wire with alligator clips on each end, so, in the course of 5 minutes, I threw together a functional pumpkin light, carved a few holes in the pumpkin, and called it a day. No need to clean out the guts when open flames are not a factor.

IMG_4423 For his first Halloween, Ian went as a dragon. Typical of his recent enthusiasm for all things space-related, Alex went as an astronaut. Instead of saying “trick-or-treat,” he would announce, “Hi, I’m Alex. I’m an astronaut!” Much candy was received, all the same.

December 3, 2013 · bob

Footprint, Part 2

My recent posting of ASCII art was intentionally subtle, perhaps overly so. If you haven’t figured it out by now, it is a C program that announces the birth of our second child. When compiled and executed, it prints:

Ian Yit-Sing Copeland Born 5 August, 2013 at 02:49 Weight 6 lbs 11 oz

In this post, I will explain how I created it.

Like many a C practitioner, I’ve always found International Obfuscated C Code Contest entries to be at once entertaining and mystifying. While I don’t consider this effort to be near the level of IOCCC entries, I thought it might be fun to try my own IOCCC-lite ASCII art program.

I knew I wanted the program to simply print an announcement string, in a non-obvious fashion. It also had to be easy to modify the program with the actual details on the day of the delivery. Indeed, I wrote this program several weeks in advance and modified the output in only a few minutes.

Thanks to the Can You Crack It challenge, I already had an RC4-like algorithm sitting on my disk. The plan then was simple: embed the key and ciphertext in the program, and just decrypt and print it. Of course, the ciphertext would be all binary, which is hard to encode in a compact manner in the source. Thus, I decided to store the ciphertext in base32 encoding.

I actually didn’t put much effort into obfuscating the code; the main issue was getting the size of the source code into around 600 characters, and doing that involved using typedefs and one-letter variable names already. By the time that was done, I didn’t change much. Apart from variable naming, the main obfuscation step was to change the base32 mapping table to consist only of numbers and symbols so that the embedded string would itself look like code. The code otherwise is pretty straight-forward.

My starting point, which base32-decoded and decrypted some placeholder text, looked like this:

#include <string.h>
#include <stdio.h>

char str[] = "43(:7&!#3&@>$%^|]:&6;<7*-$}9{;!*!$5{<;-=^8]#:5<@#%#&!5!@40207#9($3&)7<$1";

int b32dec(char *in, char *out, int len)
{
    int i;
    char alpha[] = "3:5[9&2^]{7}*<-8@=4(6#!>|)0+;1$%";
    for (i=0; i < len; i++)
    {
        unsigned char bits = strchr(alpha, in[i])-alpha;
        int j = (i / 8) * 5;
        switch (i % 8) {
            case 0:
                out[j + 0] |= bits << 3;
                break;
            case 1:
                out[j + 0] |= bits >> 2;
                out[j + 1] |= bits << 6;
                break;
            case 2:
                out[j + 1] |= bits << 1;
                break;
            case 3:
                out[j + 1] |= bits >> 4;
                out[j + 2] |= bits << 4;
                break;
            case 4:
                out[j + 2] |= bits >> 1;
                out[j + 3] |= bits << 7;
                break;
            case 5:
                out[j + 3] |= bits << 2;
                break;
            case 6:
                out[j + 3] |= bits >> 3;
                out[j + 4] |= bits << 5;
                break;
            case 7:
                out[j + 4] |= bits;
                break;
        }
    }
    return i/8 * 5;
}

int keysched(unsigned char *x, unsigned char *key, int keylen)
{
    int i;
    unsigned char tmp, a = 0;

    for (i=0; i < 256; i++)
        x[i] = i;

    for (i=0; i < 256; i++)
    {
        a += x[i] + key[i % keylen];
        tmp = x[i];
        x[i] = x[a];
        x[a] = tmp;
    }
}

int crypt(unsigned char *x, unsigned char *y, int len)
{
    unsigned char a;
    unsigned char b = 0;
    unsigned char tmp;
    int i;

    for (i=0; i < len; i++)
    {
        a = i+1;
        b += x[a];
        tmp = x[a];
        x[a] = x[b];
        x[b] = tmp;
        y[i] ^= x[(x[a] + x[b]) & 0xff];
    }
}

int main()
{
    unsigned char x[256];
    unsigned char key[] = "abcd";
    unsigned char crypt_text[sizeof(str)] = {};
    int len;

    len = b32dec(str, crypt_text, strlen(str));
    keysched(x, key, strlen(key));
    crypt(x, crypt_text, len);
    printf("%sn", crypt_text);
}

Micro-optimizing for source code size is unusual, and in some ways backwards to optimizing for generated code. For example, this change saved a couple of characters, but in the opposite way frequently done:

-            *o++ = d[0] << 3 | d[1] >> 2;
+            *o++ = d[0] * 8 | d[1] / 4;

Similarly, I found that combining unrelated functions was useful in eliminating the character waste of function definitions. There are likely a good deal more space-savers to be found; I quit when I got it small enough.

I experimented with a few different formats for the code. It turns out that I’m not terribly good at drawing ASCII. I abandoned a baby bottle as unrecognizable and went with a footprint after seeing this motif on some birth announcements. I hand-drew it, scanned it in, loaded as a background in an html document and then put dollar signs in the right places. Yes, cheating, but I am no artist.

                                          $$$$
                                        $$$$$$$$
                              $$$      $$$$$$$$$
                        $$   $$$$$    $$$$$$$$$
                       $$$$   $$$     $$$$$$$$$
                       $$$$             $$$$$$
                  $$   $$
                 $$$$            $$$$$$
             $  $$$$$       $$$$$$$$$$$$$
           $$$$  $$$$    $$$$$$$$$$$$$$$$$
           $$$$       $$$$$$$$$$$$$$$$$$$$$
           $$$$     $$$$$$$$$$$$$$$$$$$$$$$
            $$    $$$$$$$$$$$$$$$$$$$$$$$$$
                $$$$$$$$$$$$$$$$$$$$$$$$$$$
               $$$$$$$$$$$$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$$
              $$$$$$$$$$$$$$$
               $$$$$$$$$$$$$
               $$$$$$$$$$$$
                 $$$$$$$$$
                    $$$$

I wrote a python script to encrypt and encode the string to be embedded in the code. A second script tokenized the original C source and replaced dollar signs from the text template with code. The latter script is not perfect, but worked well enough that I could hand-edit the output in a few seconds to get something reasonable.

The gory details are available at github.

Finally, on delivery day, I discovered that Wordpress mangled C code included in posts. So I simply took a screenshot of the output and posted that instead, with a link to the original text. A picture of the newborn was hidden as a hyperlink from the footprint image.

Overall, the entire process took a couple of evenings from concept to completion, and I’m quite happy with the way it turned out. And, of course, I’m ecstatic about the inspiration: our newly arrived baby boy. We are very fortunate to have both Alex and now Ian in our lives, and silly C programs and fake man pages cannot come close to capturing our joy.

August 12, 2013 · bob

New house, new projects

This year I attained permanent residency in Canada, and our family also attained permanent residency in a different way, by buying our first, and probably last, house. We moved into it a few months ago, a fact I neglected to remark here, so if you are mailing me something, and for some reason read my blog, you’ll want to ask me for my new address.

With the house comes plenty of things to work on that are only marginally interesting, so I shall proceed to bore you with them from time to time.

I completed my first mini-project this weekend: installing task lighting in the kitchen. Our builder wanted to charge hundreds of dollars to put in (environmentally unsound) Xenon lights under the cabinets in the kitchen. I, having zero experience with house wiring, thought “I can do that!” Thus, we opted to have them install just the house wiring but we would take care of the lights.

led-spool When I was a wee undergrad, LED lighting was then just around the corner. Installations existed, but they were terrifically pricey. Now, hundreds of years later, you can get lots of them on a spool for a few tens of dollars. The particular ones I purchased (from Amazon) come as a ribbon of copper with sticky tape on the back. The ribbon is essentially one 16-foot wire with groups of three small LEDs and a resistor in series, and each group connected in parallel. To use it, you just cut to length, and then solder on power and ground from the +12 volt DC power supply (sold separately). I went for ‘warm white’ LEDs (2700K) which are a bit into the yellow spectrum; they are quite a bit softer than your average super bright white LED.

led-wiring2.jpg I mounted the LEDs via the aforementioned tape on the back of the cabinet valence, and the power supplies on the cabinet undersides. The power supplies are designed to plug into a wall socket, but since we had junction boxes for the lighting pre-installed, I simply cut the ends off the cords and wired the DC supplies directly into the boxes. The house lines were already wired to a circuit with a wall switch, so that was all that was required. Each strip worked the first time.

Under cabinet lighting All in all, it was a pretty uneventful install – the kind you want when dealing with A/C. I still need to staple up some hanging wires to the cabinet underside, but otherwise it’s finished, and the end result looks great.

August 4, 2013 · bob

It's faster because it's async!

Some Javascript developers, when presented with an API, think, “I know, I’ll make it async!” Now their users have a giant mess of a state machine implemented with callbacks and recursion, in a GC runtime that doesn’t eliminate tail calls, and two orders of magnitude worse performance. Normally, I wouldn’t care, because you get what you ask for when you write something in Javascript, but this time it happened to a project that I occasionally maintain for $work. And so I was sad.

So, far from expert in the ways of JS, I looked for a way out of this mire, and stumbled across task.js, which is what the kids are doing these days. It is a neat little hack, although it only works if your JS engine supports generators (most do not). Still, it seemed like a reasonable approach for my problem, so I decided to understand how task.js works by deriving my own.

I should note that if one’s JS engine doesn’t have generators, one can kind of emulate them, in the same sense that one can emulate goto with switch statements. Consider this simple example:


var square_gen = function() {
    var obj = {
        state: 0,

        next: function() {
            var ret = this.state * this.state;
            this.state++;
            return ret;
        },

        send: function(v) {
            this.state = v;
            return this.next();
        },
    };
    return obj;
};

var gen = square_gen();
for (var i=0; i < 4; i++) {
    console.log("The next square is: " + gen.next());
}
/*
Outputs:
The next square is: 0
The next square is: 1
The next square is: 4
The next square is: 9
*/

In other words, square_gen() returns an object that has a next() method which returns the next value, based on some internal state. The next() method could be a full-fledged state machine instead of a simple variable.

Certainly this is less tidy than the equivalent with language support:


var square_gen = function*() {
    var state = 0;
    while (1) {
        yield state * state;
        state++;
    }
};

(I’ll assume the existence of generators in examples henceforth.)

The send() function is interesting – it allows you to set the state from which the generator continues.


square_gen.send(16); /* => 256 */

The key idea is that generators will only do one iteration of a possibly large computation. When yield is reached, the function exits, and the computation is started up again after the yield statement when the caller performs another next() or a send().

Now, suppose you need to do something that takes a while, without waiting, like fetching a resource over the network. When the resource is available, you need to continue with that data. In the meantime you should try to do something else, like allow the UI to render itself.

The normal way one does this is by writing one’s code in the (horrible) continuation-passing-style, which is fancy talk for passing callbacks to all functions. The task.js way is better: write functions that can block (generators) and switch to other tasks when they do block. No, I’m not making this up – it is normal for a program in JS land to include a half-baked cooperative multitasker.

You can turn callbacks into promises, as in “I promise to give you value X when Y is done.” Promise objects are getting baked into various runtimes, but rolling your own is also easy:


function MyPromise() {
    this.todo = function(){};
}

MyPromise.prototype.then = function(f) {
    this.todo = f;
};

MyPromise.prototype.resolve = function(value) {
    this.todo(value);
};

That is: register a callback with then(), to be called when a value is known. The value is set by calling resolve().

Now, suppose you have an async library function that takes a callback:


function example(call_when_done) {
    /* do something asynchronously */
    call_when_done(value);
}

Instead of calling it like this:


    example(function(value) { /* my continuation */ });

…you can give it a callback that resolves a promise, which, when resolved, calls your continuation:


    var p = new MyPromise();
    example(function(value) { p.resolve(value); });
    p.then(function(value) { /* my continuation */ });

This is just obfuscation so far. The usefulness comes when you rewrite your functions to return promises, so that:


    function my_fn(params, callback) { /* pyramid of doom */ }

becomes:


    function my_fn(params) { /* ... */ return promise; }

Now you can have generators yield promises, which will make them exit until another next() or send() call. And then you can arrange to call send() with the promise’s value when it is resolved, which gives you blocking functionality.


    /* An async function that returns a promise */
    function async() {
        var p = new MyPromise();
        example(function(v) { p.resolve(v); });
        return p;
    }

    /* A generator which blocks */
    var gen = function*() {

        /* does some async call and receives a promise */
        var p = async();

        /* blocks until async call is done */
        var v = yield p;

        /* now free to do something with v... */
    }();

    /*
     * Run one iteration of the generator.  If the
     * generator yields a promise, set up another
     * iteration when that promise is resolved.
     */
    function iterate(gen, state) {
        var p = gen.send(state);
        p.then(function(v) {
            iterate(gen, v);
        });
    }

    /* Start a task */
    var p = gen.next();
    p.then(function(v) {
        iterate(gen, v);
    });

    /*
     * You can do something else here, like start another
     * generator.  However, control needs to eventually
     * return to runtime main loop so that async() can
     * make progress.
     */

A lot of details are omitted here like StopIteration and error handling, but that’s the gist. Task.js generalizes a lot of this and has a decent interface, so, do that.

In summary, Javascript is terrible (only slightly less so without c-p-s), and I’m glad I only have to use it occasionally.

July 17, 2013 · bob

AWS precursor

Let’s say it’s 1975, and you have a mountain of data (2 megs) to process, and a heap of cash. Whom do you call to run your Cobol? Your local airline, of course!

Excerpt:

IBM 360/195 for only 50 cents a SECOND

Guaranteed Turnaround! 2meg; 2314’s - 3330’s - 3420’s OS/MVT HASP/RJE MPSX-GPSS-PMS-SSP-CSMP Ans Cobol, Fortran G, G1, H, Assembler F & H, PL/1 F and PL/1 Optimizing and Checkout Compilers.

Our typical customer is knowledgeable in OS; has good working knowledge of JCL, Utilities and the functions of the compilers/assemblers he uses. […] Call or Write UNITED AIRLINES

Courtesy of a yellowed copy of Computerworld my dad found among his things. I noticed Google has scanned a lot of old issues but I couldn’t find this one in their archive.

No, I don’t remember those days.

June 4, 2013 · bob

Grepping 300 gigs

It’s fun when a problem is simple, yet the program to solve it takes long enough to run that you can write a second, or third, much faster version while waiting on the first to complete. Today I had a 1.8 billion line, 300 GB sorted input file of the form “keytvalue”, and another file of 20k interesting keys. I wanted lines matching the keys sent to a third file, where the same key might appear multiple times in the input.

What doesn’t work: any version of grep -f, which I believe is something like O(N*M).

What could have worked: a one-off program to load the keys into a hash, and output the data in a single pass. Actually, I had written this one-off program before for a different task. In this case, the input file doesn’t need to be sorted, but the key set must be small and well-defined. It is O(N+M).

What worked: a series of sorted grep invocations (sgrep, but not the one in ubuntu). That is O(lgN * M), which can be a win if M is small compared to N. See also comm(1) and join(1), but I don’t know off the top of my head whether they start with a binary search. I had a fairly low selectivity in my input set so the binary search helps immensely.

What also could have worked: a streaming map-reduce or gnu parallel job (the input file was map-reduce output, but my cluster was busy at the time I was processing this, and I am lazy). That would still be O(N+M), but distributing across P machines in the cluster would reduce it by around the factor P. P would need to be large here to be competitive with the previous solution from a complexity standpoint.

Making up numbers, these take about 0, 5, 1, and 20 minutes to write, respectively.

Of course, algorithmic complexity isn’t the whole picture. The last option, or otherwise splitting the input/output across disks on a single machine, would have gone a long way to address this problem:

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
sda              10.50     0.00  361.00    9.75 83682.00  4992.00   478.35   139.42  174.20    6.43 6385.95   2.70 100.00
sdb               0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00    0.00    0.00   0.00   0.00
sdc               0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00    0.00    0.00   0.00   0.00
sdd               0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00    0.00    0.00   0.00   0.00

You can’t go any faster when blocked on I/O.

Note the similarities with join algorithms in databases – variations on nested loop, hash, and sort-merge joins are all present above.

April 24, 2013 · bob

Cooking with gnuplot

Over the winter holidays I was put in charge of cooking one (of several) of the family dinners. At my house, a Christmas dinner can mean only one thing: prime rib is on the menu. The local grocery store had a great deal on rib roasts, so I bought a whole one. All seven ribs, 25 pounds of it. When it came time to cook this beast, I did plenty of reading, and settled on this seriouseats recipe. I guessed at about six hours to slow-roast the behemoth. But after a few hours of roasting, I decided it would be nice to know whether it would finish in time for the guests, or whether we would have to invent some pre-meal activities to stall.

Linear regression to the rescue! I had a leave-in meat thermometer plugged into the slab of cow, the type with a cable that runs outside the oven so that you can read the temperature without opening the oven door. It was then a simple matter to record the temperature every fifteen minutes and plot it to see how it was going. My uninformed guess was that the temperature curve is really sigmoid-shaped, but linearity is probably close enough around the target range.

Gnuplot can do linear regression for you:

f(x) = a*x + b
fit f(x) 'temp.dat' u 1:2 via a, b
set xrange [-5:160]
plot 'temp.dat' u 1:2 w linespoints, f(x)

This produces a graph like the image below, which shows that after 3 hours of cooking, the meat would be around 128 degrees (I started keeping track about three hours in).

In the end, I turned up the oven a bit in the last hour to speed things along. The meat turned out great, although I didn’t have too much luck with the in-between rest that the recipe promotes: there were still plenty of juices all over the place at carving time. Next time, I believe I’ll just turn the oven up to 500 deg. F when the interior target temperature is reached, and then do a normal rest afterwards. Another lesson learned: a full rib roast is perhaps twice as much as needed for eight people, but I am not one to complain about having prime rib leftovers for a week.

February 12, 2013 · bob

Mavened.

So, I’m applying a one line patch to a Java package, and oh yes, it needs maven. Hooray!

$ apt-cache depends --recurse maven | grep Depends |
     grep -v '<' | egrep lib.*java | sort | uniq | wc -l
203
[... start build and watch maven download another pile ...]
$ find ~/.m2 -name *pom | wc -l
851

I find it hard to believe that there are that many useful libraries in the world.

December 13, 2012 · bob

Olio

I neglected to write up anything on the blog in November despite it being the penultimate of months, so here’s a meandering catch-up post to atone. My apologies for the gratuitous self-linking that is about to ensue.

On Halloween: our 2-year old went as Kung Fu Panda (his favorite movie, and yes, shame on his parents for letting him watch movies) for Halloween this year. He was quite excited to learn that you can just go ask for candy from strangers and they will give it to you. He has mastered enough language to say “Pumpkin Scary,” which he did given every opportunity on seeing the skull I had carved on the pumpkin on the right. The other pumpkin is supposed to be McQueen from the Disney Cars property; Alex called it “Pumpkin Car.” They are now composting. So it goes.

On Thanksgiving: being a half-US, half-Canadian family, we get to celebrate both Thanksgivings: the fake one and the real one. And so we did. It was great spending time with the family and meeting up with some old friends in Atlanta, though we learned painful lessons about air travel with young children.

On Canada: I’ve now been in Canada for a little over a year. Among the observations I had detailed previously, I can now add these:

  • We do have a few days here in the summer that qualify as hot, but no, it does not get Georgia-in-August-hot.

  • Canadian Coca-cola is superior to non-KFP USA Coke, and despite what the PR machine in Atlanta will tell you, you can easily tell the difference between sugar and HFCS when you’re used to one or the other.

  • Canadian TV is even more a wasteland when there is no hockey.

On Bash Goto: per my last post, I considered how hard it would be to write an x86 emulator in bash. Conclusion: despite the potential good fun in simulating %eip using ’nl’ and sed, I’ll leave this task to someone else. However, I did improve my actual implementation of this somewhat. One easy win is to put the jump labels inside comments so that an ordinary run of the script won’t barf. And so that is what I did.

On Work: while I’ve been a contractor in name for the last year, I have now taken on some other contracts and thereby made this status more official. It was a tough decision to go this route versus, say, working on a salaried basis with some large, hypothetical mobile chipmaker with a Canadian presence, but so far I am happy with the choice. Most recently, I have been doing some Linux mesh networking stuff with Cozybit. It may be a while before any of it finds its way upstream (there are NDAs involved) but I claim that it is cool stuff. In the meantime, I get to continue slaying big data dragons at LP/Xmarks.

On HBase: speaking of HBase, two things have recently come to my attention. First, there is Hannibal, a cluster monitoring tool which was inspired by my post about beating gnuplot over the head with perl. I had nothing to do with its implementation otherwise, but it looks pretty cool. Secondly, I recently had an enquiry about my cache-oblivious code from some HBase folks. I’m not working on that either, but I am hopeful that something comes of it since it would be great if these ideas (not my own) percolate out into mainstream practice.

December 11, 2012 · bob