Binding (and unbinding) JQuery Event Handlers in a Complex Web App

I’m commonly placed in a tough situation. Here I am, working on a web related project and I would like to implement a lot of complex features via javascript. JQuery is the first library I’ve used and it has allowed me to at least dream of a functional, yet complex, web application. Typically, the first 25% of the javascript related work is a total breeze, thanks to jquery. The next 30-50% of the work becomes totally convulated, thanks to jquery being my crutch, and never diving in and bothering to understand javascript all these years. The final percent is ussually left on a wish-list of too-buggy-to-deploy and wouldn’t-it-be-nice.

Here I am again, endeavoring to build a complex and functional web application and this time I really want to get it right, and low and behold, I’m beginning to run into one of those typical problems.

Binding Events with JQuery

JQuery really makes this easy. I love it. I remember first starting off and writing a little bit of code like this:

$('.button').click(function() {
  $.get('/some/stuff', function() {
    $('.somestuff').append(....);
  });
});

and what not. Then I discovered that beloved .load() function. Really cut down on a lot of legwork I was doing. But there was always a slight problem. I always ended up with conflicting binds. There were various ways I worked around this, among other problems before .live() was around, but it was always a bit of a conundrum. I think this mostly deals with the approach JQuery takes towards usability. The focus is quickly accessing an object and binding the specified event, nothing more. It makes no effort to force any sort of design paradigm, which leads me to wonder, how should I handle this? I figure the first place to look for inspiration are in libraries I already currently use that solve this sort of design pattern.

Pyglet Event Handling for OpenGL/Python

I’ve used pyglet for a while now. It has a few design patterns for handling events that go something like this:

# first, it allows for decorators over a method
@windows.event
def mouse_press(...):
    pass # and do stuff

# and also a window method to push handlers of class instances
class SomeStuff(object):
    def mouse_press(...):
        pass # and go

some_stuff = SomeStuff()
window.push_handlers(some_stuff)

# and likewise, you can pop those handlers
window.pop_handlers(some_stuff)

The first design pattern doesn’t really solve any particular problem of mine and is pretty much already what is going on using jquery events. But the second pattern is something I would have considered impossible for me to accomplish in javascript, I’ve just never understood the language enough to consider it doable. But recently, I’ve been coming to understand the language a lot more and wrote a small utility for making better use of prototypal inheritance in javascript, js.js, and it struck me that this would be pretty easy to implement.

A Design Paradigm for JQuery Event Handling

First, its important to understand a small bit about the js.js utility. It’s somewhat based off of Crockford’s function that prototyped an empty constructor with a passed in object. The difference here is that js.js calls magic methods (instead of being an empty constructor) and allows one to pass in multiple objects and functions to be prototyped.

The design consists of two parts. A jquery plugin in the form of $.events.push() and $.events.pop() and a prototype inheritance pattern, optionally using the js.js function.

This is the plugin code:

$.extend({
    events: {
        recurse: function(args, action) {
            for (var x in args) {
                var obj = args[x];
                for (var k in obj) {
                    if (typeof obj[k].bind != "undefined") {
                        if (action == "push") {
                            $(obj[k].bind).bind(k, obj[k], obj);
                        } else {
                            $(obj[k].bind).unbind(k, obj[k]);
                        }
                    } else if (typeof obj[k].live != "undefined") {
                        if (action == "push") {
                            $(obj[k].live).live(k, obj[k], obj);
                        } else {
                            $(obj[k].live).die(k, obj[k]);
                        }
                    }
                }
            }
        },
        push: function() {
            this.recurse(arguments, "push");
        },
        pop: function(obj) {
            this.recurse(arguments, "pop");
        }
    }
});

The scenario is this. A lot of ajax events are very similar and would work across different loaded pages/forms. Where necessary, one could override an event to add extra functionality:

controls = {
  index: function(params) { $(...).load(...); },
  form: function(params) { $(...).load(...); },
  save: function(data) { $.post(..., this.index); }
}

events = {
  keyup: function() { ... },
  submit: function() { ...; this.save(data); return false; }
}
events.keyup.live = '.main .filter'; // just demonstrating access to live and bind
events.submit.bind = '.main .form';

