Great Use For Javascript Closures

Posted on June 24th, 2009

setTimeout() with a paramter

If you need to use the setTimeout() function to call a javascript function that accepts a parameter you might be tempted to use syntax like

setTimeout('functionName()', 1500, param1, param2, etc); 

And you would probably have success until you went to test your site in Internet Explorer. Firefox seems to be able to handle the extra parameters on the end of the setTimeout() call but IE simply sends undefined variables to the function you are calling and your script dies.

Here is the solution – use closures! They are a little tricky to understand if you are new to the idea but, in a nutshell, you are assign a function to a variable. Normally you assign numbers, or strings to variables – well you can assign functions to variables too. Here’s how:

setTimeout(function() { delayedFunctionName(param1); }, 1500); 

This causes the function delayedFunctionName(p1) to be called with a 1.5 second delay AND the p1 parameter actually gets a value!

Then != Than

Posted on April 22nd, 2009

I can’t believe how many people seem to not know the difference between then and than. They are not the same word at all. For some reason people tend to forget about “than” altogether and only use “then” and it is extremely annoying. So FOR THE LOVE OF ALL THINGS DECENT please learn the difference between then and than. Then means next and than means instead of. Here are a few examples.

Proper Use of THEN

First I will shower, THEN I will get dressed.

I saw him fall THEN he cried like a baby.

Open up the system folder THEN click the remote login check box.

Proper Use of THAN

I’d rather eat grapes THAN grass.

Men are generally taller THAN women are.

Fried food is less healthy THAN raw vegetables.

Share Files Between Linux and Mac

Posted on April 21st, 2009

It is EXTREMELY easy to happily share files between your linux system and your mac. I use both Ubuntu and Mac OS X. Simply login into you mac desktop, open up your system settings and turn on Remote Login. This enables incoming SSH connections to your mac. If you want to connect while you are away from home, you can set up some sort of dynamic IP service like DynDNS.org. Open up port 22 on your home firewall or router and you can connect to your home mac from anywhere you go with an internet connection.

Once your mac has SSH enabled, log into your Ubuntu machine and click Places –> Connect To Server. Choose SSH as your Service Type. Enter in the IP address of your mac or whatever name you may have assigned to it in your /etc/hosts file or whatever. Use the username and password you use to log into mac and there you go. You can browse files on your mac with your Ubuntu machine in Nautilus.

WordPress Uploaded Images – How To Change Absolute URL

Posted on March 29th, 2009

When working with WordPress, you may develop a site on a development server with a different domain than the live server where you intend to deploy the site. When you upload images in a post or a page, WordPress assigns an absolute link as the source of the image. Here is a quick SQL query to run after you migrate your site to the live server so that the absolute URL is updated to reflect the changed domain name.

UPDATE wp_posts set post_content=REPLACE(post_content, 'www.devServer.com/', 'www.liveServer.com/');

UPDATED: PHP Snake Case To Camel Case

Posted on March 20th, 2009

For anyone interested in converting snake_case_strings into CamelCaseStrings, here’s a quick php snippet to do it:

/**
* Take a string_like_this and return a StringLikeThis
*
* @param string
* @return string
*/
function _snakeToCamel($val) {
return str_replace(' ', '', ucwords(str_replace('_', ' ', $val)));
}

Or if you prefer the inline thing…

$val = 'snake_case_string';
$val = str_replace(' ', '', ucwords(str_replace('_', ' ', $val)));
echo $val; // Output: SnakeCaseString

Update: Back To CamelCaseString

The popularity of this post has prompted the natural question on how to go from snake_case_string to the camel case version – SnakeCaseString. This gives me the opportunity to make use of a little known feature of php, the create_function function which allows you to make inline, anonymous, functions and use them as parameters. Take a look at this function to see it in use.

function _camelToSnake($val) {
return preg_replace_callback('/[A-Z]/',
create_function('$match', 'return "_" . strtolower($match[0]);'),
$val);
}

ANOTHER UPDATE: Some people want to get a stringLikeThis rather than a StringLikeThis – keeping the first letter lowercase. This is actually a little trickier to accomplish because there is no lcfirst() function like there is a ucfirst() function [NOTE: lcfirst() is coming in PHP 5.3]. So here is an updated function that returns your camelCaseValue starting with a lowercase letter.

function _snakeToCamel($val) {
$val = str_replace(' ', '', ucwords(str_replace('_', ' ', $val)));
$val = strtolower(substr($val,0,1)).substr($val,1);
return $val;
}

Vim: How To Fold Functions

Posted on March 20th, 2009

Vi Gang Sign

The is really a tip on how to fold any code block including functions. Navigate your cursor somewhere inside of the code block you want to fold, make sure you are in command/normal mode (press escape if you need to) then type zfa}

To save your folds between vim sessions you need to issue the command :mkview otherwise when you close vim your folds will be lost (your folds, not your code). To make life easier on you, you can have your folds automatically saved for you by adding this to your .vimrc file

au BufWinLeave * mkview
au BufWinEnter * silent loadview

Recursive searching in vim with grep – vimgrep

Posted on February 17th, 2009

Vi Gang Sign

