Archive for the ‘Computer Nerdiness’ Category

Programming is Magic

Wednesday, January 13th, 2010
I first started programming when I was 10. Dad had CompuServe, a 28.8Kbps modem and a laptop the size of a microwave. It was summer break and during the evenings he would let me log in to a MOO. (Think World of Warcraft but entirely text based and it had a programming language).

Every night I would open up the laptop, dial in, launch some ancient, long-since defunct shell and log in to the MOO. It was exciting every time. Using the MOO was pretty straightforward. Once you logged in you were in a room. A room was just a screen of descriptive text followed by a list of commands you could type in like ‘North’ or’South’. You were also usually given a list of people in the room you could chat with.

My memory of the MOO is almost 20 years-old and fading, but I’ll never forget the first time I programmed. One night I was chatting in a room with someone when he spoke a command I’d never heard. In an instant my character was whipped up into a tornado of wind and thrown across the world into a secret room. HOLY SHIT COOL! Of course I asked him:

“How did you do that?”

“It was a spell.”

“How do I use spells?”

“You need a quota. I can get you 10k”

Of course a quota was disk space and the spell was a bit of code in the MOO’s programming language. But to me it was spell book and a magic spell. He set me up with a quota and told me how to copy paste what he had done. The whole process was arcane — and I loved every step. I think I had to use Gopher and maybe even Emacs. It was all so new and mysterious. Eventually I adjusted my new spell. Now a giant  earth elemental appeared out of nowhere, grappled them in massive hands of stone and ran straight to my secret room. Everyone else had lame tornados.

I was on the path to becoming a wizard. Actually, at this point the number of possible paths my life could take that intersected with ‘cool kid’ or ‘not a nerd’ began to asymptotically approach zero.

Prototypes in Javascript

Wednesday, December 30th, 2009

Inheritance allows programmers to reuse code. Code reuse is the holy grail of software development best practices. The most common form of inheritance relies on an idiom known as the Class. The Class is a blueprint of what an object should look like once instantiated. It is declaritive and exists at compile time. Any Class can inherit another Class and override methods declared by it’s parent or add new methods.

Example (I hate using metaphors to describe software, but it will have to do):
A house blueprint defines a building with four walls and two windows. A villa blueprint adds plans for a jacuzzi and refers the builder to the house blueprint for everything else.

Another implementation of inheritance uses Prototypes instead of Classes. Prototypes are instantiated objects. Programmers take a Prototype and add or remove methods and properties to create a new object. Prototypal inheritance is procedural and happens at runtime.

Example (You’re about to see why I hate metaphors — they produce odd outcomes):
You build a prototype airplane. For this metaphor to work you need to imagine that this prototype can make infinite copies of itself, and the copies stay in perfect sync with eachother. Remember the Mirror Image spell? Like that. If the original prototype gets a scratch, all the copies instantly have the same scratch. If one of the copies is scratched, it doesn’t affect the original. Now, take one of those copies and replace the wings. That’s prototypal inheritance.

Using Classes, you are reusing the directions for building the object. Using Prototypes, you are reusing objects.

This is what prototypal inheritance looks like in a fake programming language I call OolongScript:

var biplane = { 'sound' : 'buzzZZZzzz',
'color' : 'blue',
'numWings' : 4,
'chanceOfFailure' : 60%;}

var jet = create(biplane); //jet is a magic copy of biplane

//Let's improve our biplane copy
jet.numWings = 2;
jet.chanceOfFailure = 5%;
jet.weaponry = "Smart Bomb";

//okay, how many wings does the jet have?
print jet.numWings
>> 2
//What color is the jet?
print jet.color
>> blue

//Did we mess up the biplane?
print biplane.numWings
>> 4
print biplane.weaponry
>> Undefined

//All airplanes should be red, not blue.
biplane.color = 'red'

//What color is the jet?
print jet.color
>> red

//I want an F22 Raptor, not some lousy generic jet
var raptor = create(jet)//Create a magic copy of the jet.
raptor.stealth = True
raptor.sound = "looooooooud"

print raptor.weaponry //should be "Smart Bomb" as defined on the jet.
>> Smart Bomb

print raptor.color //should be red, just like the biplane
>> red

The raptor is built on a magic copy of the jet which uses a magical copy of the biplane prototype as a base. The jet and raptor replace the bits they don’t want and add new stuff. This doesn’t affect the biplane. But when the biplane changes color, the jet is automatically updated, as is the raptor.

Prototypal Inheritance in JavaScript (not OolongScript)

Javascript facilitates inheritance using prototypes, but where OolongScript has “create” for making magic copies, JavaScript has constructor functions and the prototype property. This is not better, it’s just harder to understand. But working from the example above, we should be able to understand what is happening.

