• Shortcuts : 'n' next unread feed - 'p' previous unread feed • Styles : 1 2

» Publishers, Monetize your RSS feeds with FeedShow:  More infos  (Show/Hide Ads)


Date: Saturday, 12 Apr 2014 16:40
In Git, it is often useful to merge one specific commit from one branch into another. Frequently this happens when Using Git Interactive Rebase With Feature Branches, as you develop in the branch, you realize that one or more of your commits should be added to master right away, but not all the CLs. Enter git cherry-pick <changelist hash> for the win! The cherry pick command allows you to merge one CL from a branch, or even straight from the reflog into another branch.

Getting ready

For this article, lets assume you have a commit history that looks like:
fc64d55 -- d0e6ac9 -- 1edbe95 -- 24c685b -- 2f0514a  [master]
                         \
                          a70d41c -- b45af4a -- 38967f5 [branch feature1]
And we want to merge some important change in #b45af4a into master.

How do it…

The code to cherry pick the change into master is:
git checkout master
git cherry-pick b45af4a
Now rebase master on to the feature1 branch:
git checkout feature1
git rebase master
You may have to resolve conflicts, but notice that git is smart enough not to reapply the cherry picked changelist:
Applying: a70d41c
Applying: 38967f5

How it works…

It is important to note that cherry-pick behaves just like a merge. If there are merge conflicts that git cannot resolve, then it will ask you to manually resolve them. Consequently, the new changelist in master will not necessarily be identical to the cherry-picked CL, and it will definitely have a new hashcode. Fortunately, git tracks cherry-picked CLs, so when you rebase back onto the cherry-picked branch, it won’t duplicate the CLs and will restructure your history according to master. Also, while cherry-pick is great for merging one or two commits, it is not ideal from many commits. If you need to copy
Author: "--"
Send by mail Print  Save  Delicious 
Date: Friday, 28 Mar 2014 23:06
Last week I was busy at GDC and have not had time to put together a detailed article, so in the spirit of GDC, I thought I would share the latest iteration of my HTML5 gaming engine (still very rough). There has been a lot of progress around the Game class to support stages (or levels) and a score board to track the player’s score. The stages are demoed by a new version of the Snake game where collecting five powerups will cause a new and slightly more difficult map to render. This showcases a fully functioning Snake game: a movable snake, score incremented and snake grown by picking up powerups, and levels changing over time. Please try the Snake game demo and let me know your thoughts or any issues you experience. Eventually, I will revisit Snake to add enemies and eventually some type of multiplayer, but my next step for the platform will be to try out one or two other games to see how it holds up. I’ll share them with you when they are ready. You can read more about the original release at Introducing Gaming Engine - Snake Demo v1.
Author: "--"
Send by mail Print  Save  Delicious 
Date: Wednesday, 05 Mar 2014 05:01
Today’s article will be short and will cover a bash topic that frustrates me to no end. Please don’t use ; to separate commands, when you mean &&. There is an important difference between the two and many developers never realize that they want to be using && in their scripts.

How do it…

Here is a common oneliner that you might use to compile a package:
./configure ; make ; make install
In this example, we intend to configure the build, make it, and then install it (in that order). There is no reason to run make if the configuration step failed, and no reason to run make install, if either of the previous steps failed. However, that is exactly what the above code will do. What you really mean to write is:
./configure && make && make install
Now each command will only execute if the previous command was successful.

How it works…

When the ; operator is used as a separator between commands, bash will execute each command in order, but it doesn’t care about the result of the previous command. When the && operator is used as a separator between commands, bash will execute each command in order, but will continue only when the previous command return zero (errors are non-zero). For that reason, anytime command a is expected to execute successfully before running command b, then && should be used instead of ;. The reason that this gets under my skin, is that almost every time I see commands chained like this, the developer intended that command a executed sucessfully, before running command b, and every now and then something really bad happens if b runs and a did not. Please be conscientious of your fellow developers, who may have to consume your scripts, and make sure they do what you intend by using &&.

There’s more…

There is another separation operator ||, which will execute each command in order, but will continue only when the previous command returns a non-zero value. I like to use this operator with testing commands, where command a will fail and now command b needs to be run to fix things, or maybe command a was a platform test and command b needs to be run on other platforms.
Author: "--"
Send by mail Print  Save  Delicious 
Date: Friday, 21 Feb 2014 03:58
This article showcases a useful caching strategy for static data that is fetch via AJAX. We will use jQuery to setup a promise and cache the data in the localStorage for subsequent page loads or data loads.

Getting ready

A modern web browser supporting localStorage and JSON. Also, a basic understanding of promises[2] is helpful.

How do it…

Here is the code:
(function($) {
  var oKeyDeferredMap = {};
  
  function fnReadData(sKey) {
    var sValue = window.localStorage.getItem(sKey);
    return sValue ? JSON.parse(sValue) : sValue;
  }
  
  function fnWriteData(sKey, oData) {
    var sValue = JSON.stringify(oData);
    window.localStorage.setItem(sKey, sValue);
  }
  
  $.cachedAjaxPromise = function(sUrl, oAjaxOptions) {
    var oDeferred = oKeyDeferredMap[sUrl];
    var sValue;
    
    if (!oDeferred) {
      oDeferred = new jQuery.Deferred();
      oKeyDeferredMap[sUrl] = oDeferred;
      sValue = fnReadData(sUrl);
      
      if (sValue) {
        oDeferred.resolve(sValue);
      }
      
      if (!oAjaxOptions) {
        oAjaxOptions = {};
      }
      
      $.extend(oAjaxOptions, {
        error: function(oXHR, sTextStatus, sErrorThrown) {
          console.log('customer info request failed: ' + sErrorThrown);
          oDeferred.resolve(null);
        },
        success: function(oData) {
          // making assumption that data is JSON
          fnWriteData(sUrl, oData);
          oDeferred.resolve(oData);
        }
      });
      
      $.ajax(sUrl, oAjaxOptions);
    }
    
    return oDeferred.promise();
  };
}(jQuery));
Here is how to use the code:
oPromise = $.cachedAjaxPromise('/someURL').done(function(o) {
  console.dir(o);
});
Here is a codepen demoing the code:

See the Pen HtJcD by Matt Snider (@mattsnider) on CodePen.

How it works…

The code snippet adds a new function to jQuery cachedAjaxPromise which should be passed a URL returning a static JSON and returns a promise that will be resolved with the JSON object. The function checks the local storage for a value stored at the key of the url. If a value exists, then resolve the promise. If the value doesn’t exist, then fetch it from the server, cached into localStoage, and the promise is resolved or rejected based on the AJAX response cycle. All cached values are marshalled and unmarshalled using the JSON infrastructure to and from strings. Lastly, the jQuery deferred object, is also cached, to prevent duplicate AJAX requests or calls to the localStorage when promises for the same url are created. To use cachedAjaxPromise, provide a url and chain a done or then function. The success callback provided will be pass the JSON data. If you look at the example pen, you will see that the first time the pen is loaded (or after you clear the localStorage) it takes about two seconds (simulated AJAX request), but subsequent page loads resolve the data in millisecond (from localStorage). You may pass a second argument, as the configuration options to pass into $.ajax, but the success and error functions will be overwritten for use with the promise system. This a very simple example that is dependent on modern web browser technology. If you need to support legacy browsers, then you may need a polyfill the JSON[3] library and localStorage[4].

References

  1. jQuery Deferred
  2. Promises in Wicked Detail
  3. jQuery JSON Polyfill
  4. PersistJs - a localStorage Polyfill
Author: "--"
Send by mail Print  Save  Delicious 
Date: Tuesday, 18 Feb 2014 07:24
I must apologize for the dearth of articles these last couple of weeks. As some of you know, I recently joined Google and there is a lot of technology to come up to speed on. Specifically, I have joined the Google Play Games team, which is a core service of the android operating system. We provide APIs to help game developers build better games with less work, and I am super excited to be joining the team. Anyway, the google training weeks are over and my schedule is returning to normal, so I expect to get back to regularly posting articles this week.
Author: "--"
Send by mail Print  Save  Delicious 
Date: Monday, 03 Feb 2014 06:58
Today we’ll cover how to connect to github and EC2 through a draconian proxy allowing only port 80 and 443. Github uses SSH, so like EC2 it can be connected to using SSH tunnelling. This article is based on a blog post by tachang[1], which needed some additional explanation and changes to work behind my proxy. I will be explaining how to connect on a unix-based machine, but these settings should also work on windows (see tachang’s article for windows setup[1]).

Getting ready

You will need to install corkscrew[2] on your machine for tunneling SSH through the proxy, and git (if you don’t have it already). You will also need superuser access on your own machine and any EC2 instance that you want to connect to.

How do it…

Once corkscrew is installed, simply edit or create ~/.ssh/config with the following:
ProxyCommand /usr/local/bin/corkscrew proxy.<yourCompany>.com 8080 %h %p

Host github.com
	User git
	Port 443
	Hostname ssh.github.com
	IdentityFile "/Users/msnider/.ssh/rsa_id"
	IdentitiesOnly yes
	TCPKeepAlive yes

Host <ec2PublicDNSForYourServer>
    Port 443
    User ubuntu
	IdentityFile "/Users/msnider/.ssh/rsa_id"
	IdentitiesOnly yes
	TCPKeepAlive yes
Changes to ~/.ssh/config happen immediately, so at this point we can check to see if github connectivity has been restored:
>ssh github.com
Hi mattsnider! You've successfully authenticated, but GitHub does not provide shell access.
Connection to ssh.github.com closed.
When outside of the proxy, SSH to your EC2 instance and update the sshd_config file (mine was located at /etc/ssh/sshd_config on ubuntu) to also listen on port 443:
# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port 22
Port 443
...
Then restart the server so that the changes take effect. Also, log into EC2 and update the DMZ of the server to allow connections on port 443. Then check to see if SSH connectivity to your server has been restored:
>ssh ubuntu@<ec2PublicDNSForYourServer>
If you are not behind the proxy you can force SSH to use port 443 for testing:
>ssh -p 443 ubuntu@<ec2PublicDNSForYourServer>

How it works…