user = function() {
  this.init = function() {
    $('a[href=#user]').bind('click', this.click, this);
  }
  this.click = function() {
    highlight(...);
    // do some more stuff;
    this.index();
    this.form();
    
    $.events.pop(one, two, three);
    $.events.push(this);
  }
}

var User = prototype(user, events, controls, object);

$(function() {
  var u = new User({url: '/db/User'});
});

This allows for common parts to be factored out when shared by many different objects. Picture five other objects alongside User. Some might override events and call the original, for example, events.submit.call(this, …).

This is a little rudimentary to start, but its a start none-the-less.

js.js say whaa

whaa? oh, right. Well Ive dug in deep to javascript. Well sorta, and it was all in an effort to evaluate whether to use prototype.js or mootools. My choice? neither. Instead I’ll focus my energy on expanding the default object in my js.js file. I know, its totally unoriginal. But lets face the facts, its 488 bytes.

And hot damn its amazing what 488 bytes can do. You can check it out here:
http://js.dasa.cc

Ive placed it in the public domain and what not. I think the focus will be mostly on custom constructors and lettings prototype() paste it all together. And of course, it can just be a staging ground for continued explicit prototypal declaration. It just uses whats there, and thats pretty sweet.

A New Way to Prototype with Javascript

Ive been doing alot of reading. One place that I keep happening upon is Crockford’s javascript pages. I dont reallly know who that is, but I’ve occasionally read he’s some sort of javascript legend. Well, I was looking over one of his pages, describing instantiating new objects, specifically:
http://javascript.crockford.com/prototypal.html

He talked about prototypal behavior, how it should work, and his simple function for doing so. Effectively, creating a blank function definition and then setting its prototype to the passed in object. I suddenly realized something. Ive been going about it all wrong with this class() business. Furthermore, what I had in place was his function but on steroids. Instead of initializing a blank function, I have what i was considering a sort of meta object that links to magic methods. And instead of setting the prototype to the object passed in, I set it to the all the objects passed in. So I took this thought and made some minor changes to the code, including being able to pass in objects, not just functions. Now I can write stuff like this,

x = {get: function() { return this.url; }};

function y() {
    this.get_url = function() {
        return x.get.call(this);
    }
};

var super_object = prototype(y, x);

and now super_object has the methods of y and x, where the order of the arguments decides precedence of inheritance. So I can create a new instance by

var a = new super_object({url: '/test/this'});
a.get_url() // returns '/test/this'
a.get() // returns '/test/this'

There some behind the scenes action here. What I did was abstract out the meta object with the intention of overriding it. But on some more thought, I think I will simply make it explicit, this way one could define any number of meta objects with their own magic methods, or if it so fits, simply pass in a blank function() {}, following Crockford’s lead. So it would look more like

var super_object = prototype(y, x, meta); // or whatever you call your meta, or
var super_object = prototype(y, x, function(){}); // for no magic methods or special constructors

Speaking on speed, Its important to note that there are no call’s or apply’s ever, though thats not to say one couldn’t write it into a custom meta object. Point being, it runs fast, just as fast as typing it all out manually. It doesn’t strive to be “classical” in any way. It simply focuses on custom constructors for multiple objects and a simple way to combine multiple objects, given order of precedence of arguments. It could be just as easily used in conjunction with explicit prototypal declarations. Seems like a win-win for keeping it simple.

*** Edit *** I forgot to mention, in the above example, x is an object that super_object inherited, but say you override x’s method and then needed to call it? well its a good bit shorter since its already an object, simply

x.get.call(this)

No need for specifying the prototype. I think this could easily become a simple design paradigm I might follow, Ill need more experience to judge properly though

*** Edit2 *** Heres a link to the code

Javascript’s not all bad

I gotta admit, through all the frustration and experimentation ive gone through with the language recently, its not so bad. At first I thought, “expressive? no way” b/c it seems like when you go to be expressive, you crop up with irreparable errors that eventually force you into one “expression”. Frustration follows each step, as is learning for me, yet I carry on.

Now Im feeling the chains loosened. Not so much do I feel tied to a particular paradigm when writing out bits of javascript, particularly, paradigms that Ive brought over from projects Ive worked on in python. Im looking at new ways to do things in javascript, in particular I was pretty happy to see getters and setters in javascript 1.5, Ive always enjoyed them for a couple reasons.

