Discovered Bug in Firefox Javascript Engine

Posted November 16th, 2010 in Uncategorized by admin

I was debugging a web application today and I came across what I believe to be a bug by design in Firefox’s JavaScript engine. The problem lies with the implementation of the string function substring. The syntax for substring is:

substring(startIndex, [endIndex])

If you pass undefined to substring as the endIndex in the following way, endIndex should be undefined but will be treated by the substring function as zero resulting in an empty string being returned.

var testString = "This is a test.";
var startIndex = 0;
var endIndex;
//Substring returns "" in firefox  
//Substring returns "This is a test." in all other major browsers.
alert(testString.substring(startIndex, endIndex));

The expected behavior is that the string be returned from startIndex to the end of the string since endIndex is optional and in this case undefined. Other browsers (IE8, Chrome, Opera) tested exhibited the expected behavior.

After reading Mozilla’s documentation on substring (Mozilla Documentation of Substring) I believe the problem is that they are treating any non-numeric argument to substring as zero. The problem with this is that since end index is an optional argument, undefined should be treated as an omission rather than a non-numeric argument. I filed a bug with the Mozilla Foundation and will post an update with their response.

Update: Mozilla reports this will be fixed in Gecko 2.0.

This is present in the latest version of Firefox at the time of writing: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12

How many gifts are given during the course of the song The Twelve Days of Christmas?

Posted November 11th, 2010 in Uncategorized by admin

I was at a trivia game last night and the title question was asked. Teams had about three minutes to answer the question. Looking around I was amazed at how many teams were furiously trying to add up all the days rather than use some simple algebra and summations. When I got home I wrote up the solution using summations which is much more direct that actually adding up each day(mostly just to practice LaTeX): Solution

There are a variety of ways to approach this problem. Here is someone who solves it using tetrahedral numbers: link

Creating portable jQuery plugins for Google Maps

Posted August 4th, 2010 in Google Maps, jQuery by admin

One of the useful properties of Google Maps is the ability to write custom mapping applications quickly and easily using only JavaScript and HTML. The problem with many of these applications is they are custom written for a specific site and can be difficult to use for other purposes other than what they were originally designed for. In this tutorial I am going to show you how to create a custom plug in for Google Maps using the object oriented aspects of JavaScript to allow the plug in to be embedded in virtually any maps application using only a couple of lines of code.

For an example plug in I created a dialog box that allows a user to enter Latitude and Longitude coordinates to pan to any spot on the map. The plug in is completely self contained and can be added to any maps application using only a few lines of JavaScript. The plug in I created uses jQuery and jQuery UI to create a simple dialog box.

Here is an example of JavaScript code for a simple Google Maps application that includes a dialog to pan to coordinates (DEMO).

//Variable to hold the map
var map;
//Google Maps initialize function
function initialize() {
    var latlng = new google.maps.LatLng(42.37, -71.03);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("smallmap"), myOptions);
}
//jQuery onload function
$(document).ready(function(){
	//Initialize Google maps
	initialize(); 
	//Create a reference to a new dialog box
	var dialog = new GoToLocation();
	//Initialize the dialog
	dialog.Initialize(map);
	//Show the dialog to the user.
	dialog.Show();
});

As you can see from the code above, the dialog that allows a user to go to any location on the map is completely self contained and initialized with only a reference to the map. The dialog is included on the page with a reference to a JavaScript file. The dialog is written as a custom JavaScript object. Here is skeleton code for the Go To Location Dialog with comments.

GoToLocation = function() {
    //holds a reference to the map
    this.map = null;
    //holds a reference to the jQuery UI Dialog
    this.dialogRef = null;
}
GoToLocation.prototype = {
    Show: function() {
           //Displays the dialog to the user
    },
    Close: function() {
           //Closes the dialog
    },
    Initialize: function(m, title) {
          //Initializes the dialog with custom parameters, saves a reference to the map and the dialog, includes an optional title, appends the required HTML to the current document.
    },
    RegisterListeners: function(){
          //Called by Initialize to create the listeners required for the dialog functionality.
    },
    GetDialogHTML: function() {
          //Called by Initialize to get the HTML needed to create the dialog. 
    }
}

When you fill in all the functions the source code looks like this:Source

Once all the code is filled in you have a completely stand alone Google Maps plug in that can easily be used in any maps application.

Extending jQuery UI Dialog to Include Minimize Button

