How to layout a BackboneJS project in CakePHP using GruntJS
BackboneJS does not seem to come with a recommended layout for its file structure, though Yeoman suggests it’s own concept of laying out a BackboneJS project. I took inspiration from Yeoman to put together this approach for laying out a BackboneJS project inside the CakePHP framework. CakePHP is convention over configuration and expects you to put all your assets inside cakeroot/app/webroot/.
For the sake of this tutorial, I m going to create my files based on a simple ToDo project since almost every developer creates a ToDo app at least once! The ToDo list app for this project has a database with 3 tables:
users categories tasks
Inside webroot/js, create the following directories
vendor src collections models views
Yeoman generates directories for routes, helpers and templates. I m not going to add these coz I dont need them. For routes, I m going to use only one file and it can stay inside the js folder alongside my main.js file. I have a feeling that the convention to use main.js comes from ActionScript 3.0 projects (though I do not have any proof of this)
Once you ve created your directories in the js folder, its time to put in some files. Here is the same directory structure for the js/ directory, but includes files that are based on my database schema.
js/
main.js
application-router.js
vendor/
jquery.min.js
underscore.min.js
backbone.min.js
src/
collections/
application-collection.js
categories-collection.js
tasks-collection.js
models/
application-model.js
category-model.js
task-model.js
user-model.js
views/
application-view.js
categories-view.js
task-view.js
user-view.js
Yeoman creates the main.js with one global variable based on the name of your project and creates placeholders within that for our models, collections, views and routes. Here s a sample of it:
window.ProjectName = {
Models: {},
Collections: {},
Views: {},
Routers: {},
}
Now, while defining your models or collections or views, make sure to namespace it inside ProjectName.Models or ProjectName.Collections or ProjectName.Views. For example, our task-model would look like this:
ProjectName.Models.TaskModel = Backbone.Model.extend({
defaults: {}
});
Notice the name of the model. The file was named task-model.js and the model itself is called TaskModel. This is just a convention. You can change this to whatever you think is better for you.
Finally templates, Yeoman does create a structure for that but I figured that out the easy way that it has not yet implemented the feature where you can define .ejs files inside your templates directory and use em from there. At least not as of this post. So instead of trying to do that, we can just define the templates inside a directory inside app/View/Elements/Templates. We can then render that element in Cake’s view file which also has the scripts pulled in for our app. For this tutorial, I have a controller called UsersController.php and I have routed /app to UsersControllers:app
Router::connect('/app', array('controller' => 'users', 'action' => 'app'));
Since that s how the route is defined, we need to have a file at app/View/User/app.ctp. At the beginning of this render the templates file and at the end of the same file, pull in the required JS files.
For now I ll just pull all the required JS files from CakePHP’s perspective (later we’ll use Grunt):
//vendor
echo $this->Html->script('vendor/jquery-1.9.1.min');
echo $this->Html->script('vendor/underscore-min');
echo $this->Html->script('vendor/backbone-min');
//src
echo $this->Html->script('src/main');
echo $this->Html->script('src/application-router');
//collections
echo $this->Html->script('src/collections/application-collection');
echo $this->Html->script('src/collections/categories-collection');
echo $this->Html->script('src/collections/tasks-collection');
//models
echo $this->Html->script('src/models/application-model');
echo $this->Html->script('src/models/user-model');
echo $this->Html->script('src/models/category-model');
echo $this->Html->script('src/models/task-model');
//views
echo $this->Html->script('src/views/application-view');
echo $this->Html->script('src/views/user-view');
echo $this->Html->script('src/views/category-view');
echo $this->Html->script('src/views/task-view');
Lets say your application-router.js file looks like this:
ProjectName.Routers.ApplicationRouter = Backbone.Router.extend({
routes: {
"": "firstrun",
},
firstrun: function() {
console.log("router - firstrun");
}
});
Then at the end of all the javascript calls, create script tag and create a router object and kick start the show!
(function(){
var router = new ProjectName.Routers.ApplicationRouter();
Backbone.history.start();
})();
We could even use GruntJS and have all the JavaScript and CSS files uglified or minified into one single app.js and app.css file and just pull that instead. To do so you ll need NodeJS and Node Package Manager installed. If you do have these installed, then create a file called package.json inside cakeroot/app/. I m not using the webroot directory coz I dont want my Gruntfile and package.json file to be publicly accessible. Inside your package.json file you could do something like this:
{
"name": "ProjectName",
"title": "ProjectName",
"version": "2.0.0",
"devDependencies": {
"grunt-contrib-uglify": "~0.1.1",
"grunt-contrib-watch": "~0.2.0",
"grunt": "~0.4.1",
"grunt-contrib-cssmin": "~0.6.0"
}
}
Then, add n navigate to your app folder in a terminal and run:
npm install
Once the required modules are installed, you can add app/node_modules to your .gitignore file. Then create a file (inside app/) called Gruntfile.js (unless it is not already created) and enter something like this:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! */'
},
dist: {
src: [
'webroot/js/src/main.js',
'webroot/js/src/router.js',
'webroot/js/src/collections/*',
'webroot/js/src/models/*',
'webroot/js/src/views/*',
],
dest: 'webroot/js/app.js'
},
},
cssmin: {
compress: {
options: {
banner: '/* */'
},
files: {
'webroot/css/app.css': ['webroot/css/reset.css', 'webroot/css/style.css']
}
},
},
watch: {
scripts: {
files: [
'webroot/js/src/main.js',
'webroot/js/src/router.js',
'webroot/js/src/collections/*',
'webroot/js/src/models/*',
'webroot/js/src/views/*',
'webroot/css/*'
],
tasks: ['uglify', 'cssmin'],
options: {
nospawn: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-watch');
//register default task
grunt.registerTask('default', 'watch');
}
I m just using uglify and cssmin along with watch. You can add whatever else you may need. After that you wont need to pull all those JS files in your view file. As you may already know, the browser pulls 2 files at a time from the server. So if you have 16 files (including Javascript as well as CSS), then it ll make 8 trips to the server and back!
Now that we have some grunt tasks running, we can reduce the round trips to the server (and cut file size considerably). Run ‘grunt’ from the ‘app/’ directory in a terminal and marvel at the ‘magic’ from the contributors of Grunt as you make even the tiniest of the changes to the files that are being ‘watched’. These views are just my idea based on how Yeoman lays out a Backbone JS project. If you have some suggestions to improve this, then please do share.
Install Apache, MySQL PHP and phpMyAdmin on Ubuntu 13.04 Raring Ringtail
When Thomas Edison worked late into the night on the electric light, he had to do it by a gas LAMP or candle. I’m sure it made the work seem that much more urgent.
-George Carlin
Ubuntu 13.04 ‘Raring Ringtail’ released yesterday and though I use Crunchbang, like any ex Ubuntu fanboy I got myself the iso, put it on a thumbdrive and installed it on a small netbook I have that was just lying around doing nothing fancy. I thought I d install the new Ubuntu on it and use it to ‘code’ while in the John or while standing in the line at Starbucks
So anyway, I had to setup a LAMP server:
sudo apt-get update sudo apt-get upgrade
MySQL
sudo apt-get install mysql-server mysql-client
Apache
sudo apt-get install apache2
PHP
sudo apt-get install php5 libapache2-mod-php5 php5-mysql
Restart Apache
/etc/init.d/apache2 restart
phpMyAdmin
sudo apt-get install phpmyadmin
I don’t like to use Apache’s default http folder /var/www so I need to update the apache2.conf file:
sudo nano /etc/apache2/apache2.conf
Changing the default location will require me to make sure phpMyAdmin continues to load on http://localhost/phpMyAdmin so at the end of the same file I ll add the virtual host configuration for phpMyAdmin
Include /etc/phpmyadmin/apache.conf
Restart Apache
/etc/init.d/apache2 restart
Rearrange characters of a string to create all possible combinations
Governments tend not to solve problems, only rearrange them
-Ronald Reagan
How to take a word(string) and rearrange its letters to create all possible combinations? Lets say we want to use the word ‘goal’ and list out all possible words that can be made by rearranging the letters of the word ‘goal’. Take the first letter ‘g‘ and then create permutations and combinations of the balance letters ‘oal‘ and append them to ‘g‘.
| g | oal ola alo aol loa lao |
Then take go and create create permutations for the balance letters ’al‘ and append them to ‘go‘.
| go | al la |
Then we take goa and l
| goa | l |
This is done for each of the letters. As you can see, with each letter, the permutations will reduce for the subsequent letters. The parameters that are passed to our recursive function are a string that will be used to prepend (starting with an empty string) AND the array of the letters of the word that will be looped over to rearrange its words.
At the moment the JavaScript function I ve written tends to have too many iterations to produce the desired result but it works alright. Here’s a demo for this. I ve added 2 helper functions to this function. One to find if an item exists in a given array and another to remove an item from an array by index. I m not using the Array.splice function to remove item by index coz it to alters the array that was passed to it.
Here’s the function in JavaScript:
Here’s the same thing in python:
Create a right click menu for your web application
Taken out of context I must seem so strange.
-Ani DiFranco
Update: I ve converted this into a jquery plugin. You can download/fork it from my gitbhub page.
There is a common issue when crafting out non-trivial web applications, where you may have many different actions for the user to perform and yet you certainly do not want to overwhelm her with a complex UI with icons, menus, floating divs with action buttons in them etc. A simpler way to reduce the UI clutter could be to introduce a contextual menu on right-clicking an element. This is really simple using jQuery. Here s a DEMO for the following snippet. And here’s the demo for the same thing as a jquery plugin.
You could design a UL element the way you want and set
ul#context-menu {
postion: absolute;
display: none;
/*sample style attributes follow*/
width: 100px;
background: #333;
color: #fff;
font-size: 12px;
}
ul#context-menu li {
margin: 3px;
padding: 3px;
background: #000;
}
Assuming that we want this context menu to appear on right clicking an image, the sample HTML could be:
<img src='' /> <ul id='context-menu'> <li>Edit</li> <li>Delete></li> <li>Export</li> </ul>
Now we simply bind the ‘contextmenu’ event of images to show this context menu.
$('img').bind('contextmenu', function(e){
$('#context-menu').css('left', e.pageX + 'px');
$('#context-menu').css('top', e.pageY + 'px');
$('#context-menu').show();
e.preventDefault();
return false;
});
Basically, we got the X and Y position of the current mouse position and applied it to the context-menu UL element (which has position set to absolute) and prevented the default action from happening. Finally, we need to get rid of this context menu if the user clicks anywhere but the context menu.
$('html').click(function(e){
$('#context-menu').hide();
});
We don’t want the menu to hide if the user clicked the menu itself, so we disable the default behavior of the element from propagating the click event way up to the HTML element:
$('#context-menu').click(function(e){
e.stopPropagation();
});
Since we set position: absolute on the context menu, resizing the browser when its open will mess it s position. The probability of the user right clicking the image and then resizing the browser window is low, but just in case she does so, then we can simply hide the menu on resize as well:
$(window).resize(function() {
$('#context-menu').hide();
});
So that s about it. Here’s a DEMO for this code. If you d like to see a demo of this same thing used as a jQuery plugin, then here’s the link for that and finally, here s my github page for it.
Solution for VideoJS not playing some videos in Firefox