Getters and Setters provide a consistent API
Alot of times, we find ourselves writing utilities and libraries of utilities to perform particular actions. When using these libraries (or someone else’s for that matter), its important to have a consistent API so one can think about the task at hand, not the details of the API. If you have a series of attributes on an object, but some of them might be dependent on others, getters and setters might prove useful for consistency in accessing object properties. If you have the following properties, parent, children, x, y, w, h, batch, visible, well keeping in mind to call get_parent() or batch() or whatever while calling .w and .visible for others really blows. All I can say is that I hope theres auto generated documentation to keep at hand, which will be a pain if theres long time periods in between using the library.

Getters and Setters provide a mechanism for error checking
Another use I’ve found for getters and setters is error checking. It provides a centralized point to assert the value is something valid before getting or setting. So say I have

widget.x = input

Theres alot of places I could check input, but if Im getting input and setting x from different scenarios that crop up, being able to check it with a setter on x would consolidate alot of code.

Anyway, having access to getters and setters in javascript will be useful to say the least. Embracing the functional style of javascript looks like a win-win situation. Unlike others, I have no gripes with calling object.prototype.method.call(this) but even that is probably unnecessary in alot of situations, trying to fit a bull with a shoehorn.

Whats wrong with javascript prototype?

** Edit **You can see my current approach to these frustrations here: http://js.dasa.cc

O thats easy, ok lets write up a base object we’ll want to inherit from (note, I would not actually write a this.get_name to retrieve a this.name, duh, its all in the spirit of an easy read)

function A(name, age) {
  this.name = name;
  this.age = age;
  this.get_name = function() { return this.name; }
  this.get_age = function() { return this.age; }
}

Good, ready? oh shit, wait a sec, according to MDC we were being naive. Now the only way to call the get_name and get_age functions is with an instance of A. Well crap, that doesn’t help inheritance much, prototypal or not. Alright so lets do this right.

function A(name, age) {
  this.age = age;
  this.name = name;
}
A.prototype = {
  get_age: function() { return this.age; },
  get_name: function() { return this.name; }
}

Yeay, yippie for us, now lets extend A with B

function B() {};
B.prototype = new A;

Yeay, yippie, now lets make C with an extra param and function and extend A.

function C(name, age, title, money) {
  this.title = title;
  this.money = money;
};
C.prototype = new A;
C.prototype = {
  get_title: function() { return this.title; },
  get_money: function() { return this.money; }
}

Good? alright lets.. o crap! it doesn’t work. Right, right, thats right, I totally erased the A prototype by using the prototype = {} syntax, ok so that syntax is no good for working with inheritance unless its the top level thing, but crap, i dont wanna think about that. Whatever, lets just fix C for now though readability will be a little funky, hey .. i know! lets just say if i use the prototype = {}; syntax, thats a way to differentiate it as a top level parent! yeah! thats great justification *cough*not*cough*

anyway

function C(name, age, title, money) {
  this.title = title;
  this.money = money;
};
C.prototype = new A;
C.prototype.get_title = function() { return this.title; }
C.prototype.get_money = function() { return this.money; }

ok, lets fire this bad boy up and test C.. Where the hell is my name? and age!? son of a.., I see, so i need to manually call the constructor of the same damn thing that I C.prototype=’d

alright, its cool, lets fix it, I can dig it. Lets add that A.call

function C(name, age, title, money) {
  A.call(this, name, age);
  this.title = title;
  this.money = money;
};
C.prototype = new A;
C.prototype.get_title = function() { return this.title; }
C.prototype.get_money = function() { return this.money; }

Sweet buttery buttons! It works! wait a sec.. why is this code running slower then before? Yeah yeah, theres creating the name and age now that wasn’t before but its more… its .call() ! Wth?! why is this causing it to go slower? Alright alright, its cool, lets just… migrate these object property inits out of the contructor and into a prototype function that will handle the needs of all that inherit it since its mostly the same.

Ah hell, im hungry, maybe another day..

A Javascript Class with magic methods

Hey, ok so this is what i have so far, totally preliminary

function class() {
    var that = function() {
        this.__init__(arguments[0]);
    };
    that.prototype = new object;

    for (var x=arguments.length-1; x>=0; --x) {
        var m = new arguments[x];
        for (var i in m) { that.prototype[i] = m[i]; }
    }
    this[arguments[0].name] = that;
}

