Developer. Gamer. Yo-Yo Thrower.

Node.js : Very cool

I have started playing with Node.js way more, it’s totally fun (especially for a JavaScript guy like myself) and extremely powerful. I’ll post more later, but I just wanted to point to a quick little web-app scaffolding I threw together to help get to know the Node.js environment. I called it scaffnode, it’s 3 little Node.js + ExpressJS + mustache (‘stache‘) (+ if you want) setups. I’ll be adding MongoDB for sure – I’ve been playing with it too (and it’s so good too) but haven’t put my code anywhere yet.

More JavaScript Wonders

Another couple JavaScript oddities I’ve run into recently.
The first one is to do with function expressions vs. function blocks.

//A function in a block
var aNumber = getNumber(); //Returns 42 as you might expect
function getNumber() { return 42; }

Now a slight variation of the same script:

var aNumber = getNumber(); //Error: getNumber is undefined
var getNumber = function() { return 42; }

Why?! It’s easy: function expressions are evaluated at runtime. Function ‘blocks’ are parsed at runtime. Neat little gotcha right?

The next one was brought to my attention from one of my co-workers who was refreshing his JavaScript knowledge:

var aNumber = 42;
var aString = "42";

var result = aString + aNumber; // result is now "4242" - String is automatically concatenated
var result = aString - aNumber; // result is now 0 - String is automatically parseInt() and evaluated

This is just JavaScript being clever – it knows you might want to join two strings, but no such ‘logical’ operation exists if you’re using a minus sign. A very interesting different result based on a mere plus or minus symbol. Always use parseInt and mind your NaNers. 😉

Batman JavaScript Error

Check out this silly JavaScript snippet that’s been floating around (it has nothing to do with the microframework):

Array(16).join("lol" - 2) + " Batman!";

For the non-web geeks: It’s a line of code that causes a neat error message. If you’re in Chrome, press F12 (that’s what the guts of the internet look like BTW), click the “Console” button at the top and paste that line of code in, then press enter. “NaN” means “Not a Number” in JavaScript, it’s saying this because you can’t subtract 2 from “lol”.

Modern JavaScript

Kind of a continuation of the JSON Gotcha post I wrote way back. I've been getting into JavaScript 1.8 (engines that implement ECMAScript 5). JavaScript implementations are tricky, it's a little like trying to deploy C code on different platforms with different compilers - this makes JavaScript in the browser kind of tricky to work with. Spidermonkey in FireFox works differently than V8 in Chrome, which works differently than Chakra (JScript) in Internet Explorer and SquirrelFish in Safari -- in addition to minor ECMAScript implementation differences they also have 'vendor specific' methods and differences that you must be aware of. As anyone who does web development with JavaScript can attest, this makes the mantra "write once, run everywhere" kind of tricky.


Code Poetry

Came across this quote by Frederick Brook from the book The Mythical Man-Month: Essays on Software Engineering. It makes me feel pretty awesome to be a programmer:

The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds castles in the air, from air, creating by exertion of the imagination. Few media of creation are so flexible, so easy to polish and rework, so readily capable of realizing grand conceptual structures. Yet the program construct, unlike the poet’s words, is real in the sense that it moves and works, producing visible outputs separate from the construct itself. It prints results, draws pictures, produces sounds, moves arms. The magic of myth and legend has come true in our time. One types the correct incantation on a keyboard, and a display screen comes to life, showing things that never were nor could be. … The computer resembles the magic of legend in this respect, too. If one character, one pause, of the incantation is not strictly in proper form, the magic doesn’t work. Human beings are not accustomed to being perfect, an few areas of human activity demand it. Adjusting to the requirement for perfection is, I think, the most difficult part of learning to program.

If you’re not seeing your code as art than you should think about how you look at programming as a whole.

Zen Coding Makes Writing HTML Easy

Very few things have actually made writing code easier for me. Sure most editors do neat things in the name of helping you do things a bit faster, but rarely does something come my way that truly makes writing code easier. One of those things is "Zen Coding", an extension/plugin for most major editors that makes writing HTML and CSS almost painless. It simply takes short hand and turns it into full W3C compliant HTML and/or CSS all at the press of a command ( CTRL+e in my editors of choice). Take a look (what I typed is inside of comment tags, results from zen-coding directly below):

text-align: center;

float: left;
You can even chain short hand together and use very simple syntax. This one line:
Evaluates to a complete website stucture:


(Ugh. WordPress (or SyntaxHighligher?) is eating my HTML doctype, html and head tags from the above example... but they're there I promise!) It's an extraordinarily cool plugin and I highly recommend it to anyone that writes HTML or CSS on a regular basis.

Python Decorators

Still learning Python. It’s clean, easy to read but complex. One of the things I kept seeing across some of our back-end code are strings prefaced with “@” before a function definition. They’re called decorators and they were a mystery to me … until today. Succinctly put: decorators let you execute code before and after the function they decorate without needing to modify the function itself.

def immaFunction():

Before we dive into what they do, we need to know two things about functions in python: Functions themselves can be assigned to a variable. Functions can be defined within other functions. Pretty straight forward:

def drink(type="redbull"):
    #Define a couple of functions inside our drink function
    def redbull(reaction="omgwtfbbq"):
        return reaction.upper()+"!!!!!"
    def coffee(reaction="omg"):
        return reaction.lower()+"!"

    #Decide what function to return
    if type == "redbull":
        return redbull
        return coffee

drinkMe = drink()
print drinkMe
#prints something like: <function "redbull" at 0xdeadbeef>
print drinkMe()
#prints OMGWTFBBQ!!!!!
print drink("not redbull")()
#calls the coffee function directly and prints "omg!"

#You can also pass functions as parameters
def doSomethingBefore(functionName):
    print "Herpty derp de derpity close... lets see what this function does:"
    print functionName()

#Herpty derp de derpity close... lets see what this function does:

Now; Decorators. A decorator is simply a function that expects another function as a parameter. Let’s do the work of a decorator manually:

def myDecorator(theFunctionToDecorate):
    #This nested function is going to wrap around the original function passed through myDecorator
    def wrapperAroundOriginalFunction():
        #Just a little proof we're doing something before
        print "Before the original function"
        #Just a little proof we're doing something after
        print "After the original function"

    #It's important to note that the functions wrapperAroundOriginalFunction and theFunctionToDecorate are never actually excuted
    return wrapperAroundOriginalFunction

def justANormalFunction():
    print "I am a normal function. Please don't decorate me!! I have a family!!"

#Outputs: I am a normal function. Please don't decorate me!! I have a family!!

decoratedNormalFunction = myDecorator(justANormalFunction)
#Before the original function
#I am a normal function. Please don't decorate me!! I have a family!!
#After the original function

This is exactly what decorators do! In fact, we can change the last bit of code and then guess what? We’re using a decorator!

#Just Do this
def justANormalFunction():
    print "I am a normal function. Please don't decorate me!! I have a family!!"

#Now outputs:
#Before the original function
#I am a normal function. Please don't decorate me!! I have a family!!
#After the original function

#These guys aren't needed anymore! Our function justANormalFunction is now decorated!
#decoratedNormalFunction = myDecorator(justANormalFunction)

If you’re getting this, you can see that Pythons decorators are similar to Java’s annotations and are purely syntactic sugar. However, the Wikipedia page for the programming pattern called decorators is explicit in pointing out: “Not to be confused with the concept of “decorators” in Python.”

Let’s look at one more slightly more complicated example. This time we’re going to build a delicious burger.

def theBun(func) :
    def wrapper() :
        print "|''''''|"
        print "|______|"
    return wrapper

def ingredients(func) :
    def wrapper() :
        print "-tomatoes-"
        print "-lettuce-"
    return wrapper

#Try changing the order of these decorators! You'll see that the order is important!
def theBurger(food="--burger patty--") :
    print food

#If we didn't have the decorators on theBun()
#sandwich = theBun(ingredients(theBurger))

That’s it! Please keep in mind that I’m still learning and if you see an error, or a better way to do something please let me know. I make these kinds blog posts mostly to help myself learn… I can’t do that if I’m learning the wrong stuff 😉

I’m sold on Python

I’m sold on Python. I am having way too many “Why was I doing this the long way with PHP?” moments.

Some fun with PHP:

echo 10010.10 - 10009.93;

Same thing in Python

print 10010.10 - 10009.93

I also saw on Reddit this “magic kill number” that simply hangs most versions of PHP5.

$d = 2.2250738585072011e-308;

Hangs the default install of PHP in Ubuntu 10.10 (PHP 5.3.3-1ubuntu9.1). Crazy.

Making Plyons (and other Python apps) Play with Apache

Problem: I want to serve my Plyons app from the same server, on the same port as my other PHP based projects. All the tutorials tell me to start my pylons app by running “paster serve –reload development.ini”, but as I read that I thought “Apache is my webserver, I don’t need two” 🙂

My Solution: Using mod_wsgi to run my pylons app.

Simply edit Apache’s configuration file for the server/domain in question and add this line to the that hosts your Pylons project. In this case I’ve got my pylons project named “helloworldapp” and it lives in “/var/www/”, so my virtual host configuration looks something like this:

                WSGIScriptAlias / /var/www/
                #... the rest of your vhost config

Notice the index.wsgi – this is going to be what loads your pylons app. I choose ‘index.wsgi’, but feel free to use any name you like.

The contents of index.wsgi simply tell Python where your app is, adds its base-path and then starts it:

APP_BASE = "/var/www/"
APP_CONFIG = "/var/www/"


os.environ['PYTHON_EGG_CACHE'] = '/usr/local/pylons/python-eggs'
from paste.deploy import loadapp
application = loadapp("config:" + APP_CONFIG)

That’s really all there is to it! I’m eager to get more into Python web development. I’ve had my head in PHP development for too long!

Why not just enable mod_python and set an “AddHandler”? Performance! mod_python is kind of inefficient with the way it runs Python apps. As I understand it (please correct me if I’m wrong), it spawns a whole new Python thread for each Apache instance – this can consume memory and CPU like crazy!

PHP Variable variables

Gah! I was reading about variable variables the other night!! Damn my memory!

I just bombed an interview question asking what does this line do:

$$foo = "x";

I knew I had seen it, and I knew it was a newer feature for PHP5.
It’s to do with PHPs variable variables feature. In a nutshell, it allows you to set dynamic variable names.

$x = 9;
$foo = "x";
echo $$foo;
//prints 9

So the correct answer to “What does that statement do?” would have been “refers to variable $x”. That’s one feature of PHP I won’t soon forget.


Table of Contents