One of the smartest people I’ve ever digitally met, Ryan Paul, taught me this awesome tip for doing a project wide search in vim. I needed to look for all occurrences of the patter _Models_ in a PHP project I was working on and you can do it right inside of vim – the best text editor ever invented.

  1. Open vim and make sure you are in the top level folder of your project by typing :pwd
  2. Then type :vimgrep YourPattern **/*.php
  3. To open your search results in their own buffer type :copen

The **/ recursively searches through all your directories for you pattern. :copen opens the search results in their own buffer. You can use the arrow keys to move up and down through the list and hit enter to have it open that result in the main buffer. You can also use :cnext and :cprev to move to the next and previous items in the list. Perhaps you might bind those to keyboard shortcuts so you can move through the search results quickly.

How To Delete URL Auto-fill In Safari – One At A Time

Posted on December 12th, 2008

I like using Safari and I’m a web developer. Sometimes I’ll be developing a website and then decide to rename a page. The problem is Safari will cache the old pages’ URL and then auto-fill the old URL as I’m typing. Then I hit enter and shucks, I’m getting a File Not Found error. In FireFox you can just press Shift-Delete to get rid of the outdated URL. In Safari, to delete one, several, or even all of your cached urls used by the auto-fill feature, just delete the offending URLs from your history.

To do this you can go to Bookmarks –> Show All Bookmarks. Then in the upper right corner of your window you can search for the URL you want to delete. I’m frequently typing the domain of our development server so I can delete all of the development URLs they may be outdated. Once you see the URLs you want to delete, highlight them and press Delete. This is a little more cumbersome than Firefox’s Shift-Delete but at least it can be done.

Note: Both History and Bookmarks are used for the auto-fill feature. So even if you delete all of your history, the URLs from your Bookmarks will still be used for auto-fill. Of course, if you have bookmarked a page that is no longer available you probably want to delete that too.

Multiple Gmail Signatures

Posted on December 10th, 2008

I Want Mulitple Gmail Signatures

I love using Gmail and I have several different email address for the various companies I work for. Gmail only lets me have one signature which is a bit of a problem because, depending on which from address I am using, I use different email signatures. There are a couple of Firefox add-ons that help with the problem but sometime I enjoy using other browsers like Safari. I have finally found the solution using QuickSilver and it’s Shelf feature.

QuickSilver And The Shelf

I’ve know about the Shelf on QuickSilver for a while now. It’s like a persistent clipboard. You can save snippets of text and then use that text later – like copying things to the clipboard but it stays there forever. So this was a good solution for my multiple email signature problem except that it took quite a few key stokes to get the text off the shelf and into my email. I set up triggers to do this but QuickSilver’s trigger display doesn’t handle the multi-line signature trigger very well. The name of the trigger spans multiple lines and overlaps the names of my other triggers. I hate that so I avoided using that as a solution. Also, it’s hard to think of enough unique keyboard shortcuts of each one of my five different signatures that don’t interfere with other shortcuts. So I created a trigger that just opened the shelf. Once the shelf is open I right-click the signature I want, then select paste from the actions menu. This was a fair solution, but the right-clicking and then hunting for paste in the pop-up actions menu was still a bit cumbersome.

Command Chains Can Be Stored On The Shelf

What I didn’t realize until today, was that you can store more than just text on the shelf. You can store chains of actions. So now my workflow is really nice. I have a keyboard shortcut that pulls up the Shelf then I just double-click on the signature I want and Blamo! my signature is in my email. Since this is a QuickSilver thing, I can use the signature for Mail.app, or Gmail and I can use any browser I want. It’s very nice. The one last tweak I wish I could figure out is how to get rich text in my signature because it seem that only plain text can be stored in QuickSilver’s shelf.

How To Store Command Chains On The Shelf

The huge realization I had today was that you can type Control-Enter rather than just Enter to make a chain of actions in QuickSilver. So I create the text (type . in the subject panel) for my email signature. Then tab to the action window and type paste the type Control-Enter and type Put on Shelf then click Execute. Now you can open your shelf, double-click your signature and it is pasted into whatever text area you were just in.

If anybody knows how to get rich text into the signature I would LOVE to know. I know that you can copy from Pages or Word or whatever and the bold, italics, links, etc come with you when you paste into Gmail. So I’ve thought about writing an AppleScript to open up a Pages document with my signature, copy the content to the clipboard, quitting Pages, then paste the clipboard. But the launching and quitting of pages takes too long and is more trouble than it’s worth.

Video Tutorial

Here is a quick video tutorial showing how to set all this up.

Recursively Delete A Non-Empty Directory With PHP5

Posted on November 26th, 2008

There are bunches of examples on how to delete non-empty directories in PHP but none of the examples that I’ve seen take advantage of PHP5’s RecursiveDirectoryIterator which makes this an almost trivial task. If you haven’t already, please check out the SPL Standard PHP Library Classes. I keep a class of static utility functions and here is my function to delete non-empty directories recursively.

public static function deleteDir($dir) {
    $iterator = new RecursiveDirectoryIterator($dir);
    foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
      if ($file->isDir()) {
         rmdir($file->getPathname());
      } else {
         unlink($file->getPathname());
      }
    }
    rmdir($dir);
}

Please note the RecursiveIteratorIterator::CHILD_FIRST parameter. Without that the listing will not be in the correct order. As you iterate along you will end up trying to delete directories before they are empty. This CHILD_FIRST parameter was added with PHP 5.1 so make sure you have at least that version installed before using this technique.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes