Thursday, December 31, 2009

Identifying from where JavaScript libraries invoke your callback functions, with Firebug

There comes a time where one would need to dig beyond the abstractions to see what is really going on under the covers.

Say for example you wanted to see how a certain library computes parameters for your callback, how would you do it? Scanning the library and figuring out the logic step by step is one way you can do it, but that is very time consuming and with complex libraries such as jQuery, it's nearly impossible to exactly pinpoint from where your callback function is being invoked.

In this post we will see how we can use Firebug to pinpoint exactly from where your callback functions are called in the abstraction.

A simple library

Let's take an example with a very small hypothetical "library" example:

var alibrary = (function () {
    var callback, 
    privatefun = function (p) {

    return {
        setCallback: function (fn) {
            callback = fn;
        doIt: function () {
            var params = ['some', 'parameters', 22 + 20];

This 'library' offers 2 public functions; setCallback, which takes a function and stores it into the callback parameter and the doIt function that invokes the function that was stored previously.

Here's how this library can be used:

alibrary.setCallback(function (p) {


When the doIt function is called, the callback function that was passed previously will be invoked, passing in some parameters from behind. The library is passing an array as a parameter and the third element of that array is a computation of 22 + 20.

Now, as users of the library, we want to check how that 42 is computed from our callback function; and we will do this with Mozilla Firefox's best friend, Firebug

Tracing the steps

Open your Firebug (F12) and head onto the Script tab and choose the script from where you are defining your callback function. Then find your function and put a breakpoint in the function:

To set a breakpoint, click next to the line number in the and a red dot will appear.

The next step is to perform the action that will invoke your callback, and in my case this 'action' is a page refresh.

So now after my page refresh, the library will invoke my callback and the breakpoint will be hit:

When the breakpoint is hit, the line will be highlighted in yellow.

Now comes the part where we trace the steps back to where the callback was invoked. If you look closely to the upper part of the Script tab, you will see the following:

From there, you can now trace the path to where the function was invoked! Now let's click on the first step, privatefun().

Upon clicking, Firebug takes you directly to that function, privatefun, and now from this function we can see how our callback function was invoked:

Now although we can see from there the function was invoked, we still don't know from where that 42 is coming from, and so we must check which function invoked privatefun and to do that, we move a step back through the invocation line, the doIt() step:

From here, we can now see how that 42 was being computed because we have finally arrived to the step we wanted to.

Now obviously this technique isn't that much useful for this example because the code of this 'library' is so small that it doesn't require backtracking of the function calls, but it can be used very effectively on much larger libraries to quickly identify how certain parameters are being computed and sent to your functions, amongst other uses.

Sunday, December 27, 2009

Trying out the examples from 'The Little Schemer' book

This delightful book leads you through the basic elements of programming in Scheme (a Lisp dialect) via a series of dialogues with well-chosen questions and exercises.

To try out the examples from The Little Schemer, you must first download1 PLT-Scheme. This will install DrScheme, which is the IDE you will use to type in the Scheme examples.

As a language, I chose Module in DrScheme and it seems to be suitable for trying out the examples.

Once the language is set, you need to start each file with the following line:

#lang scheme

The upper section of the screen is used to enter all the definitions and the lower part of the screen is used to execute those functions you defined in the upper part.

Minor Changes

Something you need to be careful about are the minor syntax changes. This is because there are slight changes from the examples in the book to the real Scheme.

One of changes is the way you call identifiers. Identifiers require an apostrophe (') in Scheme, but in the book the apostrophe is not used in the examples.

This is mentioned in page 3 of the book:

L, S: (quote atom) or 'atom

This means that, for example, to test the atom? function (or any function), you need to call it like such:
(atom? 'elem1)

Same goes for when the identifier is a list:

(atom? '(peanut butter jelly time))

The Apostrophe

The apostrophe is a shorthand notation of the (quote ...). Basically, you are saying the interpreter to not evaluate the name but only replace it with its value, verbatim.
Therefore, the following two lat? questions are the same thing:

(lat? (quote (peanut butter jelly)))


(lat? '(peanut butter jelly))

If you do not put the apostrophe, you are signaling the interpreter to use the variable. This can be clearly illustrated with the following example:

(let ((x 42))
  (display x) (newline)
  (display 'x) (newline))

The output of the above code is:

1 If you don't want to download PLT-Scheme, you can use an online interpreter. Two of which you can try are SISC and CodePad

Tuesday, December 22, 2009

jsLaTeX: A jQuery plugin to directly embed LaTeX into your website or blog

jsLaTeX is the latest plugin I developed for jQuery and I wrote it so that I could easily be able to embed LaTeX directly into my blog but anyone can use it for their site.

You can download the normal, unpacked version for development or the packed version for production.

Click here to view a demo

Here is a link to the jQuery plugin page, where you can find all the releases.

Usage Instructions

1. Download the jquery.jslatex.js file from one of the above-mentioned links and add it to your page along with jQuery (if it is not already added):

<script src=""></script>
<script src="jquery.jslatex.js"></script>

2. The simplest way to invoke the script is by calling the plugin with no parameters:

$(function () {
<div class="latex">
    \int_{0}^{\pi}\frac{x^{4}\left(1-x\right)^{4}}{1+x^{2}}dx =\frac{22}{7}-\pi

The above will render the following:

\int_{0}^{\pi}\frac{x^{4}\left(1-x\right)^{4}}{1+x^{2}}dx =\frac{22}{7}-\pi

The plugin works by taking the inner HTML of the specified container obviously assuming that it is valid LaTeX, and displays the image using CodeCogs LaTeX engine. The rendered output replaces the equation inside the container.

The plugin also accepts 3 optional parameters:
  • format
  • url
  • callback

The format parameter is used to specify the format of the returned output. There are currently 3 supported formats:
  • gif
  • png
  • swf

The url parameter is used to change the engine of the LaTeX generator. Let's take an example with a different engine, and in this case I will be using SITMO's LaTeX engine.
The url SITMO's engine uses to render the output is as follows:

where equation is the the LaTeX equation you wish to render.

Now we must tell the plugin where to put the equation and we do this by using the {e} specifier. This is how it can be used:

$(".latex").latex({url: '{e}'});

As you can see from the above example, we placed the {e} specifier where the equation should be and then the engine takes care of the rest.

Here is an example of using the new engine to render the output:

\int_{0}^{\pi}\frac{x^{4}\left(1-x\right)^{4}}{1+x^{2}}dx =\frac{22}{7}-\pi

The plugin currently supports another specifier: {f} and this is used for those engines that allow you to specify a file-format output. The file-types that are currently supported are the ones mentioned in the [format] section.

If we take the 'original' engine url, we can turn into a url with specifiers like such:{f}.latex?{e}

Here are examples of Engines you can use (ready with specifiers):


The callback parameter allows you to pass a function that will be executed after the image has been retrieved. In your callback function, this will refer to the newly created element (as a jQuery object) that contains the rendered output.

The following example will set a border around your rendered output.

    callback : function() {
        this.css({ border: '1px solid black'});

With the above callback, we can now render the following:

\int_{0}^{\pi}\frac{x^{4}\left(1-x\right)^{4}}{1+x^{2}}dx =\frac{22}{7}-\pi

Monday, December 21, 2009

Aligning a block of text in LaTeX

This is how you can indent and align a block of text in LaTeX:

Contact Address: \= 175, Ambjent\\
\> Francesco Buhagiar str.\\
\> Swieqi, SWQ 3230

That will produce the following output:

Creating a signature line in LaTeX

To create a signature line in LaTeX, use the makebox command like such:

Signature\hspace{0.5cm} \makebox[1.5in]{\hrulefill}

This will produce the following:

Sunday, December 20, 2009

Centering a container on screen with JavaScript (jQuery plugin)

Recently I needed a way to center an image on screen for a 'Coming Soon' kind of page, and so I wrote this jQuery plugin that does in fact this.

You can download the normal, unpacked version for development or the packed version for production.

Click here to view a demo

The container needs to have a preset width and height for this to work

Here is the unpacked code:

 * CenterScreen v1.1 - jQuery plugin
 *  Copyright (c) 2009 - 2010 Andreas Grech
 *  Dual licensed under the MIT and GPL licenses:

(function ($) {
    $.fn.centerScreen = function () {
        return this.each(function () {
            var $this = $(this),
                $window = $(window),
                center = function () {
                    var winWidth = $window.width(),
                        winHeight = $window.height();
                        position: 'absolute',
                        left: ((winWidth / 2) - ($this.outerWidth() / 2)),
                        top: ((winHeight / 2) - ($this.outerHeight() / 2))

Saturday, December 19, 2009

Lexical Scoping in JavaScript

Take a look at the below code:

var f = function () {
    var n = 42;
    return function () {
        return n;

var result = f();

The function f is a self-invoking function that returns a function, that returns the variable n declared in the outer function.

The alert of the above code is, as you'd expect, 42

Now let's try rewriting the above code so that instead of returning a function that is declared internally, it now returns a function that was defined outside (but that does the same thing):

var f2 = function () {
    return n;

var f = function () {
    var n = 42;
    return f2;

var result = f();

This should return the same result, no?

Actually, we are greeted with the following error:

n is not defined

This is because of JavaScript's static scoping, also known as lexical scoping, because matching a variable to its binding only requires analysis of the program text.

This means that the scope of the variable is determined at compile-time, and from the second code snippet we can see that during compile time variable n of function f2 has window (window.n) as it's scope; and since n doesn't exist in the global scope, it is undefined.

JavaScript's Function Scope

Those developers who are coming from a C background may find JavaScript's scoping rules a bit confusing.

Let's take a look at the following C code:

#include <stdio.h>

int main () {
    int n = 5;
    if (1) {
        int n = 2;
    printf("n is %d", n);

The output of the above code is:

n is 5

Now let us implement the above code in JavaScript:

var scoping = function () {
    var n = 5;
    if (1) {  
        var n = 2;
    alert('n is ' + n);

What do you think the above code alerts?

If you answered n is 5, then you are wrong

This is because, unlike C, JavaScript only supports Function Scope and not Block Scope.

What this means is that JavaScript creates a new scope only with a function:

var scoping = function () {
    var n = 5;
    var x = function () {  
        var n = 2;
    alert('n is ' + n);

Now, n is 5 is alerted because a new scope has been created with the inner function and thus it's encapsulating the inner variable n.

Saturday, December 5, 2009

Updating your Twitter Status from C#

Today I needed a way to update my Twitter Status via C#, and for that I found this library: Yedda Twitter C# Library.

After I added a reference to the Yedda.Twitter.dll, I tried working with the following code:

namespace TestingAPIs
    using Yedda;

    class Program
        static void Main(string[] args)
            var t = new Twitter();
                "myUsername",                          // Username
                "myPassword",                          // Password
                "From Visual Studio",                  // New Status
                Yedda.Twitter.OutputFormatType.JSON);  // Output Type

Simple eh?

Well, much to my amazement, that threw an exception -_- ...obviously, it wouldn't as much fun if it worked on the first try eh!

So, after some googling, I found some posts that detailed the problem:

This error is seemingly because Twitter servers have started rejecting Expect HTTP header with value "100-Continue".

So anyways, to fix this problem we need to modify a method from the Twitter.cs file of the Yedda library.

Open up the file and find the following method: ExecutePostCommand

At the start of the method, add the following line of code:

System.Net.ServicePointManager.Expect100Continue = false;

That will fix the above problem.

Here is the complete modified method:

protected string ExecutePostCommand(string url, string userName, string password, string data) {
 System.Net.ServicePointManager.Expect100Continue = false;
 WebRequest request = WebRequest.Create(url);
 if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) {
  request.Credentials = new NetworkCredential(userName, password);
  request.ContentType = "application/x-www-form-urlencoded";
  request.Method = "POST";

  if (!string.IsNullOrEmpty(TwitterClient)) {
   request.Headers.Add("X-Twitter-Client", TwitterClient);

  if (!string.IsNullOrEmpty(TwitterClientVersion)) {
   request.Headers.Add("X-Twitter-Version", TwitterClientVersion);

  if (!string.IsNullOrEmpty(TwitterClientUrl)) {
   request.Headers.Add("X-Twitter-URL", TwitterClientUrl);

  if (!string.IsNullOrEmpty(Source)) {
   data += "&source=" + HttpUtility.UrlEncode(Source);

  byte[] bytes = Encoding.UTF8.GetBytes(data);

  request.ContentLength = bytes.Length;
  using (Stream requestStream = request.GetRequestStream()) {
   requestStream.Write(bytes, 0, bytes.Length);

   using (WebResponse response = request.GetResponse()) {
    using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
     return reader.ReadToEnd();

 return null;

Sunday, November 29, 2009

Detecting Firebug with JavaScript

Need to implement some debugging methods for your library with Firebug's console as your Output Window?

Here's a quick way to check if Firebug is enabled:

if (window.console && window.console.firebug) {
    //Firebug is enabled

Obviously, this is not a fool-proof method because anyone can overwrite the console object, but I think that it's the best you're gonna get.

Thursday, November 26, 2009

Custom-sorting arrays in JavaScript

To sort an array in JavaScript, we use the array.sort() method.

Let's take a look at the following code:

var words   = ["andreas", "john", "grech", "janica", "buhagiar"];
var numbers = [5, 2, 8, 666, 42, 13];


The results of the above are:

["andreas", "buhagiar", "grech", "janica", "john"]

[13, 2, 42, 5, 666, 8]

As you can see, the strings are sorted correctly, but what happened to the numbers? 13 is obviously greater than 2, so why is it before?

Sorting lexicographically

The problem with the array.sort function is that it sorts lexicographically, meaning it sorts 'alphabetically'; in dictionary order; and thus the sort function just assumes that the elements that need to be sorted are strings. And if they aren't strings, it converts them to strings and then compares them.

Fortunately, sort takes also a single parameter; a function that will be used to sort the array with.

Let's take an example of how we can sort numbers:

var numbers = [5, 2, 8, 666, 42, 13];
var ascNumSort = function (a, b) {
    return a - b;
var ns = numbers.sort(ascNumSort);

Now we created a function called ascNumSort and passed it to the sort method, and as you can see the numbers are now correctly sorted in ascending order.

What kind of function ?

The function that you pass as a parameter to the sort method needs to abide with the following rules:
  1. It must accept two formal arguments
  2. Return a 0 if the two elements are equal
  3. Return a positive number if the second parameter should come before the first parameter
  4. Return a negative number if the first parameter should come before the second parameter
With these rules, we can now build our custom sorting functions.

Let's say that we have an array of objects representing people and we want to sort these people according to their height, in descending order:

var people = [
    {name: "Andreas", height: 5.4},
    {name: "Janica",  height: 4.3},
    {name: "Cameron", height: 5.8},
    {name: "Richard", height: 5.4},
    {name: "Ryan",    height: 4.5}

var sortedPeople = people.sort(function (p1, p2) {
    return p2.height - p1.height;

 Object name=Cameron height=5.8, 
 Object name=Andreas height=5.4, 
 Object name=Richard height=5.4, 
 Object name=Ryan    height=4.5, 
 Object name=Janica  height=4.3

Sorting on multiple keys

By implementing what we did above, but in a more general way, we can come up with a function that will allow us to sort an array of objects, given a key (or multiple keys) [taken from Douglas Crockford's The Good Parts]:

//Function by takes a member name string and an
//optional minor comparison function and returns
//a comparison function that can be used to sort an
//array of objects that contain that member.  The
//minor comparison function is used to break ties
//when the o[name] and p[name] are equal 

var by = function (name, minor) {
    return function (o, p) {
        var a, b;
        if (typeof o === 'object' && typeof p === 'object' && o && p) {
            a = o[name];
            b = p[name];
            if (a === b) {
                return typeof minor === 'function' ? minor(o, p) : o;
            if (typeof a === typeof b) {
                return a < b ? -1 : 1;
            return typeof a < typeof b ? -1 : 1;
        } else {
            throw {
                name: 'Error',
                message: 'Expected an object when sorting by ' + name

Now let's take a look of an example of how we can use the above by function:

var people = [
    {name: "Andreas", height: 5.4},
    {name: "Janica",  height: 4.3},
    {name: "Tony",    height: 5.8},
    {name: "Richard", height: 5.4},
    {name: "Ryan",    height: 4.5},
    {name: "Cameron", height: 5.8}

 Object name=Janica height=4.3,  Object name=Ryan height=4.5, 
 Object name=Andreas height=5.4, Object name=Richard height=5.4, 
 Object name=Tony height=5.8,    Object name=Cameron height=5.8

console.log(people.sort(by('height', by('name'))));
 Object name=Janica height=4.3,  Object name=Ryan height=4.5, 
 Object name=Andreas height=5.4, Object name=Richard height=5.4, 
 Object name=Cameron height=5.8, Object name=Tony height=5.8

Check if your CPU is either 32-bit of 64-bit in Windows Vista

Today or tomorrow I will be upgrading from my current Vista to Windows 7 and I needed to check which version of the OS the install.

To check whether my CPU was 32-bit or 64-bit, here's what I did (in Vista):

 First open up the System Information tools from Accessories > System Tools

Then from the System Information, look for the System Type Row, and there you will have your answer:

  • x86-based PC: 32-Bit Computer
  • x64-based PC: 64-Bit Computer

Wednesday, November 25, 2009

JavaScript's Evil Equality Twins (Equality vs Identity)

In JavaScript, there exists two sets of equality operators:

=== and !==

and, as Douglas Crockford likes to call them, their corresponding evil twins :

== and !=

What's the difference?

The first set of operators, called Identity Operators ( === and !== ), produce true (or false) whenever the given operands are both of the same type and have the same value.

On the other hand, the evil twins, formally known as Equality Operators ( == and != ), do type-coercion whenever the operands are of a different type before checking for value equality.


First of all, don't get thrown off by the word coercion; it's just another word for conversion.
In Computer Science, there are two forms of type conversions, implicit and explicit.  The term used for implicit type conversion is coercion and the term used for explicit type conversion is casting.

In most languages, explicit casting is done via the parenthesis:

int main () {
    float fl = 7.2;
    int n = (int) fl;   // (int) makes an explicit cast
    //n is now 7

But JavaScript, being a loosely typed language, never casts.

Implicit casting, coercion, is the automatic type conversion that is done internally by the compiler.  For example, we can rewrite the above C code as such:

int main () {
    float fl = 7.2;
    int n = fl;   //now the C compiler is internally coercing the operator to an integer 
    //n is now 7

This time, the compiler is implicitly casting fl to an integer.

What's wrong with type-coercion ?

Earlier on I said that the evil twins do type-coercion before checking for type-equality, and unfortunately the rules by which they coerce the values are complicated and unmemorable.

Here are two cases of comparing the values with both sets:

//Using the equality operator (==)

true == 1; //true, because the boolean value true is converted to 1 and then compared
"2"  == 2  //true, because 2 is converted to "2" and then compared

//Using the identity operator (===)

true === 1  //false
"2"  === 2  // false

Here is a list of other "interesting" cases:

'' == '0'          //false
0  == ''           //true
0  == '0'          //true

false == 'false'   //true
false == '0'       //true

false == undefined //false
false == null      //false
null  == undefined //true

' \t\r\n ' == 0    //true

All of the comparisons shown above produce false with the === operator.

Therefore in my opinion, you should never use the Equality operators, but only use the Identity operators, === and !==

Simple enough?

Well, not really...because as usual, there has to be a caveat. Take a look at the following example:

var x = new String('hello');
var y = 'hello';

console.log(x === y); //shows false
console.log(x == y);  //shows true

As you can see, a false is returned when we used the Identity operator! This is because:

console.log(typeof x); // 'object'
console.log(typeof y); // 'string'

When we used the Identity operator ===, it returned false because x and y are not of the same type! This is due to the fact we used the constructor to initialize a string (new String()), the primitive value was boxed into an Object.

The moral of this is to Always use literals to initialize values and this goes for all the primitive types. I will leave further explanation of this for another post.

3D Rotating Tag Cloud for Blogger (Cumulus Cloud)

Today I implemented a rotating 3D tag cloud, called a Blogumus.  Such a script was initially written as a plugin for WordPress, called WP-Cumulus.

But Amanda from BloggerBuster has ported a version of the WordPress plugin to Blogger; and it's now called Blogumus.

Here's an example of the Blogumus in action:

Implementing the Blogumus for your Blogger blog is very easy:

  1. Find the side-bar section in your layout's html. The sidebar section starts with the following tag:

    <b:section class="sidebar" id="sidebar" preferred="yes">

  2. In your side-bar section (ie in the tag mentioned above), paste the following code:

    <b:widget id='Label99' locked='false' title='Labels' type='Label'>
    <b:includable id='main'>
    <b:if cond='data:title'>
    <div class='widget-content'>
    <script src='' type='text/javascript'/>
    <div id='flashcontent'>Blogumulus by <a href=''>Roy Tanck</a> and <a href=''>Amanda Fazani</a></div>
    <script type='text/javascript'>
    var so = new SWFObject("", "tagcloud", "240", "300", "7", "#ffffff");
    // uncomment next line to enable transparency
    //so.addParam("wmode", "transparent");
    so.addVariable("tcolor", "0x333333");
    so.addVariable("mode", "tags");
    so.addVariable("distr", "true");
    so.addVariable("tspeed", "100");
    so.addVariable("tagcloud", "<tags><b:loop values='data:labels' var='label'><a expr:href='data:label.url' style='12'><></a></b:loop></tags>");
    so.addParam("allowScriptAccess", "always");
    <b:include name='quickedit'/>

To customize the dimensions and background-color, modify the following line from the code above:

var so = new SWFObject("", "tagcloud", "240", "300", "7", "#ffffff");

The default values are:
  • Width: 240
  • Height: 300
  • Background Colour: #ffffff

To change the color of the font, modify it from the following line:

so.addVariable("tcolor", "0x333333");

The default color is #333333

This tutorial was adopted from Amanda's Tutorial.

Tuesday, November 24, 2009

Code Beautifiers

Don't you hate it when you want to follow some code that's virtually unreadable because of it's horrific formatting?  Believe me, you're not alone.

That's why in this post I am going to compile a list of Code Beautifiers.




'What I was listening to' box in my posts

I recently implemented a 'system' in where I show one or more songs I was listening to whilst writing a blog post, in this form:

To do that, I wrote a small script:

var blogmusic = function () {
    var lastContainerDone = 0;
    return function (music) {
        var musiccount = music.length,
            blogmusic = $(".blogmusic").eq(lastContainerDone++),
            header = $("<div/>").addClass("header");
        header.append("<center>What I was listening to</center>");
        var musiclist = $("<div/>").addClass("musiclist");
        for (var i = 0; i & lt; musiccount; i += 1) {
            var song = music[i];
            var listing = $("<div/>").addClass("listing");
            var songname = $("<span/>").addClass("songname").html('<a href="' + ( || '#') + '" target="_blank">"' + + '"</a>');
            var artist = $("<span/>").addClass("artist").html('- ' + song.artist);
} ();

And I invoke the script in my blog posts like such:

<div class="blogmusic">
    artist : 'Jerry Lee Lewis',
    name : 'Whole Lotta Shakin\'',
    link : ''

The correct way to delete an element from an array in JavaScript

In JavaScript, there exists an operator called delete.  This operator is used to remove properties from objects, and since arrays in JavaScript are really objects, it can be used to remove elements:

var arr = ['a','b','c','d','e'];
delete arr[2];

//arr is now ['a', 'b', undefined, 'd', 'e']

As you can see from the above code, the element is removed but this leaves a hole in the array because the element was replaced with undefined.

Therefore, the correct way to remove an element an array from an element is by using the splice method.

Arrays in JavaScript have a method called splice.  To remove an element from array, we will use it is like such:

var arr = ['a','b','c','d','e'];
arr.splice(2, 1);

//arr is now ['a', 'b', 'd', 'e']

The first argument is an index (ordinal) in the array from where to start deleting and the second element is the number of elements to delete. Thus, with 2 and 1 as parameters, we are starting at index 2 and removing 1 element. (Additional parameters get inserted into the array).

One thing to note is that with splice, the property with the value 'd' has it's key changed from 4 to 3 and because every property after the deleted property will be removed and reinserted with a new key, this might take a while for large arrays.

Sunday, November 22, 2009

Passing a pointer to a function with parameters in JavaScript (Partial Function Application)

In JavaScript, you can easily add a direct reference to a function with no parameters like such:

var f = function () {  };

var pf = f; // passing a direct reference to the function f

pf(); //invoking the function f

But how can you pass a reference to a function with parameters?

Say I have the following function:

var f = function (arg1, arg2) {  };

var pf = f(4, 5); // you can't do that, because that invoke f and put 
                  // it's result into pf, instead of a reference to f


One alternative is by invoking that function within an anonymous function:

var f = function (pars) {  };

var pf = function (pars) {


What I am doing in the above example is wrapping the function invocation of f with an anonymous function, and passing a reference of that anonymous function to pf.

That will then allow me to invoke pf with parameters, which will in turn invoke f with the parameters passed to pf.

But in the above example, although it works, I am not passing a direct reference to function f, but rather a reference to a function that invokes f.

Fortunately enough, there is a way we can pass a direct reference to a function including its arguments, and this is called Partial Function Application.

Take a look at the following function:

var partial = function (func /*, 0..n args */) {
    var args =, 1);
    return function () {
        var allArguments = args.concat(;
        return func.apply(this, allArguments);

With the partial function, I can now do:

var f = function (pars) {  };

var pf = partial(f, 200);

pf(/* you can add more arguments */); //invokes f with the previously 
                                      //added arguments (in this case, 200);

Let's go through the partial function step-by-step:

First of all, as you can see from the function signature, I declared only one formal argument for the partial function: func; yet when I am invoking the function, I passed in more than one parameter: 

partial(f, 200);

This is because every function in JavaScript has a property named arguments (JavaScript is a functional objected-oriented language, and thus functions can have both methods and properties), which is an array-like object that allows you to access all the actual arguments in the function (I will leave further explanation of the arguments object arguments for another post).

Now in the first line of the function we are taking a copy of the arguments array, excluding the first argument (which will be the pointer to a function), func, and storing it into a variable. The reason we are doing this will be clear later on.

But how exactly am I taking a copy of this arguments object ?

To make a copy of an array in JavaScript, one should use the array's inbuilt method slice.  The slice method returns a part ( a slice) of the array it is invoked on.  But if you remember earlier on I told you that arguments is an 'array-like' object. This is because it has the length property, but lacks all the methods that are available to normal arrays; thus we cannot call slice directly from arguments (i.e. we cannot do arguments.slice

Therefore, we are calling the slice method directly from the Array.prototype, passing in arguments as the first parameter and 1 as the second parameter.  That will return a copy of the arguments 'array' excluding the first element; the first element being the function that is passed into the partial function, func.

The next line of the function is returning an anonymous function.  This means that we are declaring a closure.  The explanation of closures is beyond this post, but I will just explain it lightly.

In JavaScript, whenever a function declares an inner function and returns it, it is creating a closure.  This is because the function that is being returned (inner) will still have access to the local variables of the function that is returning it (outer), even after the outer function has returned!  In C terms, this could mean that instead of the variables in the main function being allocated in the stack-frame, they are malloc-ed!

Now back to the partial function.

The first line of the inner function is making a copy of the arguments object (of the inner function) and concatenating it with the copy of the arguments object that we copied in the outer function, args.  And that is the reason why we took a copy of the arguments object when we first entered the outer function, so now we could access it and concatenate it with the new arguments (of the inner function).

The final line is then invoking the function func that was passed as an argument (from the outer function) with the current function as it's context (this) and with an array of all the arguments we built earlier on.
This is because the apply method takes 2 arguments; the first one is the object that will be bound to this and the second an optional array arguments.

Saturday, November 21, 2009

Function pointers in JavaScript

What do you think the following code alerts ?

var f = function () {
    alert('Function 1');

var pf = f;

f = function () {
    alert('Function 2');


If you answered 'Function 2', then you are wrong

First, a function f was created which now occupies a block of memory. Internally, the only reference the function has is the assigned location in the JavaScript's Heap.

When you a pass a function (var pf = f;), you are only passing a pointer to a function. This means that you are passing a reference to the memory location of the function, not the function name!

In the above code, pf is a pointer to the function f created beforehand. When we later on change to original function f to point to a different function, pf still retains its pointer to the original allocated function.

The only difference now is that the variable f is now pointing to a different memory address of the Heap (because it is now pointing to a new function)

No one should extend the Object.prototype in JavaScript!

In an earlier post, I wrote:

But everyone should keep in mind that extending the Object prototype in JavaScript is a big NO-NO

But why exactly should no one extend the Object.prototype?

What is the prototype?

Every object in JavaScript has a property (an object) called prototype (Introduced in JavaScript 1.1) that allows you to add custom properties and functions to every instance of that object.

Let's take an example.  First we'll add properties to objects without using the prototype:

var square = function () {  };

var box = new square();
box.height = 55;  //Adding a custom property to the box instance

In the above example, we created a new function called square and other one called box. The box is then initialized as an instance of square.
We then added a custom property to box called height and assigned a value to it.

If we now check the value of box.height, we get 55.

But if we now create another instance of a square, that new instance will not have the height property:

var anotherBox = new square();
alert(anotherBox.height) ; //alerts 'undefined' (not 0)

The reason undefined is displayed is because anotherBox does not have a property called height.

So the best thing to do is to add the height property to the square object, instead of the instantiated objects, via the prototype:

var square = function () {  };
square.prototype.height = 0;

//Now, every instance of square will have a height object

var box = new square();
box.height = 55;

var anotherBox = new square();
alert(anotherBox.height) //alerts 0

anotherBox.height alerts 0 because this time round, the anotherBox object has a property named height and it's set to 0.

I'll soon explain why it's a bad idea to extend the Object.prototype.

In JavaScript, every object inherits from an object called (not surprisingly) Object. Now, earlier on I described how when you attach a property to the prototype, it will exist in all instances of that basically, since every object inherits from Object, when you extend the Object's prototype, every object from then on will have that property that was added to the Object.prototype.

Let's take an example:

Object.prototype.myCustomProperty = 200;

var square = function () {  };
alert(square.myCustomProperty); // 200 is alerted

As you can see from the above example, square now has a property called myCustomProperty!

But now you may think that this won't cause problems because you will only call the properties you know exist in the object you create; and well, that may be true but the real problem occurs when you use the statement.

In JavaScript, there exists a construct that lets you iterate over all the properties of an object, the statement:

Object.prototype.myCustomProperty = 200;

var box = { width: 200, height: 500 };

var props = "";
for (var p in box) {
    props += p + "\n";

In the above code I am iterating over every property of the box object and appending the name of that property to a string called props.

The output of the above alert is :

So you see, myCustomProperty now appears as part of the box object! And when you iterate over properties of an object, you will want the properties of only that object and not properties that are up the inheritance chain!

Fortunately enough, there is a workaround for this. This workaround involves using the hasOwnProperty function:

Object.prototype.myCustomProperty = 200;

var box = { width: 200, height: 500 };

var props = "";
for (var p in box) {
    if (box.hasOwnProperty(p)) {
        props += p + "\n";

Now the alert displays:

This is because the hasOwnProperty returns true only if the property in the current iteration is directly linked to the object you are using in the loop; and thus, it returned false for the myCustomProperty property.

So make sure that when iterating over properties in JavaScript, you use the construct! ...or else bad things may happen if someone (probably some JavaScript framework) extends the Object.prototype!

Friday, November 20, 2009

Arduino with a 3x4 Keypad

The following is something I made a while back with an Arduino, a speaker I ripped off from an old toy and two LEDs:

To make use of the keypad, I used Arduino's keypad library.

I connected the keypad to the Arduino as follows:

Keypad Pin
Arduino Pin

The above keypad numberings map as follows:

To use in your code, make sure you include it:

#include <Keypad.h>

You also need to map out the keys like such:

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
    '1','2','3'    }
    '4','5','6'    }
    '7','8','9'    }
    '*','0','#'    }

//The below numbers correspond to the Arduino Pins
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6};    //connect to the column pinouts of the keypad

Afterwards, instantiate the Keypad:

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

Then to get the key pressed, it's just as simple as this:

char key = keypad.getKey();

Thursday, November 19, 2009

Stackoverflow's reverse-engineered WYSIWYM editor

If you want a lightweight, yet advanced (especially if you want it for a website for developers) online wysiwym editor, I suggest you take a look at Stackoverflow's reverse-engineered WMD Editor.

To download it, visit their development folder at github:

Note that in the demo, I used the wmd along with a modified Stackoverflow css file.

Konami Code in JavaScript

Yesterday I came to know about this thing called a Konami Code and about how many websites use it as an easter egg!

So I decided to write up my own JavaScript version of this Konami Code.  You can download the normal, unpacked version for development or the packed version for production.

Click here to view a demo

To use the code, following these instructions:

1. Download the konami.js file from one of the above-mentioned links and add it to your page:

<script src="konami.js"></script>

This will create a konamiCode object in your website, which can be used in multiple ways. The konamiCode object takes 2 parameters: combination (an array of keyCodes) and a callback function.

The combination parameter can be skipped and if it is skipped, the default combination will be the Konami Code (UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B, A)

2. The simplest way to enable the Konami Code for your website, is like such:

konamiCode(function () {
    alert('You entered the code!');

This will start the Konami code listener.

3. To stop listening for code input, store the konamiCode in a variable and call it's stop method:

var konami = konamiCode(function () {
                 alert('You entered the code!');


konami.stop(); // <== stop listening

4. To use a different combination, enter an array as the first parameter of the konamiCode function:

konamiCode([38, 40, 37, 39, 52, 53], function () {
    alert('You entered the code!');

The combination listed above is UP, DOWN, LEFT, RIGHT, 4, 2
As you can see, the elements of the array are the Key Codes of the keys, not the letters themselves. Use this website to convert from a key-press to a Key Code

Here is the unpacked code:

 * Konami Code in Javascript
 * Andreas Grech
 *  v 1.1 (20091119)

 Keycodes for the Konami Code
 UP    : 38
 DOWN  : 40
 LEFT  : 37
 RIGHT : 39
 B     : 66
 A     : 65

var konamiCode = function(combination, callback) {
 var lastCorrectInput = - 1,
 isActive = 0,
 o = {};
 if (typeof combination === "function") {
  callback = combination;
 if ( !== "[object Array]") {
  combination = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
 o.start = function() {
  if (isActive) {
  isActive = 1;
  document.onkeyup = function(e) {
   var code;
   if (!isActive) {
   code = window.event ? window.event.keyCode: e.which;
   if (combination[++lastCorrectInput] === code) {
    if (lastCorrectInput === combination.length - 1) {
     if (callback && typeof(callback) === "function") {
   lastCorrectInput = - 1;
  return o;
 o.stop = function() {
  isActive = 0;
  return o;
 return o;

Testing if an element is an array, in Javascript

Up till now, I have always used this function (taken from Crockford's The Good Parts) to check for array validity in JavaScript:

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&

But recently I came to know that a guy from Google (Mark Miller) used the following condition (by carefully reading the ECMAScript Standard):

var is_array = function (value) {
    return === '[object Array]';

Although mind you, the above isn't perfect either, because it can easily be broken by extending the Object prototype :

// native prototype overloaded, some js libraries extends them
Object.prototype.toString= function(){
  return  '[object Array]';

function isArray ( obj ) {
  return === '[object Array]';

var a = {};
alert(isArray(a)); // returns true, expecting false;

But everyone should keep in mind that extending the Object prototype in JavaScript is a big NO-NO . So, as of the moment, the most robust and concise way you can use to check for array validity in JavaScript is by using Miller's method.

Tuesday, November 17, 2009

Passing a pointer by reference in C

Today I needed a way to pass a pointer to an int to a function, modify the location of that pointer (via malloc) in that function, and then access the modified pointer from outside the function (from the caller).

I tried to code it like such (incorrectly):

int f(int *arr, int n) {
    int i;
    arr = malloc( n * sizeof (*arr));
    for (i = 0; i < n; ++i, ++arr) {
        *arr = i;
    arr -= i;
    printf("Second element (from function) : %d\n", *(arr + 1));
    return 0;

int main()
    int *arr;
    f(arr, 5);
    printf("Second element (from caller) : %d", *(arr + 1));
    return 0;
This is the output:

Second element (from function) : 1
Second element (from caller) : 1032044593

As you can see from the above output, the correct element is displayed when accessing the array from the function, but when I try to access the array from outside of the function (after it has been malloced and data was added), the value displayed seemed like a value from an unmalloced address!

What was I doing wrong?

The problem with the above code is that I am passing the pointer to an int by value to the function; ie a copy of the pointer.  That is why when I changed its address, the change was only visible from inside the function.

The Correct Way

The correct way to do it is to pass a pointer to the pointer to int (int **arr) to the function, like such:

int f(int **arr, int n) { //arr is now a pointer to a pointer to int
    int i;
    int *temp = malloc(n * sizeof **arr); //declare and malloc temporary space
    for (i = 0; i < n; ++i, ++temp) {
        *temp = i;
    temp -= i;

    *arr = temp;  //Assign the value of the inputted location to the temporary one created earlier on

    printf("Second element (from function) : %d\n", *(temp + 1));
    return 0;

int main()
    int *arr;
    f(&arr, 5);  //The address of the pointer is now passed, not the pointer itself
    printf("Second element (from caller) : %d", *(arr + 1));
Now the output from the above function is correct:

Second element (from function) : 1
Second element (from caller) : 1

Monday, November 16, 2009

Number of elements in an array in C

Take the following piece of code:
int main()
    int nums[] = {1,2,3,4,5};
    printf("Outside: %d\n",sizeof(nums) / sizeof(*nums));
    return 0;

int f(int nums[]) {
    printf("Inside: %d\n",sizeof(nums) / sizeof(*nums));

Here is the output of the above code:
Outside: 5
Inside: 1
As you can see from the above output, when the calculation is done in the scope where the array was initialized, the correct output is displayed; but when it is passed to a function, the calculation fails!
This is because the formal argument int nums[]  does not contain any information about the array whereas the declaration of the array in the main function contains an implicit size  (determined by the number of items in the value), so as long as you use the variable in the main function (ie where it was declared), the compiler knows the size of the array.

When you send the array as a parameter to the f function, there is no information about the size sent along, it's just a pointer to an array of unknown size. The f function could be called from anywhere, so the compiler can't use the information about the variable in the main function.
If you want to know the size of the array in the f function, you have to send that along with the array as another parameter.

Sunday, November 15, 2009

ShowSlow - A jQuery plugin for displaying elements in order, one by one with a delay

Recently I needed the functionality for displaying some hidden divs, in order, one by one, and with a timed-delay between each one.

Thus I wrote this jQuery plugin that does infact this (demo):

 * ShowSlow v1.1 - jQuery plugin
 *  Copyright (c) 2009-2010 Andreas Grech
 *  Dual licensed under the MIT and GPL licenses:

(function($) {
    $.fn.showSlow = function(options) {
        var opts = $.extend({}, $.fn.showSlow.defaults, options),
        elementCounter = 0,
        $elements = this,
        isStopped = 0,
        isPaused = 0,
        callbackExecuted = 0,
        executeCallback = function(val) {
            if (typeof opts.callback == "function") {
                callbackExecuted = 1;
        getValues = function() {
            return {
                elementsDone: elementCounter
        showNextDiv = function($element) {
            if (isPaused || isStopped) {
            if (!$element.length) {
            $element.slideDown(opts.slideTime, function() {
                setTimeout(function() {

        return {
            start: function() {
                if (isStopped || elementCounter < $elements.length) {
                    $elements.css("display", "none");
                    elementCounter = 0;
                } else if (isPaused) {
                    elementCounter -= 1;
                isStopped = 0;
                isPaused = 0;
                callbackExecuted = 0;
            stop: function() {
                isStopped = 1;
                if (!callbackExecuted) {
                return elementCounter; //return the number of elements displayed before stopped
            pause: function() {
                isPaused = 1;

    $.fn.showSlow.defaults = {
        slideTime: 1000,
        displayTime: 500

Saturday, November 14, 2009

Vim is like your average text editor...on steroids!

So recently I started using vim after a friend suggested it, and man I have to say, it's like your average text-editor on steroids!

vi was actually written in the 70s (1976), but I just started using recently.  Actually, what I started  I had read a lot about it on Stackoverflow, and last time my friend told me he uses vi when working with C (I, instead, had been using the Code::Blocks IDE); and so I decided to give vim (which is actually an extended version of the vi editor) a go during a *boring* Entrepreneurship lesson at school...and I was impressed and got so immersed in it that I even forgot I was still in a lesson at school.

What really impressed me with vim is the amount of work I can do with fewer keystrokes as possible.

Here is a list of couple of basic commands (from this answer over at stackoverflow) :

y(ank) - copy
d(elete) - delete
c(hange) - change
p(aste) - put from buffer after cursor
o(pen) - start a new line
i(nsert) - insert before current character
a(fter) - insert after current character
w(ord) - moves to beginning of next word
b(ack) - moves to beginning of current word or prior word
e(end) - moves to end of current word or next word
f(ind) - moves to a character on the current line
movement keys you just need to learn: h,j,k,l

^ - beginning of text on a line
$ - end of text on a line
0 - first position on line

most commands can be prefaced with numeric modifiers.
2w - means move 2 words
5h - means move 5 charcters to the left
3k - means move 3 lines up
3fs - means move to the 3rd letter s folling the cursor

modification commands (d,c,y) need to know how much to work on.
dd - delete a line into memory
yy - yank a line into memory
cc - change the whole line
c$ - change from current position to the end
c2w - change the text spanning the next 2 words
3dd - delete 3 lines
d2f. - delete to the second period.

. - means redo the last modification command.
/ - searches for text, and then n(ext) will go the next found occurance. N will go prior.
? - searches backwards through the document.

This is the book I used to start learning vim with:

Once I complete the above book, I'll have a go at O'Reilly's Learning the vi and Vim Editors