function object() {
    this.__init__ = function(kwargs) {
        for (var k in kwargs) {
            this[k] = kwargs[k];
        }
    }
}

Short, right?

Then I can write something like this,

class(A, object)
function A() {
    this.get_name = function() {
        return this.name;
    }
}

class(B, A)
function B() {
    this.get_age = function() {
        return this.age;
    }
}

class(C, object)
function C() {
    this.__init__ = function() {
        this.name = "OVERRIDE";
    }
}


var a = new A({name: "Daniel", age: "24"});
var b = new B({name: "David", age: "25"});
var c = new C({name: "John", age: "26"});

effectively just sticking a little header over normal javascript functions, and everything works as one would expect.

a.name // returns Daniel
a.age // returns 24
b.get_age() // returns 25
b.get_name() // returns David
c.name // returns OVERRIDE

And to boot, it executes at the same speed as writing it the “native” way. Here’s what i have for “native” (im a noob so correct any errors)

function object() {}
object.prototype.init = function(kwargs) {
    for (var k in kwargs) {
        this[k] = kwargs[k];
    }
}

function A(kwargs) {
    this.init(kwargs);
}
A.prototype = new object;
A.prototype.get_name = function() {
    return this.name;
}

function B(kwargs) {
    this.init(kwargs);
}
B.prototype = new A;
B.prototype.get_age = function() {
    return this.age;
}

function C() {
    this.name = "OVERRIDE";
}

I ran a test importing each implementation, respectively, and got similar results in execution speed and memory size. I created 100,000 thousand objects of each A, B, C and each method occupied 78mb according to top, and each method consistently ran between 2100-2300 ms with variance that occasionally hit 3000 ms. Ultimately its not surprising as all the class function i wrote does is auto write how you would do it natively. What Im surprised about is theres no extra cruft when the javascript runtime compiler handles it. I never intended this to be useful, it was all part of an experiment delving into javascript scope and messing with constructors so i could evaluate the use of a library like prototype.js or mootools.

But hell, so far this little bit of code is turning out to be fairly useful. I imagine if i write more magic methods, the memory size will increase by a small amount. I half expected to see a difference in memory since the C is much more stripped down in “native” version vs the version with __init__ cruft from object function.

This has all been using spidermonkey-bin (smjs) so now im curious to see how other javascript implementations handle the details, as from the get-go i expected a huge increase in memory (not that I know anything about anything) from functions existing in the constructor and then being linked to a prototype, and all those “new” instances called in class. But it all seems negligible, in spidermonkey anyway. This could be a totally different story in IE, lol

for reference, heres my lame-o profile code (i know, i know, but it was enough to find all sorts of issues when exploring javascript scope and constructors)

var date1 = new Date(); 
var milliseconds1 = date1.getTime(); 

load('custom.js'); // point this to which script to test
var l = [];
for (var j = 0; j < 100000; ++j) {
    l.push(new A({name: "Daniel", age: "24"}));
    l.push(new B({name: "David", age: "25"}));
    l.push(new C({name: "John", age: "26"}));
}

var date2 = new Date(); 
var milliseconds2 = date2.getTime(); 

var difference = milliseconds2 - milliseconds1;
print(l.length)
print(difference)

*** EDIT *** Also, function object needs a class(object) so you can call its magic methods, so in C this.__init__ = function(kwargs) { object.prototype.__init__.call(this, kwargs) }
Of which, im a little confused, b/c I originally expected to not work. Anytime a Class(X) is called, its constructor gets replaced, so another Class(X) later on will be referring to that replaced class which i thought would cause some kind of error, or so i would think. So deep inheritance might cause some bad mojo with the amount of memory or hell if i know. I haven’t looked into that yet
*** EDIT 2 *** Also, im not sure how much of a “class” this is really, if it turns out useful i may find a different name, maybe just call it “prototype” so like
prototype(A, object)
function A() {};
var a = new A({name: “daniel”});

Baffling Results from my Javascript Class(-ishness)

** Edit, regarding the following, I suddenly realized what the problem was, .call is slow and was used in the “native” approach. Nevertheless Ive had positive result following through on multiple inheritence and magic methods. refer here, http://wp.me/piHZk-14 **

Ok, So recently I’ve taken an interest in javascript. By interest I mean taking it more seriously as a language. One of the first things I wanted to do was to see if I should adopt a framework like mootools to allow for classical inheritance type of stuff or if I should develop using the prototypal javascript inheritance. This lead me to really dig in deep to javascript scope and all of its nuances, especially considering prototype.

Along the way, pecking away at my smjs console (aptitude install spidermonkey-bin), I eventually wrote this function class() {} as I was trying to see what I could get away with in poking at the scope of functions and their prototypes. I was particularly annoyed with a seperation between the constructor and that which was prototyped and the foresight required, which Im going to lack since Im new to the game. Anyway, heres the function,

function class() {
    var that = arguments[0];
    for (var x=arguments.length-1; x>=0; --x) {
        m = new arguments[x];
        for (var i in m) { that.prototype[i] = m[i]; }
    }
}

effectively, this allowed me to write my prototypes in the constructor as well as extend functions. It was all in the name of learning and I wasn’t considering it practical. So basically I wrote stuff like

function object() {
    this.init = function(kwargs) {
        for (var k in kwargs) {
            this[k] = kwargs[k];
        }
    }
}

class(A, object)
function A(kwargs) {
    this.init(kwargs);
}

var a = new A({name: "Daniel", age: "24"});

I was also playing around with object constructors (unsuccessfully) curious as to if i could implement magic methods that could be inherited and run automatically, but yeah, that went no where so i was all but about to abandon this whole excursion when I decided, before I do, I wonder how much more memory my function class() {} uses and how much slower it is from doing it the standard way. By standard, I mean what I basically learned from perusing the net and from MDC javascript 1.5 Engineering Model Example. Heres what I have for the “standard” way

function object() {}
object.prototype.init = function(kwargs) {
    for (var k in kwargs) {
        this[k] = kwargs[k];
    }
}

function A(kwargs) {
    object.prototype.init.call(this, kwargs);
}

var a = new A({name: "Daniel", age: "24"});

Now my profiling isn’t very scientific I suppose, I used top and timed the execution from within javascript, but the results are consistent. What I basically did was this

var date1 = new Date(); 
var milliseconds1 = date1.getTime(); 

load('test2.js');
var l = [];
for (var j = 0; j < 5000; ++j) {
    l.push(new A({name: "Daniel", age: "24"}));
}

var date2 = new Date(); 
var milliseconds2 = date2.getTime(); 

var difference = milliseconds2 - milliseconds1;
print(l.length)
print(difference)

where load(‘test2.js’) was the “standard” way and load(‘test4.js’) in a seperate file was my way. The first thing that caught me off guard was that memory consumption was the exact same. I was half expecting my method to take more memory b/c the function definations existed in two places, but I guess the javascript runtime compiler doesn’t cause this to happen, so yippie freaggin do da. Now what left me baffled was that my way was consistently faster then the standard way. Here are the time results, running 10 in a row

* all times are in milliseconds
=== Standard ===
54
58
49
55
55
53
53
49
53
52

=== My Way ===
42
41
42
45
45
42
42
48
48
48

The numbers were close, so then i decided to increase the number of objects created to perhaps provide a more significant and visible difference. So I increased the number of objects from 5,000 to 500,000.

=== My Way ===
5716
4257
4229
4331

=== Standard Way ===
7601
4866
4913
5564

Its as if the javascript compiler runs faster instantiating an object property and linking it to a prototype then it does when just instantiating a prototype property. And it doesn’t require any extra headway in memory to do it.

If theres any javascript ninja’s that can explain whats going on, thatd be simply awesome. Speaking of which, im gonna go find mailing list now…

Motionbuilder from AutoDesk and OpenCV in Harmony

For anyone ever curious, recently I have delved into the world of motion capture, image recognition and the likes for the past week. The task, build a headset with a mounted usb camera that tracks the eye and moves it accordingly to a model in motionbuilder. Just to get this out there, I know nothing about 3D art, modelling or anything of the likes, including motionbuilder. This would be the first time I’ve ever even used the software.