Posted July 7th, 2010 in jQuery by admin

The jQuery UI plugin includes a great set of tools for quickly putting together professional looking interfaces. One of the greatest advantages to using jQuery UI is that it is easy to add new features to existing widgets or to create your own widget that inherits from existing UI widgets. This tutorial assumes a decent knowledge of how jQuery’s events and selectors work and is aimed at people who are familiar with jQuery and jQuery UI who are looking to quickly add functionality to existing widgets.

There are two ways of extending UI widgets to suit your needs. The first is to extend the current widget. This means writing code that will be added to the current implementation of the widget you are extending. The second way is to use jQuery’s extend functionality to create an entirely new widget. Since adding a minimize button is fairy simple I am going to modify the existing jQuery UI Dialog widget.

Here is the template we will be using to modify the Dialog widget. This code can be placed in its own javascript file and then included after the jQuery UI javascript file and it will be used in any jQuery UI Dialog we create.

(function($){
	var _init = $.ui.dialog.prototype._init;
 
	//Custom Dialog Init
	$.ui.dialog.prototype._init = function() {
		var self = this;
                       _init.apply(this, arguments);
 
		//custom init functionality, variables and event binding goes in here
 
 
	};
	$.extend($.ui.dialog.prototype, {
		//Custom Dialog Functions go in here
	});
})(jQuery);

There are a few things we need to do to add the minimize functionality.

  1. We need to actually add the html so that our minimize button is part of the dialog and also we will need to add a restore button.
  2. We need to bind these buttons to handlers so our code to minimize and restore a dialog box will be called.
  3. We need to write the custom functions that will be called by the button handlers.

The first thing to do is add some variables to support our functionality and also to add the minimize and restore button to the dialog HTML. The code for this is as follows and goes in the dialog init part of the template:

//Reference to the titlebar
uiDialogTitlebar = this.uiDialogTitlebar;
 
//Save the height of the titlebar for the minimize operation
this.titlebarHeight = uiDialogTitlebar.css('height') + uiDialogTitlebar.css('margin-top') + uiDialogTitlebar.css('margin-bottom');
 
//we need two variables to preserve the original width and height so that can be restored.
this.options.originalWidth = this.options.width;
this.options.originalHeight = this.options.height;
 
//save a reference to the resizable handle so we can hide it when necessary.
this.resizeableHandle =  this.uiDialog.resizable().find('.ui-resizable-se');
 
uiDialogTitlebar.append('<a href="#" id="dialog-minimize" class="dialog-minimize ui-dialog-titlebar-min"><span class="ui-icon ui-icon-minusthick"></span></a>');
uiDialogTitlebar.append('<a href="#"class="dialog-restore ui-dialog-titlebar-rest"><span class="ui-icon ui-icon-newwin"></span></a>');

We have now appended the HTML needed for the minimize and restore buttons to the dialog title bar but they need a small amount of CSS for them to look right. The following CSS can go in its own file or you can append it to the CSS file that comes with jQuery UI. If you look in the jQuery UI CSS file you will see it is a slightly modified version of the CSS used for the close button on the dialog.

.ui-dialog .ui-dialog-titlebar-min{ position: absolute; right: 23px; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; }
.ui-dialog .ui-dialog-titlebar-min span { display: block; margin: 1px; }
.ui-dialog .ui-dialog-titlebar-min:hover, .ui-dialog .ui-dialog-titlebar-min:focus { padding: 0; }
 
.ui-dialog .ui-dialog-titlebar-rest{ position: absolute; right: 23px; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; }
.ui-dialog .ui-dialog-titlebar-rest span { display: block; margin: 1px; }
.ui-dialog .ui-dialog-titlebar-rest:hover, .ui-dialog .ui-dialog-titlebar-rest:focus { padding: 0; }

Now that the buttons have been correctly placed in the title bar of the dialog box, we need to bind handlers for their functionality. The following code will also go in the init part of the template.

//Minimize Button
this.uiDialogTitlebarMin = $('.dialog-minimize', uiDialogTitlebar).hover(function(){
	$(this).addClass('ui-state-hover');
}, function(){
	$(this).removeClass('ui-state-hover');
}).click(function(){
	self.minimize();
	return false;
});
 
//Restore Button
this.uiDialogTitlebarRest = $('.dialog-restore', uiDialogTitlebar).hover(function(){
	$(this).addClass('ui-state-hover');
}, function(){
	$(this).removeClass('ui-state-hover');
}).click(function(){
	self.restore();
	self.moveToTop(true);
	return false;
}).hide();