The code for creating the biplane is the same:

var biplane = { 'sound' : 'buzzZZZzzz',
'color' : 'blue',
'numWings' : 4,
'chanceOfFailure' : 60%;}

In JavaScript we want to ‘construct’ a jet by calling a function. It might look like this in OolongScript:

var this = create(biplane); //Set this to a magic copy of the biplane
var Jet = function(){
//Let's improve our biplane prototype
this.numWings = 2;
this.chanceOfFailure = 5%;
this.weaponry = "Smart Bomb";
return this;
}
var jet = Jet();

Except in JavaScript there is no ‘create’ function. So how does JavaScript set the variable ‘this’ to a magic copy of the biplane? Like so:

// The Jet function remains the same. 'this' is a JavaScript keyword that we don't need
// to define anywhere. We tell JavaScript what 'this' should be later using the 'new'
// keyword, as you'll see below.
var Jet = function(){
//Let's improve our biplane prototype
this.numWings = 2;
this.chanceOfFailure = 5%;
this.weaponry = "Smart Bomb";
return this;
}

//Set the prototype property of the function Jet
Jet.prototype = biplane;

// Calling a function with 'new' in front of it tells JavaScript to bind
// the keyword 'this' to a magic copy of the prototype property of
// the function Jet, which we set the line above.
var jet = new Jet();

This whole setup is really hard to wrap your head around. Understanding prototypal inheritance is much easier when you can ‘create’ magic copies of objects at will. Wouldn’t it be nice if JavaScript had the ‘create’ function like we did in OolongScript? I give you my slightly simplified version of Douglas Crockford’s ‘create’ function:

var create = function(o) {
var F = function () {};
F.prototype = o;
return new F();
};

I leave it as an exercise to the reader to figure out how this works.

Hint: replace ‘F’ with ‘Jet’ from the example above and ‘o’ with ‘biplane’.

ActiveRecord Style Validation using SQLAlchemy and Elixir

Sunday, April 20th, 2008

Update: Turns out I missed the boat on this one. This has already been implemented in Elixir.

I just spent the better part of today putting together the pieces in order to create ActiveRecord like validation in my Elixir models. Here is what I wanted to be able to do:


class Tag(Entity):
label = Field(String(200))
before_insert('validate_label')
before_update('validate_label')

def validate_label(self):
Some validation code here

I wanted to be able to write custom validation methods in my model and then hook them into sqlalchemy events like ‘before_update’ so that before any data goes to my app’s database it is first validated. Then at that point I can catch it and redirect the user to change the invalid data.

Earlier I had stumbled upon this code by Beachcoder. While I was excited to see that it could work, I was having a difficult time understanding the approach, largely because a lot of this stuff was essentially a black box to me. So I got under the hood and came up with my own approach. I’m not sure if it’s better or even complete, (even though it seems to work and I pass all my unit tests), but that’s why I am posting it here. Feedback is welcome!

from sqlalchemy.orm import MapperExtension
from elixir.statements import Statement
class HookExtension(MapperExtension):
"""
Given a hookname and a list of callbacks, (which are just methods associated with the instance)
this mapper extension overrides the given hook with a function that executes each of the callbacks.
"""
def __init__(self, hookname, callbacks):
MapperExtension.__init__(self)
def execute_callbacks(mapper, connection, instance):
for f in callbacks: getattr(instance,f)()
setattr(self, hookname, execute_callbacks)

def create_hook_statement(hookname):
"""
A simple class generator. Given a sqlalchemy hook name like 'before_insert' or 'before_update' creates
an Elixir statement. The statement excepts a list of 'callbacks' which are names of methods associated
with the Elixir class that will be executed based on the hook.
"""
class HookStatement(object):
def __init__(self, entity, *callbacks):
ext = HookExtension(hookname, callbacks)
entity._descriptor.add_mapper_extension(ext)
return HookStatement

before_insert = Statement(create_hook_statement('before_insert'))
before_update = Statement(create_hook_statement('before_update'))

Motorola Q Review

Tuesday, September 5th, 2006

I have had the Motorola Q for 3 months. People want to know — do I like it? Well people, here is my answer:
General Overview
The Q is the latest Smartphone offering from Motorola. It is running Windows Mobile 5.0 Smartphone edition. It has a full QWERTY keyboard, a bright, large screen and a very thin profile that borrows from its cousin the RAZR.Motorola Q

The Good

The Q has a lot of upside.

Price: At $200 with the purchase of a new Verizon plan, the price can’t be beat. If you buy it at full retail, it comes with the slightly heftier price tag of $500. Compare this to similar offerings and you will find it is still a very modest price.

Form Factor: The Q fits nicely into the palm of your hand. Although its width initially had me concerned, that feeling quickly passed as soon as I realized how easily it fit into my shirt pocket. It’s also slips comfortably into normal pants pockets and its presence is not as easily detected as the clamshell models I previously preferred.

One drawback I see with the shape of the Q is that when using it as a phone, a wide portion of the screen is pressed against your cheek, and so it is constantly smudged.

The Keyboard: The Q is the first phone of its class with a full QWERTY keyboard. Responding to email, text messages and entering data is a breeze. There are a few problems and drawbacks with the keyboard. The keys are rather hard plastic and are not very comfortable — I have a texture phobia and these keys do not help matters. I have a feeling normal people won’t care. Also, you will never be able to text IDOL04 to vote for Taylor Hicks because the letters underneath the numbers do not line up the same way as on a traditional phone. You’ll have to ask your non-Q owning friends to help you out.

Smartphone Software: This phone can accomplish almost anything you need it to accomplish. Keep in mind that the Q does not have a touch screen — it’s a Smartphone not a Pocket PC. This means that you can’t edit documents since only the Pocket PC software will allow you to do that. The Q is the first Smartphone with a QWERTY keyboard, and as such it is the first Smartphone where the ability to edit documents would actually be a useable feature. I have a feeling this ability will be available as a software update in the near future. In the meantime, even though you can’t edit them, you can view virtually any document.

If you are not happy with the out of the box functionality there are hundreds of Windows Mobile 5.0 compatible third-party applications to take advantage of. For instance, I am using Oxios ToDo list in order to use my Q in my Getting Things Done (GTD) system. (More on GTD in a future post). I also highly recommend AgileMobile for instant messaging. Watch out though, it drains the battery quickly.

Email is easy to get going. I use ActiveSync to sync with Accenture’s exchange servers for work, and I just use the built-in browser to access Google’s mobile web interface to check my Gmail account.

Miscellaneous: The Q also has: built in Bluetooth, a slot for MiniSD memory (I bought a gig for $60), voice notes recorder, excellent media player, pretty good camera, (I actually use it vs. didn’t even bother with previous phones), and very good voice quality. It excels at its basic function as a phone.

The Bad

It’s certainly not perfect.

Smartphone Software: I know this made the list of pros, but something has to be said about the negative aspects of the phone’s software. There are a wide ranging set of user interface problems associate with the Windows Mobile Smartphone software. Basically, it’s not as well thought-out as Palm software so you click through more submenus then you should rightfully have to.

Email: Again, this was a pro overall, but as of now you can’t set the Motorola Q to accept push email. I think this feature will be available soon as a software upgrade, but for now you’ll have to settle for checking your email every 5 minutes. I suppose this would be an acceptable interim solution, if it weren’t for the…

Battery Life: The Q sucks the battery dry when you are using it as a phone. I’ve found I have approximately 3-4 hours of talking time. When I’m primarily using the data features and not the voice features, the battery easily lasts all day. If you are on the phone a lot and not near a charger, this is not a good phone for you. My life consisted of a series of stressful and long phone calls in the last few weeks before my wedding, so I am very familiar with the poor battery life of the Q. On the bright side, the battery life has gotten better over the past few months, so I can skip charging at night every once in a while — but this is risky so I don’t recommend it. Also, I noted significant improvement in battery life when I set my email to sync manually. Syncing every 5 minutes drained the battery quickly.

The Data Plan: $45/month for less than DSL speeds is just too much. You can’t get the Q without a data plan. I guess you can, but you really shouldn’t. The Q assumes you have a plan and doesn’t ever warn you if you are about to use the data network. Expect to see charges for accessing Verizon’s data network on your bill each month even if you have gone out of your way to not use the data services. Don’t get a Q without a data plan.

Conclusion

In general I am extremely pleased with this phone. It accomplishes exactly what I want. I recognize that it is not as powerful as a bigger and chunkier Treo 650 or similar Pocket PC devices, but I also felt it was more important to have something that was truly mobile and didn’t make me feel like tightening my belt to keep my pants on when I put it in my pocket. I can check my email and respond. I can view attachments. I can create voice notes, take pictures, read my Bloglines account, chat with my friends on AIM and Google Chat, watch videos, listen to music and place phone calls. The best part is that all of this functionality slips into my shirt pocket for $200. It may not be the iPod of Smartphones, but I thinks it is a glimpse into the future of our mobile lifestyle.

how to install tortoiseSvn (subversion for windows users)

Tuesday, August 29th, 2006

1. Open up your web browser to the TortoiseSVN downloads page.

2. Scroll down until you see a post entitled “The current version is…” and download the file that ends with the .msi extension under the 32 bit subheading. It will look something like the following, but the numbers could be different: TortoiseSVN-1.3.5.6804-svn-1.3.2.msi

3. You will be directed to a screen with a list of locations and download links on the right side. Scroll down until you see the location nearest you, in my case it is Phoenix, AZ.

Download the file to your desktop or where you can find it easily.

4. Once the file completes downloading, open it and click through the wizard. There are no special options, just keep clicking ‘next’ until you can click ‘install’. You will have to reboot your computer to finish the installation.

5. Once your computer has finished rebooting, TortoiseSVN is now installed. Right click anywhere on your desktop and you will now see two additional options: SVN checkout and TortoiseSVN.

6. Now we need to adjust the configuration settings. Right click anywhere on your desktop and within the TortoiseSVN submenu choose “Settings…”

7. Highlight “General” and click the “Edit” button next to the words “Subversion configuration file”

8. Delete everything in that file and insert the following:

Note: Ensure that there is no leading white space, (tabs or spaces), in your file when you cut and paste the selection below.

[auth]
[helpers]
[tunnels]
[miscellany]
enable-auto-props = yes
[auto-props]
* = svn:needs-lock=*

9. Save your changes and close out all of the TortoiseSVN windows currently open.

10. Open up My Documents and create a new folder. If you are following these directions, I have sent you an email with some information. Name the new folder the same as the name of the repository that is within that email.

11. Right click on your new folder and choose “SVN checkout”. In the “URL of repository” field enter http://meshsandbox.com/svn/(the name of your repository). Leave everything else and click OK.

12. Enter in the username and password I provided you. Make sure and choose the option to save the name and password, otherwise you will be entering it in quite frequently.

You have successfully installed subversion and checked out a working copy of your repository. Chances are there are no files in your repository, so let’s add one for practice:

1. If you have a file that you know you want to be under version control, drag it into the folder we have just created. For future reference this folder is called the “Working Copy”.

2. Even though you see the file in the folder, it is still not in the repository. As you recall from this article, what you have on your computer is merely a copy of all the files held within the repository. Anyone with access to the repository has a copy of it and it is up to you to update the real repository with any changes you have made. Right click on the document, go into the TortoiseSVN menu and choose “Add”.

3. The file is now part of the repository, but now you need to committ your changes. Right click anywhere within the window and choose “SVN Commit”. This will permanently save your changes to the repository. Now, whenever anyone checks out or updates the repository, they will have your file.

I will create another set of directions to clarify these last few steps. I have also created a screen cast that illustrates how to check out the repository and add a file as described above. You can view it here. I recommend clicking on the icon with the double boxes located in the bottom right corner of the video box to expand it to full screen.

You can also download the zipped windows media file here if you want a clearer picture.

Subversion Repositories for Everyone

Friday, August 25th, 2006

I offered to create Subversion repositories for some of my family and friends and to my surprise, quite a few were very interested. This article is to give a broad overview of what Subversion is and why it is incredibly useful.

What is Subversion? Subversion is version control software. Version control helps a group of people manage a set of shared files.

For example:

You are working on a presentation with three other people. You go home and after watching an inspirational television program you feel the urge to update the slides. Just before you head off to bed, you email the new presentation to everyone on your team. At the same time another member of your team also updated the slides and emailed their changes to everyone. The next morning when you check your email you have two separate versions of your presentation and the joyless task of merging both sets of changes into one version. Version control solves this problem.

All files controlled by Subversion are stored in a repository. This is basically a digital vault that everyone on your team can access from anywhere with an internet connection. Each person who has access to the repository maintains an updated copy of all the files on their computer: this is called your “working copy”. Each person has their own copy. Once you are done working, you update the version stored in theSubversion Workflow Diagram vault. This is called, “committing” your changes. The next time someone on your team updates their working copy it will contain your changes and they will be working on the most recent “version” of the file. This is why it’s called “version” control.

As of Subversion 1.2 you can now lock files. When one member of the team locks the file, no other team member can make changes to the file. In our example above, you would have locked the presentation before you started making changes, so the other member of your team couldn’t have made changes to the document.

I’ve created a workflow diagram to show the process you would use to update a file when it is under version control using Subversion.

Note: Using Subversion it is possible to have multiple people working on one file at the same time. Subversion would then merge the changes and pass off any complicated conflicts to a human. However, it can’t do this with complicated files like Microsoft Word, Excel or Powerpoint. This is why the repositories I am creating for my friends and family will be set up to require locks as I have described above.