Looking at the ~/.ssh/config, the ProxyCommand tells SSH to tunnel through a proxy when connecting to any host. Change the location of corkscrew to where yours is installed, replace the proxy server domain (don’t put http:// in front of the name) with yours, and change the proxy port 8080 to the one you connect to your proxy on. The %h and %p are special variables that will be populated by SSH dynamically (target host and port respectively). Next the file defines all the hosts to connect to. We want to be able to connect to github.com and the EC2 public DNS for the instance. Under each Host definition the Hostname, Port, User, IdentityFile are important. The Hostname is the server DNS to connect to, if the Hostname is different from the Host; notice that the one under github.com has been changed to ssh.github.com (the github server that allows port 443). The Port is the port to connect on, and since your proxy blocks everything but 80 and 443, you need to use one of those two. The User should be changed to the user used to SSH into the server. And IdentityFile is the location of your private identify file used for SSHing to the server. I used RSA keygen[3] and have the same key on my server and github, but you can use any number of identify files and other cipher formats supported by SSH. Lastly, for SSHing to your EC2 server, you need to modify the sshd_config file on the server. This file configures the SSH service on the server, and needs to be told to also listen to port 443. The SSH service can listen to as many ports as you want, so simply add the port 443 line under the port 22 line. I tried to just restart the SSH service, but Ubuntu wouldn’t let me, since I was logged in over SSH, so I ended up restarting the machine. Since, you cannot connect to this server when you are behind the proxy, you will need make this change outside the office. Also, port 443 is typically reserved for secure HTTP connections, so adding this port may conflict with an existing HTTP service. The best way to get around this is to have a second server (without HTTP services running) that you SSH into when at work and connect through that machine to port 22 on the machine running the webserver.

References

  1. USING GITHUB THROUGH DRACONIAN PROXIES (WINDOWS AND UNIX)
  2. Corkscrew
  3. SSH Keygen
Author: "--"
Send by mail Print  Save  Delicious 
Date: Friday, 24 Jan 2014 08:08
In my not so copious spare time over the past few months, I’ve been working on a game engine to power two dimensional board-based games. The engine has a long way to go, but I have reach the first demo milestone and wanted to share it with you. Here is a basic version the snake game written using the game engine. It illustrates a working main thread, responsiveness to keyboard commands, interaction between a user controlled character and the game environment, and a simple map building engine. I chose the Snake game, because it is relatively simple, but has some unusual characteristics (growing character size, collision detection, power ups) that forced me to consider more complex behaviors in the game engine. The idea behind the engine is to allow developers to build a two dimensional board-base game using a combination of HTML/CSS/JavaScript. For most games, I expect a user to control a sprite and move it around the board, but it should eventually be versatile enough to even support multiplayer board games. See the source files on github for more information. Obviously, there is still a lot missing from the engine, so I won’t go into its details yet, but the engine and the Snake game are at a point where you can begin to play around with it. The next demo will have a finished version of Snake, then I’ll use the engine to build a second game, a third game, and so on. By the completion of the third game, I believe the engine will be ready to be consumed by other game developers looking to build some simple browser games.
Author: "--"
Send by mail Print  Save  Delicious 
Date: Sunday, 19 Jan 2014 00:58
In my experience, it is rare to assign only a change event to a text input, as any callback that would be executed for the change event should also be called on a key event as well, but with a slight delay (think how an autocomplete shows results as you type). This is a common pattern and I was surprised to not immediately find a jQuery plugin implementing it, so I decided to add one myself.

How do it…

The jQuery plugin is available at http://plugins.jquery.com/changeOrDelayedKeyListener/. Here is the basic way to use it (just like other jQuery events):
$('someSelector').changeOrDelayedKey(function(e) {
    // your event callback
});
You can pass a data object as the first argument, like other jQuery events:
$('someSelector').changeOrDelayedKey({/* a data object*/}, function(e) {
    // your event callback
    // e.data is the data object
});
There are two optional arguments for specifying the delay and the key event to use (keydown is used by default):
$('someSelector').changeOrDelayedKey(function(e) {
    // your event callback
}, 400, 'keyup');
And here is the code:
$.fn.changeOrDelayedKey = function(fn, iKeyDelay, sKeyEvent) {
	var iTimeoutId,
		oEventData;

	// second signature used, update the variables
	if (!$.isFunction(fn)) {
		oEventData = arguments[0];
		fn = arguments[1];
		iKeyDelay = arguments[2];
		sKeyEvent = arguments[3];
	}

	if (!iKeyDelay || 0 > iKeyDelay) {
		iKeyDelay = 500;
	}

	if (!sKeyEvent || !this[sKeyEvent]) {
		sKeyEvent = 'keydown';
	}

	// non-delayed event callback, should clear any timeouts, then
	// call the original callback function
	function fnExecCallback() {
		clearTimeout(iTimeoutId);
		fn.apply(this, arguments);
	}

	// delayed event callback, should call the non-delayed callback
	// after a short interval
	function fnDelayCallback() {
		var that = this,
			args = arguments;
		clearTimeout(iTimeoutId);
		iTimeoutId = setTimeout(function() {
			fnExecCallback.apply(that, args);
		}, iKeyDelay);
	}

	if (oEventData) {
		this.change(oEventData, fnExecCallback);
		this[sKeyEvent](oEventData, fnDelayCallback);
	}
	else {
		this.change(fnExecCallback);
		this[sKeyEvent](fnDelayCallback);
	}

	return this;
};
The following example shows the event callback (the delay has been increased to 1000ms so it is easier to trigger the change event):

See the Pen jQuery on Change or Delayed Key Event Listener by Matt Snider (@mattsnider) on CodePen.

How it works…

The changeOrDelayedKey function has two signatures (this is common with jQuery functions). The first signature is a required callback function, an optional integer in milliseconds to delay before firing the callback on key events, and an optional string name of the key event to target. By default the key delay is 500 milliseconds and the keydown event is used. The second signature has an object, followed by the callback function, and then both optional arguments. And like most jQuery functions, changeOrDelayedKey is chainable. Looking under the hood, the implementation is fairly simple. The changeOrDelayedKey function first figures out which signature was sent, assigning the correct values to local variables, and sets any defaults. There are two inner functions, the fnExecCallback simply clears any existing timeout and calls the original callback function, while fnDelayCallback waits the delay time before calling fnExecCallback. Some implementations my avoid the extra fnExecCallback, but I want to make sure that the internal timeout is always cleared before delegating to the provided callback functions. Lastly, the fnExecCallback function is assigned to the change event and the fnDelayCallback function is assigned to the desired key event.

There’s more…

There are two caveat when using the changeOrDelayedKey function. The first is that it doesn’t work well with the jQuery event off function for unsubscribing from events. You can use the off function to remove all change and keydown events, but you can’t remove just the callback function that you provided, because the actual callback function passed into change and keydown listeners is an anonymous function. I don’t foresee a big demand for this feature, so I haven’t included it. The second is that I haven’t wired it into the jQuery event on function. The signature for the on function adds more complexity that I did not want to support unless absolutely necessary. And since listeners can be called directly, I don’t see a need yet for supporting the on function.
Author: "--"
Send by mail Print  Save  Delicious 
Date: Tuesday, 07 Jan 2014 03:55
Continuing to evaluate efficient sorting algorithms, today we’ll look at merge sort. Merge sort[1] is a comparison sort using a divide and conquer algorithm, developed by John von Neumann[2] in 1945. It recursively divides the list into smaller sublists of length one, then repeatedly merges the sublists in order until there is only one sublist left. It has a worst case runtime of (O(nlogn)), making it worst-case more efficient than Quicksort.

How do it…

Merge sort needs two functions, the first is a function to merge two ordered arrays together:
function fnMerge(aLeft, aRight){
	var aResult = [],
		iLeft = 0,
	    iRight = 0;

	// iterate until one array is empty
	while (iLeft < aLeft.length && iRight < aRight.length) {
		// push the next ordered value on the resulting array
		// and increment its counter
		if (aLeft[iLeft] < aRight[iRight]) {
			aResult.push(aLeft[iLeft++]);
		}
		else {
			aResult.push(aRight[iRight++]);
		}
	}

	// join any remaining values from the two arrays into the results array
	return aResult.concat(aLeft.slice(iLeft)).concat(aRight.slice(iRight));
}
The second function is the public merge sort function that recursively splits the array into smaller halves before calling the merge function:
function fnMergeSort(aList) {
	// zero or 1 length arrays are already sorted
	if (2 > aList.length) {
		return aList;
	}

	var iMiddle = Math.floor(aList.length / 2);
	return fnMerge(
        fnMergeSort(aList.slice(0, iMiddle)),
        fnMergeSort(aList.slice(iMiddle)));
}
This visual is a little harder, but it shows each step of the splitting and merging functions:
Restart merge sort With a New Array If we take a 10,000 element array and sort it, here is how merge sort compares to native array sort (prints to the console): Merge sort Comparison Tests

How it works…

The merge sort algorithm recursively breaks the array into smaller subarrays by splitting the arrays in half, until all subarrays are length one or zero. By their nature (having only one or zero element), these subarrays are sorted. The algorithm then recursively merges the sub arrays together in order. As each subarray is combined the new subarray is ordered from the two merging subarrays, resulting eventually in one final sorted array. Since the same steps need to be taken regardless of how sorted the original array was, merge sort has an average, best, and worst case runtime of O(nlogn). The merging function accepts two sorted subarrays and merges them together into a new sorted array. We solve this by iterating until one array is fully merged, using index trackers on each array, and inserting the greater value into the merged array on each iteration. Since both lists are in order, we know that when the iteration stops, all uncompared elements in the second array are greater than the already joined elements, so we can just concatenate the remaining elements at the end[3]. Rather than using an if statement to concatenate the right subarray, we just concatenate the remaining elements of both arrays, so the fully merged array will concatenate zero elements, and the other will concatenate all unmerged elements. The merge sort function accepts a single array and splits it into two relatively even subarrays (if the array has an odd length, one subarray may be an element larger than the other). Those subarrays are each passed to the merge sort function and the results of the recursive merge sorts are joined using the merge function. Thus eventually, returning a single sorted array. The recursive calls stop when the subarrays are all of length one or zero.

There’s more…

If it is important that your merge sort function modifies the passed in array, you can use the following technique to splice the new elements into the original array[3]:
function fnMergeSort(aList) {
    // zero or 1 length arrays are already sorted
    if (2 > aList.length) {
        return aList;
    }

    var iMidIndex = Math.floor(aList.length / 2);
    var aParams = fnMerge(
        fnMergeSort(aList.slice(0, iMidIndex)),
        fnMergeSort(aList.slice(iMidIndex)));

    // put arguments one and two of the splice function into the
    // front of aParams, remaining arguments are elements to splice in
    aParams.unshift(0, aList.length);
    aList.splice.apply(aList, aParams);
}
Here we’ve used the splice function to replace all the elements in the provide array with the sorted elements, so that the originally provided list is modified, instead of returning a new sorted array. The signature of the splice function is the start index, the length to splice, and any number of elements to insert to replace the range we are splicing over. As such, we unshift the start index and length for the splice to the front of the array of sorted elements, so that we can use the apply function to properly pass everything into the splice function, which has a signature startIndex, lengthOfSplice, firstElementToSpliceIn, …, nthElementToSpliceIn.

References

  1. Merge sort Wikipedia article
  2. John von Neumann
  3. Computer science in JavaScript: Merge sort
Author: "--"
Send by mail Print  Save  Delicious 
Quicksort   New window
Date: Wednesday, 11 Dec 2013 07:04
We’ve looked a variety of in-efficient sorting algorithms, today we’ll look at Quicksort (aka. partition exchange sort), as a first foray into faster and more frequently used sorting algorithms. Quicksort[1] is a comparison sort using a divide and conquer algorithm, developed by Tony Hoare[2] in 1960. It recursively divides the list into smaller lists around a pivot value and sorts them, which means much smaller data sets when actually sorting. It has a worst case runtime of (O(n2)), but an average and more common runtime of (O(nlogn))

How do it…

We first need an algorithm to determine the pivot value. There are many algorithms, but we’ll use a recommended technique, taking the median of the first value, last value, and middle value in an array:
function getPivot (arr) {
	var iValFirst = arr[0],
			iLast = arr.length - 1,
			iValLast = arr[iLast],
			iMid = Math.floor(arr.length / 2),
			iValMid = arr[iMid];

	// first position is lowest
	if (iValFirst < iValLast && iValFirst < iValMid) {
		return iValMid < iValLast ? iMid : iLast;
	}
	// mid position is lowest
	else if (iMid < iValLast && iMid < iValMid) {
		return iValFirst < iValLast ? 0 : iLast;
	}
	// last position is lowest
	else {
		return iValFirst < iValMid ? 0 : iMid;
	}
}
Here is a the quicksort algorithm in JavaScript:
function quicksort (arr) {
	var aLess = [],
        aGreater = [],
        i,
        j,
        iPivot,
        iPivotVal;

	// array of length zero or one is already sorted
	if (arr.length <= 1) {
		return arr;
	}

	iPivot = getPivot(arr);
	iPivotVal = arr[iPivot];

	// the function to process the value and compare it to
	// the pivot value and put into the correct array
	function compVal(iVal) {
		(iVal <= iPivotVal ? aLess : aGreater).push(iVal);
	}

	// compare values before the pivot
	for (i = 0, j = iPivot; i < j; i++) {
		compVal(arr[i]);
	}

	// compare values after the pivot
	for (i = iPivot + 1, j = arr.length; i < j; i++) {
		compVal(arr[i]);
	}

	// create a new list from sorted sublists around the pivot value
	return quicksort(aLess).concat([iPivotVal], quicksort(aGreater));
}
It is a little hard to follow, but this demo chooses a pivot (blue), then puts the values into the two sub-arrays (red), before merging the arrays around the pivot, placing the pivot in its final position (black):
Restart Quicksort With a New Array If we take a 10,000 element array and sort it, here is how quicksort compares to native array sort (prints to the console): Quicksort Comparison Tests

How it works…

The Quicksort algorithm breaks the array into two parts around a pivot value, pushing smaller values into one array and larger values into a second array. These two arrays will then be quicksorted recursively, before concatenating them around the pivot value. Generally, this strategy will quickly sort the array, but the efficiency of the algorithm depends on how well the pivot value is calculated. The more equal in size the smaller and larger value arrays are, the more efficient the algorithm. There are many strategies for choosing a pivot value, such as picking a dedicated position (first or middle are common), or randomly choosing a position. However, none of these do anything to increase the likelihood that the two arrays of values are about the same size. The recommended strategy for finding the pivot is to take the median of the first value, middle value, and last value in the array. This is more likely to get a value that is near the middle when sorting. These values are also better than randomly choosing three, because they sort already sorted arrays faster. For a random distribution quicksort tends to perform better than most sorting algorithms, because it quickly divides the array into smaller arrays that tend to sort quickly. However, it will perform quadratically on array with mostly duplicate values, as the pivot does not help much and the split arrays are unbalanced. If you compared it to the built in sorting algorithm (above), you⁏ll notice only a few milliseconds of difference between the two on a large array. Lastly, Quicksort is not very efficient on small data sets since its constant operation (slicing and merging arrays) is more expensive than other sorting algorithms. One of the best optimizations is to determine a threshold k where the smaller arrays are sorted using Insertion Sort instead. The k value is best determined by experimenting on your data set.

References

  1. Quicksort Wikipedia article
  2. Stony Hoare
Author: "--"
Send by mail Print  Save  Delicious 
Date: Saturday, 23 Nov 2013 23:26
This technique has been around for a while, but it’s powerful and worth sharing. Using the filter CSS property you can apply visual effects to your elements, including the grayscale we’ll be discussing here. For my CV I wanted my image muted most of the time, but pop when it becomes the focus of the viewer (ie. they mouse over it), so I used a filter to apply grayscale by default and remove grayscale on hover. This article will explain how to do this technique.

How do it…

To start choose markup or an image that should be grayscaled. I will use the following image for this demo: photo Next define your CSS:
.grayscale {
    filter: url(../files/filters.svg#grayscale); /* Firefox 3.5+ */
    filter: gray; /* IE6-9 */
    -webkit-filter: grayscale(1); /* Google Chrome, Safari 6+ & Opera 15+ */
}

.grayscale-hover:hover {
    filter: none;
    -webkit-filter: grayscale(0);
}
For FireFox, we also need to define the SVG filter file:
<svg xmlns="http://www.w3.org/2000/svg">
 <filter id="grayscale">
  <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"/>
 </filter>
</svg>
For FireFox, instead of a separate file, you can also use a data-uri:
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
Here is the image with the new CSS applied: photo

How it works…

The filter property[1] is still experimental and only implemented fully in webkit browsers with the webkit- prefix. FireFox and IE 10+ supports only the url(…); value, which can reference a filter.svg file to define any number of filters using the SVG filter element[2]. IE 6-9 implemented a non-standard filter property. For browsers properly supporting the filter property, the following values may be used: blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, sepia, and url[3]. So for Chrome, Safari, and Opera, we use the property -webkit-filter with the grayscale(N) value set, where N ranges from 0 to 1, indicating how much to gray the content. For IE 6-9 we use the non-standard gray value and none to remove the graying. Also, IE 6 does not support the hover pseudo-class for non-anchor elements, so deal with that how you will (I choose to ignore it). For FireFox we define what grayscale means using the SVG feColorMatrix filter and also none to remove the filtering. Unfortunately, in IE 10 Microsoft decided to remove legacy filters and not implement the working standard, so this technique does not work in IE 10+. My take is to just ignore IE 10+ users, because supporting them is not worth the effort, but there are three solutions to support them: using an inline SVG element[4], applying grayscale to the image using a photo editor and swapping images on hover, or changing compatibility mode back to IE 9. Not of them are great solutions, but I think making two images is probably the simplest. If you choose to change the compatibility mode, here is the markup (keep in mind you may loose IE 10+ features by using this):
<meta http-equiv="X-UA-Compatible" content="IE=9">

References

  1. filter – css | MDN
  2. SVG filter element
  3. Filter Effects 1.0
  4. Grayscale JSFiddle by Karl Horky
Author: "--"
Send by mail Print  Save  Delicious 
Date: Wednesday, 30 Oct 2013 21:54
Lately, I have been interviewing many engineers who are interested in a CSS contractor position, and am thoroughly disheartened by the number of candidates who put CSS expert on their resume, but don’ even know the basics of CSS. This article will discuss the ten questions I usually ask, including the answer and why I ask the question. My hope is not to just give the answer, but to educate as well.

Questions

Each question has a point value associated with it and the sum of all points adds up to 12. When I ask the question, I rate the candidate’s answer. They receive positive points for correct or partially correct answers (up to the question’s point value), zero points for lame answer, but not blatantly wrong answers, and negative points for incorrect answers (up to the question’s point value). At the end of the interview I add up all the points. If the score less than an 8, I will pass, an 8-10 I will consider, and a 10+ is a good score.
How do you setup your CSS to minimize cross-browser issue? (1 point)

This question explores the candidate⁏s understanding of the CSS development ecosystem, how up-to-date on CSS technology they are, and if they have any bad habits.

The best answer is to apply a set of normalization CSS1, ensuring the standard elements have a consistent default behavior across all browsers. For bonus points they may mention that it is a good idea to create a baseline CSS file setups the default element and class behavior for their project.

Alternatively, they may mention using a CSS framework, which takes care of cross-browser issues. It’s best if the candidate understands what the framework is doing to normalize, but I will let this kind of answer slide. They may also use * to target all elements and reset padding, margins, etc., but this is over-broad and inefficient.

Sometimes candidates will say they use browser specific CSS files and various methods for targeting each browser (usually using the user agent). It is never good to use the user agent, and this should always be a last resort. This answer is not acceptable. It is okay to occasionally use IE conditional comments, if the candidate understands they should be used sparingly and only if normalization does not work.

Create a CSS rule that removes the default underline applied to anchor elements, and then create a rule restoring the underline on hover (followup: are there issues with using hover on non-anchor elements or ask about other pseudo classes). (1 point)

This question will show the candidate understands the basics of CSS and has some knowledge of a commonly used property. Additionally, they have used and basically understand pseudo classes.

        a {
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
        

Sometimes candidates will understand how to target anchors and apply the hover pseudo-class, but not know the text-decoration property and use some bogus property instead. I won’t give zero points if they use the wrong property, but correct selectors.

How would you center a block level element inside it’s parent container? (1 point)

This question will show the candidate understands how to center block level elements, which is commonly used to center a website on a page. This question tends to trick people up and separates good CSS engineers from poor ones.

        
CENTER ME

The candidate needs to know the margin property and a width property are required. The element needs a width smaller than the parent container for this to work (otherwise, it will fill the available width by default and apply no left/right margin). I may give a bonus point if they know the cross-browser CSS to center a page (IE < 6):

        body {
            text-align:center;
        }
        a:hover {
            margin:0 auto;
            text-align:left;
            width: 980px;
        }
        

Usually, candidates answer this wrong by trying to use the properties text-align or position, or JavaScript. All of these answers get negative points.

What is the difference between visibility:hidden and display:none? (1 point)

Both of these properties will be used frequently in DOM scripting and it is important the candidate understands how both behave, so they use them correctly.

Using display:none will cause elements to render as if the element and its content does not exist on the page. Removing display:none or applying another display will cause the page to reflow. While visibility:hidden will cause the element to be invisible, but the element and its content will flow normally.

What are three different ways to write the color property to set it to blue (followup: which way do you prefer and why)? (1 point)

This checks if the candidate understands the three ways to apply color rules, and the followup ensures they know the correct way to do it.

The following CSS shows the five different techniques for applying color (but the three key answers are: by name, hex, and rgb). They should prefer using rgb or hex values, because they have more control over which flavor of the color they really want to use and not be dependent on the browser defaults (browser support of named colors is no longer an issue). I may give a bonus point if they know the hex short-hand and rgba without prompting.

        div {
            color:blue;
            color:#0000FF;
            color:#00F;
            color:rgb(0,0,255);
            color:rgba(0,0,255,1);
        }
        

I will not give any positive points if they don’t listen and apply a color other than blue; it indicates the candidate is a poor listener.

Write a selector to apply 5px padding to all input elements of type text? (1 point)

Shows the candidate has experience with more advanced selectors. I sometimes write a form with a text and button input to illustrate this question.

        input[type=text] {
            padding: 5px;
        }
        
What color will the text inside the div be? (2 point)
        <div class="foo" id="bar" style="">Color?</div>
        <style>
            div {color: red;}
            #bar {color: green;}
            .foo {color: blue;}
        </style>
        

Does the candidate understand how specificity2 rules apply to a single element.

The id attribute is more specific than class is more specific than element, so the text will be green.

Any answer talking about order of attributes or order of rules in the stylesheet automatically gets zero or less points, as order of attributes has nothing to do with specificity and order in stylesheet only applies to rules with the same specificity.

If an element has an inline style making it red, how can you override it in your CSS file (followup: when should you use this technique)? (1 point)
        <div class="foo" id="bar" style="color:blue">Make Me Red</div>
        <style>
            div {color: red;}
            #bar {color: green;}
            .foo {color: blue;}
        </style>
        

Does the candidate understand that inline styles are the most specific, but they can be overwritten using the important declaration.

Adding the !important declaration will supersede the specificity rules, except versus other properties with the !important declaration. However, it prevents other CSS rules from modifying the property, so !important should be used rarely, if at all.

            div {color: red!important;}
        
Which of the following is the most specific (what color is the text and why)? (2 point)
        <div class="bar">
            <span class="foo">
                Which color am I and why?
            </span>
        </div>
        
        div .foo {color: red;}
        .bar span {color: green;}
        span.foo {color: blue;}
        

This is a more advanced specificity2 question, it ensures the candidate understands specificity and knows the last rule applies when rules have the same specificity.

This is kind of a trick question, because all three rules have exactly the same specificity so the last rule applies and the color is blue. All three rules have one element and one class in the selector.

Sometimes the candidate will get the right answer for the wrong reason. It is important they understand each rule has exactly the same specificity and the last rule applies for that reason only.

Which of the following produces more maintainable and scalable CSS and why? (1 point)

A)

        <ul class="myList">
            <li></li>
            <li></li>
            …
        </ul>
        
        .myList {
            /* list styles here */
        }
        .myList li {
            /* list item styles here */
        }
        

B)

        <ul class="myList">
            <li class="myList-item"></li>
            <li class="myList-item"></li>
            …
        </ul>
        
        .myList {
            /* list styles here */
        }
        .myList-item {
            /* list item styles here */
        }
        

Has the candidate worked on a large CSS project before or do they understand SMACCS3 principles.

While A may produce more concise JavaScript, B is better on large, shared projects for the following reasons:

  1. The CSS parser and renderer processes rules from right to left, so longer selectors require more tree traversals causing the page to render slower.
  2. Using all classes separates the design from the markup, so the markup can be changed to different elements later or used in other places, without having to change the CSS.
  3. There are no accidental style inheritances to prevent, as happens most often when nesting lists or tables.

I may only give zero points, instead of negative points if they choose A, but can come up with some good reasons, such as they like to namespace styles or they use a CSS preprocessor.

Conclusion

These are the questions I like to ask CSS-focused candidates and I think they demonstrate if the candidate has good understanding of CSS and related principles. Additionally, this article should be used as a training tool for anyone needing to come up to speed on CSS. I have included links below for concepts that were beyond the scope of this article. Please let me know if you need more explanation or if any of my answers are confusing.

References

  1. Normalize CSS
  2. Specificity
  3. Scalable and Modular Architecture for CSS
Author: "--"
Send by mail Print  Save  Delicious 
Date: Saturday, 05 Oct 2013 01:05
In an earlier article we covered Variable Hoisting in JavaScript. At the time, I did not expect to face a hoisting related code bug so quickly. And given the circumstances of the bug, I expect it to be one of the most common hoisting problems, so I wanted to share it.

How do it…

Let’s jump right into the setup. You have a function that is defined in one JavaScript file (this file is expected to load first, but may not). Here is simple cross-browser safe logger function:
function logger() {
    if (window.console) {
        console.log.apply(console, arguments);
    }
}
In another JavaScript file (expected to load later asynchronously), the existence of the first function is checked. This second file creates a temporary dummy function, if the original function does not exist:
if (!logger) {
    function logger () {};
}
The problem can also be triggered directly in a single file:
<script>
function test () {
    alert('failed to hoist');
}

if (! test) {
    function test() {
        alert('hoisted');
    }
}

test();
</script>
Everything loads in the correct order, but for some reason the logger function is the second function. What gives? hoisting

How it works…

Here is what happens. The first file loads as expected and defines the the debugger function. Then the second file loads and the if statement does not execute, but nonetheless, the logger function inside of the if statement is hoisted to the top of the current scope. In this example the execution context is the window and the function declaration is hoisted to the top of the window scope. Additionally, since functions are hoisted completely defined, the empty logger overrides the original function. This really only becomes a major problem, because we are in the global scope, so hoisting problems are not contained. There are many ways to prevent this, but we’ll cover two. The first (and my favorite) is to write all scripts inside an enclosing function to contain any hoisting to the enclosing functions execution context:
(function() {
    if (!window.logger) {
        window.logger = function() {};
    }
}());
The second option is to just use window as an object literal, as we did inside the enclosing function above:
if (!window.logger) {
    window.logger = function() {};
}
The first is just good practice, for writing all scripts, as it forces you to do the right thing automatically and prevents accidental hoisting. Dont’t let global hoisting issue bite you, never work directly in the global execute context.
Author: "--"
Send by mail Print  Save  Delicious 
Date: Tuesday, 17 Sep 2013 07:24
This is a proof of concept widget that I demoed for work. The desire is to update some text according to a regex and replacement, when an input field changes. This will allow developers to show a message and/or format the input value, so users understand they do not need to enter meta characters and see the result of their input (think phone or identification numbers). I built a simple jQuery plugin that can be used by anyone, and here is a demo app with the code.

How do it…

I'm not going to show a sample of JavaScript code, because it is not terribly complicated, but I will discuss how it works it in the next section. Here is an example of the markup:
<div>
  <label>Test US Phone</label>
  <input id="id_test_us_phone" data-placeholder="0" data-rxmatcher="(\d{3})(\d{3})(\d{4})" data-replacement="$1-$2-$3" maxlength="10" type="text" value="" />
  <span class="regexInputNote"></span>
</div>
If you include the plugin, then you can activate this markup using:
$('#id_test_us_phone').regexInputNote();
All hardcoded attributes can be changed by passing options to the regexInputNote. Here are the defaults:
$('#id_test_us_phone').regexInputNote({
  dataAttrMatcherRegex: 'rxmatcher',
  dataAttrPlaceholder: 'placeholder',
  dataAttrReplacement: 'replacement',
  invalidText: 'Invalid input',
  replacementFunction: null,
  targetClass: sPluginMarker
});

How it works…

When the script runs it searches the siblings following the span for an element with the class defined as targetClass (default is regexInputNote). This indicates the element that will have its content replaced by the script. The script uses the dataAttrMatcherRegex (defaults to data-rxmatcher) to create a regex to evaluate anything typed into the input element, and then it uses the dataAttrReplacement (defaults to data-replacement) as the replacement string. So if you type 1234 into the input it will insert the equivalent of '1234'.replace(<value of data-rxmatcher>, <value of data-replacement>) into the sibling element. There is one caveat, because we are using regex replacement, the input string must always match the regular expression for the replacement to work. Normally, 1234 would not match a phone number regular expression (since it does not have 7 or 10 digits), so I introduced the dataAttrPlaceholder (defaults to data-placeholder) which is the value to be used to fill the user input to the necessary length before running the regex replacement. This requires you also specify a maxlength attribute, so we know how long the string should be and what length the regular expression is expecting. Continuing with the phone example, if 1234 is entered, then the output would be 123-400-0000 showing the input formatted as a phone number. Finally, if the transformation is sufficiently complex, it may not be possible with a regular expressions. For those cases, instead of using the attributes, the developer can simply set a function to the replacementFunction option. This function should accept the text input as its only argument and return whatever value should be written to the sibling element. If you look at the JavaScript code, you will see that it is pretty straight forward. When the plugin initializes, it reads the data attributes and finds the sibling element before subscribing a key and change listener to the input. The callback handler just applies the regular expression or replacement function to the input and inserts it into the next sibling.
Author: "--"
Send by mail Print  Save  Delicious 
Date: Thursday, 29 Aug 2013 21:27
Hopefully, your job does not have to support corporate customers whose IT departments do not keep the companies browsers up-to-date, and therefore do not need to support older version of IE. If however, like me, you need to support older IEs, then your companies designers have probably asked you to support rounded corners in IE. The three most common techniques to solve rounded corners are to use JavaScript [1] or an HTC Access[2] file to produce VML (Vector Markup Language[5]) on demand, or a JavaScript solution that inserts positioned divs to emulate rounded corners[3]. However, all these solutions are slow (search the DOM for rounded elements on load or round on demand), kinda hacky, and require recalculations as rounded elements are repositioned. The core of the first two strategies is to dynamically inject VML into the document using scripts, but there is no reason you have to use scripts to do this. You can render the VML directly into your HTML and ship the rounded corners with the HTML. This allows the browser to render the rounded corners in the page flow as the page is parsed for a faster page loads and proper document flow. Today’s article will describe how to included rounded corners directly in your HTML for support in IE and all other browsers and is based on work originally done by Jonathan Snook[4].

How do it…

Enable VML on the body of your page (namespaced as v):
<body>
<xml:namespace implementation="#default#VML" ns="urn:schemas-microsoft-com:vml" prefix="v">
<!-- page body will go here -->
<xml:namespace>
</body>
Use the rounded rectangle VML tag to create a rounded rectangle:
<v:roundrect arcsize=".04" fillcolor="#000">
Lorem ipsum dolor sit amet, consectetuer adipiscing 
</v:roundrect>
Enable the VML via CSS for IE and other browsers:
v\:roundrect {
  color: #FFF;
  display: block;
  background-color: #000;
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px;
  border-radius: 10px;
  padding: 20px;
  height: 100%;

  /* IE-specific */
  behavior: url(#default#VML);
  /background-color: transparent;
}
Unfortunately, this doesn’t work in IE 8 standards mode, so we have to degrade IE 8 to behave like IE 7:
<!--[if IE 8]>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<![endif]-->

How it works…

For starters we are using xml to pull in the VML[5] implementation, which this example wraps around the whole body, so that roundrect can be used anywhere on the page. However, you need only wrap parts of the page that contain roundrect elements. The rounded rectangle (roundrect) VML element has a number of properties, including the arcsize and fillcolor used here. The arcsize controls the size of the arc on the corners and is unfortunately relative to the box size. The fillcolor controls the background color of the element and cannot be controlled via CSS in IE <9. This means that you need to duplicate the background-color defined in the CSS as the fillcolor attribute for older IEs. And you define border-radius in the CSS for modern browsers, but the arcsize attribute in VML for older IEs. This duplication is unfortunate, and it breaks the separation of design and layout rule, but is a necessary evil of this solution. We have defined some CSS informing modern browsers to render the unknown v:roundrect element as as block element with rounded corners. The later part of the CSS declaration tells IE to use the default VML behavior for rendering (as defined by microsoft). Modern browsers will treat the v:roundrect element as other elements, so you can apply additional attributes like id, class, and data- for further control. Out of the box, the VML solution works great in IE 6 and 7, but Microsoft changes the VML implementation in IE 8, so it breaks in standards mode. To work around this, we tell IE 8 to render as IE7 using the X-UA-Compatible meta tag. Most enterprise companies are already doing this, so they do not have to maintain different CSS for IE 7 and 8. In summary, the pros of this solution is that you hve rounded corners in IE 6-8 that render with the page like other elements and need no special scripts for activating. The drawback is you need to duplicate some design in the markup and render IE 8 as IE 7. Overall, I would recommend gracefully degraded to non-rounded corners in older IEs, as this is not a perfect solution, but if you must support rounded corners, consider putting the VML directly into your markup, instead of relying on a script.

References

  1. CSS3 Pie
  2. Cross Browser Border Radius Rounded Corners (HTC access)
  3. jQuery Rounded Corners
  4. Rounded Corners Experiment IE
  5. VML Proposal
Author: "--"
Send by mail Print  Save  Delicious 
Date: Saturday, 24 Aug 2013 00:43
In the last article, I introduced the Django HTML5 Boilerplate package, which incorporates HTML5 Boilerplate into an easy to use Django package. Today’s article will take that one step further by showing how to use DH5BP to create a base template for your HTML 5 mobile app. We will be using jQuery mobile and the jQuery Widget for Showing Add To Home Message on iOS.

Getting ready

Install Django HTML5 Boilerplate into your virtual environment:
pip install django-html5-boilerplate
Download the Add to Home Message JavaScript to your Django static files.

How do it…

All examples explained below are available as a gist. Create a mobile base file (iOSAndjQueryMobileBase.html) to extend within your application:
{% extends 'dh5bp/base_script_in_head.html' %}
{% load staticfiles %}
{% load url from future %}
{% block title %}{APP_TITLE}{% endblock %}
{% block head %}
    
    
 
    
    
    
    
    
    
    
{% endblock %}
{% block pre_main_script %}
    
{% endblock %}
{% block post_main_script %}
    
{% endblock %}
Create a new template to display a page (mobileSite.html):
{% extends 'iOSAndjQueryMobileBase.html' %}
{% load url from future %}
{% load staticfiles %}
 
{% block head %}
    
 
    {% put styles here %}
{% endblock %}
 
{% block content %}
    

Page Title

Page content goes here.

Page Footer

{% endblock %}
Remember to reference this template in one of your views. Lastly, create a js/main.js in your static files:
(function() {
  $(document).showAddToHome();

  $('#page1').on('pageinit', function() {
    // put your logic for handling page1 here
  });
}());

How it works…

The iOSAndjQueryMobileBase.html template (name it whatever you like) extends the special DH5BP template dh5bp/base_script_in_head.html, which I recently introduced for mobile applications. It is the same as dh5bp/base.html, except the script tags are loaded before body is rendered, instead of after. This is important for libraries like jQuery mobile that hijack the DOM and do a lot of manipulation as the page is being rendered. Mainly, the template adds a common page title, the apple meta properties for making your HTML 5 app look native, some icon links (you will need to create these), and references to the jQuery mobile CSS & JS. It does not introduce any new blocks. In your mobileSite.html template (name it whatever you like), we extend the iOSAndjQueryMobileBase.html template, implementing the head and content blocks. The head head block may not be necessary, if all your CSS is included in the parent template, but it illustrates how you could add page specific styles (or other stuff that belongs in head). The content block shows how to add markup, and contains an example of jQuery Mobile markup. Please read their documentation for more examples and information. By putting jQuery Mobile in the header, it will hijack the DOM and fire its events as the page renders. It is important to make sure that jQuery Mobile is loaded after your JavaScript file, or important events like pageinit won’t fire as expected. We put jQuery Mobile in the head to prevent the page from looking different before jQuery hijacks the DOM. The main.js file is where the logic for your mobile application goes. It first shows the Add to Home message, if necessary, before attaching all the jQuery Mobile page listeners. Inside the pageinit callback it is safe to reference and attach events to elements in that page using regular jQuery. In jQuery Mobile a page refers to an element with data-role="page", not the HTML document, so you can have many pages in one HTML document or pull other pages in using AJAX. You will definitely want to read the documentation on jQuery Mobile to learn how to mark it up and interact with it via JavaScript. It is really powerful, but somewhat confusing at first.

There’s more…

As I have several mobile project in production, rather than copy this pattern into each project, I have created a package that contains the iOSAndjQueryMobileBase.html for reuse on my own projects. Please include it in your own projects, if you find it useful:
pip install django-html5-mobile-boilerplate
The documentation to use it is available at Django HTML5 Mobile Boilerplate on Github.
Author: "--"
Send by mail Print  Save  Delicious 
Date: Friday, 16 Aug 2013 00:47
I am a big fan of the HTML 5 Boilerplate project, and in that past, I have made some half-hearted attempts to incorporate it into a reusable Django module. I think the problem with my attempts and the other attempts that I have found recently on the web is that nobody automated the process of converting H5BP into a django module, so each time H5BP is updated (which happens frequently), somebody has to manually update their module. This week, I finished a Django HTML 5 Boilerplate (DH5BP), which uses fabric to automatically download H5BP and create the files necessary to maintain the Django module. This way we get the benefit of a Django-friendly H5BP that can easily be updated to the latest version of H5BP. DH5BP is like any other Python module, and can be included easily into your Django project using Pip. It only requires that you have a version of Django >= 1.3 installed.

How do it…

To install django-html5-boilerplate:
pip install django-html5-boilerplate
Then include DH5BP in your `settings.py`:
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    'django.contrib.admindocs',
    ...
    'dh5bp',
    ...
)

H5BP Template

Any template you want to inherit the H5BP page architecture include the following:
{% extends 'dh5bp/base.html' %}
{% load url from future %}
{% block title %}YOUR TITLE HERE{% endblock %}
{% block content %}YOUR PAGE MARKUP HERE{% endblock %}
Additionally, you can define more styles, meta, and other head-related markup in the title block:
{% block head %}
    
    
    ...
{% endblock %}
The project expects you to create a /static/js/main.js file (see JavaScript notes below) for your primary script. To include JavaScript before or after main.js:
{% block pre_main_script %}
    
    
{% endblock %}

{% block post_main_script %}
    
{% endblock %}
If the enduser is viewing your site on a version of IE <= 7, then they will be shown a message indicating that they are using an outdated browser. To overwrite that message:
{% block outdated_message %}
    

YOUR MESSAGE

{% endblock %}
If you use Google Analytics (GA), then H5BP includes the script for it right into the page. You will need to provide the template variable `DH5BP_GA_CODE` with your GA code to activate the script. You will probably want to use a context_processor for this: Writing Your Own Context Processors

JavaScript

You will be provided the latest `jQuery`, `modernizr`, and a `console` polyfill from H5BP. In addition, the base template will look for a static file `js/main.js`. Put any JavaScript that is required for all pages of your site here. I have created two blocks (as described above), where you can put JavaScript that needs to be execute before and after the main script.

Urls & Views

The H5BP 404 page was ported over and wired up, as well as a similar looking 500 page. To use these in your project add the following to your `urls.py`:
handler404 = 'dh5bp.views.page_not_found'
handler500 = 'dh5bp.views.server_error'
I have wired up the default `favicon.ico`, `apple-touch-icon.png`, `humans.txt`, `robots.txt`, and `crossdomain.xml` from H5BP as well. To include those into your project, simply append the DH5BP urls to your urls:
from dh5bp.urls import urlpatterns as dh5bp_urls

urlpatterns = patterns('',
    # YOUR URLS
)
urlpatterns += dh5bp_urls
If you choose to change the behavior of these URLs, you can either not include these urls or declare your own version before adding the DH5BP urls (whichever definition occurs first will be the one used by Django).

How it works…

Include and consuming this module should be just like working with other Django-friendly modules. This project has simplified how you incorporate HTML5 Boilerplate into your Django projects and focuses only on solving that problem. Additionally, it includes a fabric script for keeping the package up-to-date with latest H5BP changes. At the very least, DH5BP will have a new release for every major release of H5BP. However, there is no reason to not update more frequently. The latest version of the documentation can always be found on the project homepage.
Author: "--"
Send by mail Print  Save  Delicious 
Date: Friday, 09 Aug 2013 18:36
I finally had a chance to play with PhantomCSS, a CSS regression testing tool that compares screenshots to see if CSS changes have affected the design, and wanted to share my experience with you. We are using it at Ariba to validate that I do not break any designs as I migrate us from two giant, unmanageable CSS files into smaller, modularize and better written lessCSS files. PhantomCSS uses CasperJS, built on PhantomJS as a testing framework with screenshot capabilities, and ResembleJS to compare images. It was surprisingly easy to get it to work when I used all the sub-components packaged with the download, but incredible difficult when I tried to use the sub-components I already had installed via npm.

Getting ready

The easiest way to get started is to clone the project and cd into it:
git clone https://github.com/Huddle/PhantomCSS.git
cd PhantomCSS
The project contains a version of CasperJS, resembleJS, and PhantomJS. However, the included PhantomJS only works on windows. For installation on other systems, check out the PhantomJS Installation Guide (version >=1.2 was required at the time of this writing). Except for PhantomJS, you should make sure you are using the included software versions (if you don’t change anything, then you should be using the included packages). I initially tried to use the CasperJS that I had previously installed from NPM and wasted a lot of time trying to get it PhantomCSS working with the latest version of CasperJS, when the included package works right away.

How do it…

To ensure everything is working run the test applications twice:
phantomjs demo/testsuite.js
You should see the following the first time:
Must be your first time?
Some screenshots have been generated in the directory ./screenshots
This is your 'baseline', check the images manually. If they're wrong, delete the images.
The next time you run these tests, new screenshots will be taken.  These screenshots will be compared to the original.
If they are different, PhantomCSS will report a failure.

THE END.
And this the second:
PhantomCSS found: 4 tests.
None of them failed. Which is good right?
If you want to make them fail, go change some CSS - weirdo.
The test application creates a simple nodeJS webserver and sends a couple of requests against it. The screenshots will be in the screenshots directory. If you want to see what happens when a regression is detected, change a style or visible text in demo/coffeemachine.html and rerun testsuite.js. Now, to get started with your own test. Create a new testing file:
touch demo/mytest.js
And put the following code in the file (trimmed from testsuite.js):
/*
	Initialise CasperJs
*/

phantom.casperPath = 'CasperJs';
phantom.injectJs(phantom.casperPath + '/bin/bootstrap.js');
phantom.injectJs('jquery.js');

var casper = require('casper').create({
	viewportSize: {
		width: 1027,
		height: 800
	}
});

/*
	Require and initialise PhantomCSS module
*/

var phantomcss = require('./phantomcss.js');

phantomcss.init({
	screenshotRoot: './screenshots',
	failedComparisonsRoot: './failures'
});

/*
	The test scenario
*/

var url = 'http://www.mattsnider.com'; // replace with your URL

casper.
	start(url).
	// screenshot the initial page load
	then(function() {
		phantomcss.screenshot('<SELECTOR_TO_SCREENSHOT>', '<LABEL_SCREENSHOT>');
	}).
	then(function() {
		// do something
	}).
	// second screenshot
	then(function() {
		phantomcss.screenshot('<SELECTOR_TO_SCREENSHOT>', '<LABEL_SCREENSHOT>');
	});

/*
	End tests and compare screenshots
*/

casper.
	then(function now_check_the_screenshots() {
		phantomcss.compareAll();
	}).
	run(function end_it() {
		console.log('\nTHE END.');
		phantom.exit(phantomcss.getExitStatus());
	});
Change the casper test as necessary and run it against your site:
phantomjs demo/mytest.js

How it works…

Most of the navigation and testing work is handled by CasperJS, so most likely any you want to do/test is documented here. That said, at the time of this writing PhantomCSS was still on Casper 1.0.2, while the documentation was for version 1.1.0 (I couldn’t find an active version of 1.0.2 documentation, if you find one, please let me know in the comments). The simple example we build (mytest.js) just opens a URL, takes a screenshot, does something that you specify, and takes another screenshot. From this starting point you should be able to begin building more comprehensive tests. The first time PhantomCSS runs it will perform all specified operations and take a series of screenshots (as specified by calls to phantomcss.screenshot('', '');), but the phantomcss.compareAll(); will print out a message saying that there is nothing to compare. You have just captured screenshots of the unchanged, baseline version of your site. Now go make changes to the CSS of your site and next time PhantomCSS runs, it will create new screenshots and compare them to the original. Should the screenshots be different, then PhantomCSS will error and tell you what steps failed. The boilerplate at the top of mytest.js is used to find and hook all the component libraries into PhantomJS, before we create a webpage using CasperJS. Next PhantomCSS is initialized, specifying the screenshot and failure directories. There are a lot of other configuration properties that may be specified, but these two are the most important for simple tests. CasperJS is invoked by calling .start(url). CasperJS uses the promise pattern, so you can chain function calls (a shown in the example above), or you can in call casper. individually (as shown by the end section).

There’s more…

Lastly, here are some pointers and gotchas with CasperJS that might help you:
  • Use this.echo("your string"); from inside of a callback function to print something to the terminal (or you may also use require("utils").dump("your string");), but console.log won’t print to the terminal.
  • Use this.echo(this.getHTML(selector, true)) when you aren’t sure that the correct element was found by the selector.
  • Inside the this.evaluate(callback) and this.thenEvaluate(callback) callback functions, you can run JavaScript against the page as you normally would (such as document.getElementById(id)), but you won’t have access to the CasperJS helper functions.
  • Attach listeners to CasperJS if you want to print the messages and alerts that are triggered by the HTML page you are evaluating (see code below).
function printMsg(msg) {
    casper.echo(msg);
}
casper.on("remote.alert", printMsg);
casper.on("remote.message", printMsg);
Author: "--"
Send by mail Print  Save  Delicious 
Date: Thursday, 25 Jul 2013 01:01
I recently wrote an article discussing Making HTML 5 Apps Appear Native on iOS where I mentioned building a widget for telling the users to add your application to the home screen. This article introduces a simple jQuery plugin that can be used to show the Add to Home message on an iOS device. It is fully customizable, but looks good right out of the box.

Getting ready

Download the plugin at the jQuery Plugin Site or the GitHub Project Homepage.

How do it…

Include the addToHome.js at the end of the </body> tag on your iOS native-looking HTML 5 app page:
	<script src="http://mattsnider.com//addToHome.js"></script>
</body>
Execute the function to render the message:
$(window).showAddToHome();
Options may be passed as an object to the showAddToHome function:
$(window).showAddToHome({
	triangleDiameter: 10
});
This will create the following markup:
	<div style="..."><p style="...">Add to Home</p></div>
	<div style="..."></div>
</body>

How it works…

The showAddToHome function uses jQuery to render a fixed positioned message with a disclosure triangle, pointing to the button on an iOS device where the end user can add your page to their homescreen. It will only show the message when window.navigator.standalone === false, so it won’t be seen by non-iOS browsers or if the end user launched your application from their home screen. The message is position fixed, so it will float at the bottom of the screen until it is removed from the page via a touch or click event, so it doesn’t get in the way of your UI. The markup created is two sibling divs, the first is the message box and the second is the disclosure triangle. Inside the message box will be a <p> tag containing the actual message. All styles are applied directly in JavaScript, so we do not need to include a separate CSS file. The styles can be overwritten by providing arrowStyles, elStyles, and pStyles to the options object passed into the showAddToHome function, but I don’t recommend it. If you use the standard styles, you can control the size of the arrow using the triangleDiameter option; it defaults to 20 pixels. The text can be controlled by overwriting the html option. However, the default HTML includes a <p> tag, so you should as well, unless overwriting the default styles.
Author: "--"
Send by mail Print  Save  Delicious 
Date: Friday, 12 Jul 2013 23:40
One of the designers at Ariba, recently came up with a design that needed a tri-state button to govern toggling some content. We came up with an interesting solution where the button has three colors on the outside, with the bottom color governing the content being shown. I am not sure if the widget will survive a usability study, but I put together a proof of concept using HTML 5 technologies and wanted to share it, because I think it is neat.

Getting ready

Here is an example of the widget in action. Click on a color to cause the outside to rotate, so the clicked color is on the bottom.
Check out this Pen!

How do it…

Start with two simple, nested elements:
Add some CSS to handle the display of the inner and outer circles:
.circle {
  display: block;
  background: black;
  border-radius: 50%;
  height: 300px;
  width: 300px;
  margin: 0px;
}

.circle-wrapper {

  border-radius: 50%;
  background: transparent url(http://jhsdigital.weebly.com/uploads/1/2/7/2/12727281/8752077_orig.jpg) -230px -230px;
  height: 300px;
  padding: 20px;
  transition-property: all;
  transition-duration: 350ms;
  transition-timing-function: ease-in-out;
  width: 300px;
}
Add some more CSS to handle rotating the outer circle to the other positions:
.rotate-120 {
  -webkit-transform: rotate(120deg);
  -moz-transform: rotate(120deg);
  -o-transform: rotate(120deg);
  -ms-transform: rotate(120deg);
}

.rotate-240 {
  -webkit-transform: rotate(240deg);
  -moz-transform: rotate(240deg);
  -o-transform: rotate(240deg);
  -ms-transform: rotate(240deg);
}
And a chunk of JavaScript to handle interaction with the outer circle:
var el = $('#test-circle'),
    oOffset = el.offset(),
    aColors = ['red', 'blue', 'yellow'];

el.click(function(e) {
  var elTarget = $(e.target);

  if (!elTarget.hasClass('circle')) {
    var iLeft = e.pageX - oOffset.left,
        iTop = e.pageY - oOffset.top,
        iOldRotation = parseInt(elTarget.data('rotation'), 10),
        iRotation;
    console.log(oOffset);

    if (259 > iTop && 173 > iLeft) {
      // left
      iRotation = 2;
    }
    else if (259 > iTop && 173 < iLeft) {
      // right
      iRotation = 1;
    }
    else {
      // bottom
      iRotation = 0;
    }

    iRotation += iOldRotation;
    iRotation %= 3;

    elTarget.removeClass('rotate-120');
    elTarget.removeClass('rotate-240');

    if (iRotation === 2) {
      elTarget.addClass('rotate-240');
    }
    else if (iRotation === 1) {
      elTarget.addClass('rotate-120');
    }

    elTarget.data('rotation', iRotation);
  }
});

How it works…

The goal of the widget is to move whatever color is clicked on to the bottom position. It currently doesn’t have event handlers, but they should be easy to add. The .circle class defines the dimensions and color of the inner circle, and uses border-radius to round the element into a circle. The .circle-wrapper class defines the dimensions of the outer circle, also uses border-radius to round the element, but uses a background image of a color wheel to divide the area into three colors. This means we will need to compute the clickable area for each color in the JavaScript, since there is no other indicator as to what part of the circle the user clicked on. Since the color wheel divides the circle into three even sections of 120 degrees, we need two rotation rules that transform the outer element by rotating it either 120 or 240 degrees. The .circle-wrapper class also defines a transition rule (easing-in-out animation over 350ms), so the rotation transform is animated when it is applied. The transition-property is set to target all rules, because the transformation rules use vendor prefixes. The JavaScript snippet then needs to assign a click handler to the outer div and determine what color was clicked on. We ignore any click that happens inside the inner button (or respond according to the needs of your application), and use mouse position, relative to precomputed values for the button position in the document, for determining which color zone was clicked. A data property on the outer element is used to keep track of the current state of the rotation, which is combined with the a numeric value associated with each click zone, then modulus three to determine which (if any) rotation should be applied. I don’t like that I had to grab the offset of the outer element when the script loads, and not on the click event. If the element position changes as the user interacts with the page, then this widget will break. Unfortunately, this was a necessary evil, because rotated elements return odd offsets relative to the rotation, not the absolute position on the page. A third wrapping, unrotated element will fix that, but this works for now. Anyway, this is not ready for prime time yet, and doesn’t work in legacy browsers, but introduces a new button concept. I have also experimented with four and five colors, and it works well. However, at five or more colors, the button looks too busy, and it becomes more difficult to tell what is selected. Please let me know what you think.
Author: "--"
Send by mail Print  Save  Delicious 
Next page
» You can also retrieve older items : Read
» © All content and copyrights belong to their respective authors.«
» © FeedShow - Online RSS Feeds Reader