This seems to be a common issue while using VideoJS where it will not play some videos in Firefox. Apparently some encodings of H264 are incompatible with the Firefox browser in which case you need to specify an alternative video format -> OGG. But then if you do not have the alternative format and you dont mind a dirty but quick hack, then you can just force VideoJS to use the Flash player instead of HTML5 video if the browser is Firefox. You ll need to host video.js from your own server as opposed to using their CDN for it. Then inside the video.js file ‘Find’ the term ‘techOrder’. It s the first attribute in the VideoJS.options object and looks something like this:
VideoJS.options={techOrder:["html5","flash"],
Declare an array to hold the default array and rearrange its value if the browser is Firefox:
var techOrderArr = ["html5","flash"];
if (navigator.userAgent.indexOf("Firefox")!=-1) techOrderArr = ["flash","html5"];
Then change that earlier code to
VideoJS.options={techOrder:techOrderArr,
Now VideoJS will use Flash in case its Firefox and play those videos that were not playing with the HTML5 video player
Here s a version of videojs where I ve done the required change.
How to create resize handles for jqueryui’s resizable feature
Size matters not. Look at me. Judge me by my size, do you? Hmm? Hmm. And well you should not. For my ally is the Force, and a powerful ally it is. -Yoda
Create a 10px x 10px red square and save it as gif and call it resize-handle.gif and store it in your images folder. Then use jqueryui to assign resizable() on an element that you wish to resize. In the css file that came in with jqueryui (jquery-ui-1.8.13.custom.css in my case), around line #311, substitute the style declaration for the resizable ui with this
.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; }
.ui-resizable-n { cursor: n-resize; height: 10px; width: 100%; top: 0px; left: 0; background: url(images/resize-handle.gif) top center no-repeat; border-top: 1px solid #f00;}
.ui-resizable-s { cursor: s-resize; height: 10px; width: 100%; bottom: 0px; left: 0; background: url(images/resize-handle.gif) bottom center no-repeat; border-bottom: 1px solid #f00; }
.ui-resizable-e { cursor: e-resize; width:10px; right: 0px; top: 0; height: 100%; background: url(images/resize-handle.gif) right center no-repeat; border-right: 1px solid #f00; }
.ui-resizable-w { cursor: w-resize; width: 10px; left: 1px; top: 0; height: 100%; background: url(images/resize-handle.gif) left center no-repeat; border-left: 1px solid #f00; }
.ui-resizable-se { cursor: se-resize; width: 10px; height: 10px; right: 0px; bottom: 0px; background: #f00; }
.ui-resizable-sw { cursor: sw-resize; width: 10px; height: 10px; left: 0px; bottom: 0px; background: #f00; }
.ui-resizable-nw { cursor: nw-resize; width: 10px; height: 10px; left: 0px; top: 0px; background: #f00;}
.ui-resizable-ne { cursor: ne-resize; width: 10px; height: 10px; right: 0px; top: 0px; background: #f00;}
That’s it.
Regex Find and Replace in Komodo Edit
If you don’t like something change it; if you can’t change it, change the way you think about it. -Mary Engelbreit

This applies to my most commonly used IDE: Komodo.
Lets assume that I want to find and replace (using the regex option in Komodo’s Find and Replace feature) in the following text:
1343217942.jpg
1343217932.jpg
1343217963.jpg
1343218095.jpg
I want to append a _tn to these sample file names. So ’1343217942.jpg’ should turn into ’1343217942_tn.jpg’. To do this I need to use parentheses to make a capturing group out of the part which needs to be retained (the digits part) and then back-reference that group to re-use in the replace. \d will get us digits and surrounding it in (braces) will set it as a capturing group that we can use again. The asterisk * will act as our quantifier so that we can get all the digits.
Find what: (\d*)\.jpg
Replace with: \1_tn.jpg
From this example \1 will back-reference the first capturing group(in the first set of parentheses) that we want to target and retain. If we want to target another capturing group to back-reference, then we’d need to define that in another set of parentheses. Lets change the above text to include some gif files too
1343217942.jpg
1343217932.gif
1343217963.gif
1343218095.jpg
Find what: (\d*)\.(jpg|gif)
Replace with: \1_tn.\2
This should rename all the file names as desired. \2 will back-reference the second capturing group (defined in the second set of parentheses) A cool thing about doing this in Komodo Edit is, you can perform a regex find and replace in a selected chunk of text as well.
wGet it all
The first step to getting the things you want out of life is this: Decide what you want.
- Ben Stein

For a music related project I m working on, I needed sound files for a chromatic scale. I found a site that had the files I needed but they weren’t listed anywhere with their links. They were mp3 links to play buttons at various places in the site. I found that the format of the file names was B3, Bs3, C3, Cs3 etc… the ‘s’ meant ‘sharp’ and the number was the octave. I needed sound files from the third octave so here s what I did and downloaded the one’s I need without individually right clicking on each of the play buttons and selecting to download the link to a specific location on my computer.
I created a file called ‘download-script’ (without any extension) to write a shell script for this and defined a variable for the URL and a space separated list for the file names :
url="http://www.domain-name.com/files/some-prefix.net_"
files="B3 Bs3 C3 Cs3 D3 Ds3 E3 F3 Fs3 G3 Gs3 A3 As3 B3"
for f in $files
do
wget -O $f.mp3 $url$f.mp3
done
wget is a command line utility to download files from a FTP or a HTTP server. In the loop I m using -O (output document option) so that the downloaded file would have the name in the format I need (e.g. C3.mp3) and not in the naming format on the website (some-prefix.net_C3.mp3). Then I made the file executable
chmod a+x download-script
And simply called it from the terminal
./download-script
Voila! All files downloaded
Javascript/jQuery implementation of Game of Life
To win you’ve got to stay in the game.
-Claude M. Bristol

Recently I watched a video on Coursera on Model Thinking where the instructor, Scott E Page explained the Game of Life (a zero player game) divised by mathematician John Horton Conway. The game is basically a grid of cels and each cel has a ‘on’ and a ‘off’ state or in other words, an ‘alive’ or ‘dead’ state. It has simple rules that can create complex patterns over time. If a cel is alive, then it can continue to ‘live’ only if it has exactly 2 or 3 neighboring cels alive, else it dies or goes ‘off’. A dead cel can come alive only if it has exactly 3 neighboring cels alive. Over time, this creates intricate patterns and even animations!
I decided to implement this in Javascript/jQuery for fun. This hardly took an hour and it happens to be my second project on Github. Though I need to implement some more customizations, its here for you to look at and here if you d like to fork it and make better
Manage your custom WordPress theme using git instead of FTP

Creating a WordPress theme is really fun, so is maintaining it using Git! If you ve been using FTP to push all your cool updates to your theme, then you may want to consider using version control instead. Git for instance. Earlier there really wasnt any online service that would let you host unlimited private repositories for free. Springloops (which is undoubtedly awesome!) gave out only 100MB for free. But with BitBucket the whole scenario changes. Of course, there is Github, but you may not want to make your WordPress theme public. At least not right away!
Pre-requisites:
- Git
- A BitBucket account (free)
- A Virtual Private Server (I use Linode. If you dont have a VPS yet, then I highly recommend Linode and I d be delighted if you use this link as this has my referral code in it)
Log in to your BitBucket account and create a Git repository. Leave the ‘private’ checkbox selected. Once its created, use the link it will provide to clone the newly created repository. In a terminal, change directory to the wp-contents/theme folder in your WordPress installation and paste the git command which may look something like
git clone https://yourname@bitbucket.org/yourname/my-wp-theme.git
Enter the password and you are set to create your WordPress theme. Once you make some additions or changes to this theme folder, commit the changes and push them to BitBucket.
git add .
git commit -a -m "some message to identify this commit"
The first time you push, you may run into an error due to the size of files being pushed. In that case set the http post buffer to a little higher number
git config http.postBuffer 524288000
Once you are ready to take your new WordPress theme live, login to your VPS and in your wp-content/themes folder clone the repository from BitBucket just the way you did when you cloned it on your local machine. Whenever you make changes to your theme, push them to BitBucket and then pull them inside your theme folder on your VPS by issuing the git command
git pull