The code above creates a handler for the minimize button and one for the restore button and assign the buttons to a variable we will be able to use with the widget. The code uses jQuery’s useful method of chaining functions together after a selector. The restore button is also initially hidden since only one of the buttons should be visible at a time. The hover handlers are so the button’s hover functions mimic what happens when you hover over the close button. The click handler is calling a custom functions we have not defined yet: ‘self.minimize’ and ‘self.restore’.

The final step is to implement the minimize and restore functions. These functions will go in the second part of the template. Here is the implementation of the two functions, you will see it is mostly simple CSS manipulations to create the minimize and maximize behavior.

restore: function() {
 
	//restore resizable functionality
	this.uiDialog.resizable( "option", "disabled", false );
	//show the resizeable handle
	this.resizeableHandle.show();
 
	//We want to prevent the dialog from expanding off the screen
	var windowHeight = $(window).height();
	var dialogHeight = this.options.originalHeight;
	var dialogTop = parseInt(this.uiDialog.css('top'));
	if(dialogHeight+dialogTop > windowHeight)
	{
		var newTop = windowHeight-dialogHeight;
		this.uiDialog.css('top',newTop);
	}			
	var windowWidth = $(window).width();
	var dialogWidth = this.options.originalWidth;
	var dialogLeft = parseInt(this.uiDialog.css('left'));
	if(dialogWidth+dialogLeft > windowWidth)
	{
		var newLeft = windowWidth-dialogWidth;
		this.uiDialog.css('left',newLeft);
	}
 
	//restore the orignal dimensions
	this.uiDialog.css({width: this.options.originalWidth, height:this.options.originalHeight});
	//show the dialog content
	this.element.show();
 
	//swap the buttons
	this.uiDialogTitlebarRest.hide();
	this.uiDialogTitlebarMin.show();
},
minimize: function() { 
	//disable resizable
	this.uiDialog.resizable( "option", "disabled", true );
	this.resizeableHandle.hide();
 
	//Store the original height/width
	this.options.originalWidth = this.options.width;
	this.options.originalHeight = this.options.height;
 
	//collapse dialog
	this.uiDialog.animate({width: 200, height:this.titlebarHeight},200);
	//hide the content
	this.element.hide();
 
	//swap buttons to show restore
	this.uiDialogTitlebarMin.hide();
	this.uiDialogTitlebarRest.show();
}

The extended dialog widget is complete. When you put it all together here is the source code: Source

Here is a demo of the code: Demo

Further Extension

One function some people may like is for the dialog to minimize and stay fixed in a certain spot. This can be achieved easily by adding in some CSS manipulation to put the dialog in an absolute position on the screen and saving coordinates to restore it to.

Resources and Additional Reading

First Post

Posted June 22nd, 2010 in Uncategorized by admin

This is a test post. I also want to test code highlighting since I am planning on doing a lot of it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@login_required    
def usersChart(request):
     username = request.user.username
     points = []
     for i in range(24):
         sixHoursAgo = datetime.now() - timedelta(hours=6)
 
         currentStart = sixHoursAgo
         currentEnd = sixHoursAgo
         minutes = i*15
 
         delta = timedelta(minutes=minutes)
         minutes15 = timedelta(minutes=15)
 
         currentStart+=delta
         currentEnd+=delta+minutes15
 
 
         users = TrackingRecord.objects.filter(date__gt=currentStart,date__lt=currentEnd,location=username).values('uid').distinct()
         points.append(len(users))
         currentStart = currentEnd
         #a list to hold points to return to the live view
     json = simplejson.dumps(points)
     return HttpResponse(json, mimetype='application/json')

This is a short piece of code using the Django web framework to build a json objects of points to populate Javascript Sparklines chart. It is an AJAX method.

Here is the jQuery method to populate the graph:

   $(function() {
	var values = [];
    	$('#linegraph').sparkline(values, {width: values.length*2, lineColor: '#307b7b' });
           $.get("{{gm_base_url}}/editor/userschart/",
		function(data){
    		  points = data;
			for (var i = 0; i < points.length; i++) {
				values.push(points[i]);
			}
    		  $('#linegraph').sparkline(values, {width: values.length*2, lineColor: '#307b7b' 
                 }
           );
    });