That aside, I asked someone for a model with a moveable eye and what i got was basically a head with the eyes fixed to a null point. when the point moves, the eyes move. So next was to get the data I had been receiving from opencv to motionbuilder. Just to clarify, currently I am simply using a default haarcascade for face detection so as to track something with motion on the screen. Im taking the center point of the face and using it as proof of concept to move the null. Books are expected Monday so i can delve into tracking the pupil.

The thing about motionbuilder though is its python implementation is hooorrible. As in the worst of the worst. If i were to say its barely usable, i might be hitting the head on the nail for some, but it still feels like a bit of an overstatement. That said, its still great that it has python support so kudos for someone atleast trying to implement it. Im sure its a daunting task for the type of project.

Let me briefly describe the limitations for any that might be unfamiliar. For one, the python version used is 2.4.1 and it comes with pyfbsdk library and nothing else. Considering the lack of documentation for the python module, i would typically resort to something like,

import inspect
for x in inspect.getmembers(FBSystem().Scene):
    print x

but as i said no libraries. So the first thing i did was go to the python site and download 2.4.1. Its not actually listed there but just click on whatever the latest 2.4.x is and then change the revision number to 2.4.1 in your address bar. Download, install, then copy over from your c:\python24\Lib directory all the .py’s to your program\ files\\autodesk\\python\\lib folder. Now you can you do some basic stuff like inspect.getmembers. Secondly, the python console in motionbuilder is horrid. You can type in no more than one line at a time. Syntax error’s have crashed the console. I cant up-arrow to previous commands. The output is limited to whatever the last command was that you ran, aaaaand the text of the output isn’t selectable. So that means no copy and paste of all the methods of whatever after you inspect.getmembers… aaargh! I still have the screenshot on my desktop somewhere …

But fear not! b/c there is telnet. From the python console from within motionbuilder, there is a tab that lets you enable telnet. So you can open up a telnet client and go to addy 127.0.0.1 port 4242 and hopefully you should be presented with a python console. I say hopefully b/c i didn’t have the best of luck the first few times b/c of motionbuilder (and/or my own) quirkiness.

And finally, the real bugger in it all is that if you write a python script that takes some time to run, all of motionbuilder locks until the script is finished. So this means no script thats running in the background waiting to receive data. Instead, this data needs to be sent via the telnet link to motionbuilder. I found some great resources, but mainly ill list this particular one,

http://chrisevans3d.com/tutorials/mbui.htm

He’s got some great sample code for integrating a seperate wxpython script into motionbuilder and breaks down a number of things as well. Unfortunately, his code for making use of telnetlib from within a seperate python instance to issue commands to motionbuilder didn’t work out so hot, which is precisely what prompted me to write about this. The code he had listed seemed a bit cryptic with these read_until’s with params of 0.1 and 0.01, and i didn’t see anything of the sort mentioned in python docs (barely looking of course) so I wrote my class for doing this and saved it in a mbpipe.py and it reads as follows

import telnetlib

class MBPipeline:
    def __init__(self, host="127.0.0.1", port="4242"):
        self.tn = telnetlib.Telnet(host, port)
        self.tn.read_until('>>> ')

    def call(self, command):
        self.tn.write(command + '\n')
        r = self.tn.read_until('>>> ')[:-6]
        try:
            return eval(r)
        except:
            return str(r)

Now from my script where i am doing opencv stuff (or simply from your console) I can do a

from mbpipe import MBPipeline
mb = MBPipeline()
mb.call('FBSystem().Scene.Components[216].PropertyList.Find("Lcl Translation")')

and what it returns is the actual tuple from motionbuilder. In any case where the string from the telnet session can be eval’d, you’ll receive the object. Otherwise just the string.

Just thought I’d share. 😀

I may comment later on my experiences with opencv, which so far have been great. QueryFrame, haarcascade, convert to image and push over to pyglet and render to screen my live video (note, opencv has its own windowing and controls which most will probably find useful).

Pandora minus the cruft with XUL

I made this a while back then found out a couple months ago that pandora has a ?cmd=mini getvar that shows a smaller player. So I updated this xul package I made. Im no expert or even novice in xul. Very basic stuff is all I’ve cared to do, but i figured this was a great way to use the service minus the cruft and get it out of my browser. Google Chrome’s save as application is great too if your on windows.

Pandora via XUL can be downloaded from this link: http://dasacc22.googlepages.com/pandora.tar.gz

This should work on any platform with xulrunner. You can run it from linux by

$> xulrunner application.ini

in the folder, similarly on other platforms. Ive also created a sh shortcut in the folder that runs

$> nohup xulrunner application.ini > /dev/null 2>&1 &

to background the service. When starting from the shortcut, click “run” to start it. I have adobe flash complain on startup saying it prevented something dangerious from happening, i guess b/c the flash object is embedded in XUL?? And that it shutdown the offending application. Just click ok and it runs just fine. No need to click settings like it prompts you to (it doesn’t seem to launch settings anyway).

If the ?cmd=mini ever dissappears you can just update the xul package by opening chrome/content/main.xul and replacing the embed object with the one from the site.

IBM Sliding Puzzle Contest

So someone passed onto me a pdf for an IBM sliding puzzle contest. Basically, it consists of a 3 row by 3 column puzzle with one empty space, you know the ones, and you have to write a piece of software that solves for the answer. The instructional pdf suggests that while its acceptable for your answer to be over 20 moves, it should optimally be about 20 or less and be relatively quick.

At first I had no clue about how to do something like this but found the idea very interesting. Four hours later I had a python script that solves for all possible solutions up to how ever many moves you choose it too. Turns out the shortest answer is 12 moves, according to my script. I haven’t validated the 12 move answer, but i did validate a 14 move answer by hand with success (which was actually a twelve move answer with a repeat move making it 14), and i see little reason for the 12 move answer to be wrong.

Anyway, here it is in all its glory

puzzle = ['0', '4', '2', '5', '8', '3', '1', '7', '6']

answers = []

possible_moves = [
    [lambda p: swap(p, 1, 0), lambda p: swap(p, 3, 0)],
    [lambda p: swap(p, 0, 1), lambda p: swap(p, 2, 1), lambda p: swap(p, 4, 1)],
    [lambda p: swap(p, 1, 2), lambda p: swap(p, 5, 2)],
    [lambda p: swap(p, 0, 3), lambda p: swap(p, 4, 3), lambda p: swap(p, 6, 3)],
    [lambda p: swap(p, 1, 4), lambda p: swap(p, 3, 4), lambda p: swap(p, 5, 4), lambda p: swap(p, 7, 4)],
    [lambda p: swap(p, 2, 5), lambda p: swap(p, 4, 5), lambda p: swap(p, 8, 5)],
    [lambda p: swap(p, 3, 6), lambda p: swap(p, 7, 6)],
    [lambda p: swap(p, 4, 7), lambda p: swap(p, 6, 7), lambda p: swap(p, 8, 7)],
    [lambda p: swap(p, 5, 8), lambda p: swap(p, 7, 8)]
]

def serialize(p):
    return ''.join(p)

def swap(L, m, t):
    if L[t] is '0':
        L[t] = L[m]
        L[m] = '0'
        return serialize(L)
    
def no_dups(S):
    if len(S.split("-")) != len(set(S.split("-"))):
        return False
    else:
        return True

def search(tree, index=0):
    if index < 12:
        for each in tree:
            for i, val in enumerate(list(each.split("-")[-1])):
                if val is '0':
                    generation = []
                    for move in possible_moves[i]:
                        result = each+"-"+move(list(each.split("-")[-1]))
                        if "123456780" in result:
                            answers.append(result)
                        elif no_dups(result):
                            generation.append(result)
                    search(generation, index+1)

search(["-"+serialize(puzzle)])
shortest_answer = sorted(answers)[0]
print "=========="
print "Shortest Answer: " + str(len(shortest_answer.split("-"))-2) + " Moves"
print "++++++++++"
print shortest_answer

Edit: I just thought i would add,
yeah so the thing that was the turning point for solving this thing was how you look at solving the puzzle. Ive always looked at those puzzles as, ok what can i move into the empty space and rotate these pieces around and this and that but thats totally the wrong viewpoint. The way to visualize solving the answer is to look at the empty space as your focus and to move the empty space around, pushing the other numbers around into place. The puzzle suddenly becomes eaiser to solve by hand on your own and thats how the program solves for the answer too, by moving the empty space around, not trying to calculate how to get a particular number to its destination