Author Archive

How to show a Percent Complete in Python

from __future__ import division
import sys

sys.stdout.write('%.2f%% complete' % (number / total * 100,))

How to fix ‘url’ requires a non-empty first argument. The syntax changed in Django 1.5

I really hate doing all this junk by hand, so I wrote a sed script to do it for me. Make sure you have a backup first, then run this in your templates directory:

find . -type f -print0 | xargs -0 sed -i 's/ url \([^" >][^ >]*\)/ url "\1"/g'

It’ll go through all of your template files and replace this:

{% url something.else foo bar %}

with this

{% url "something.else" foo bar %}

Be careful, I was a little lazy with this, it might get stuff you don’t want it to if you have a lot of writing in your templates. It’s still going to be easier looking for errors in a diff than doing it by hand, though.

Convert an 8 character string to a 64-bit integer

You can store an 8 character (10 byte) string as an integer in SQL Server. Note that any more than 8 characters will get truncated.

I mean, you probably shouldn’t ever do it, but it works. Here’s how:

Convert String to Int




Convert Int back to string




Convert String to Int – then back to a String again:


PSR-0 Final Proposal

Somehow the PSR-0 Final Proposal disappeared from I’m putting it here since no one seems to have been responsible enough to post it elsewhere.
The following describes the mandatory requirements that must be adhered to for autoloader interoperability.


  • A fully-qualified namespace and class must have the following structure \\(\)*
  • Each namespace must have a top-level namespace (“Vendor Name”).
  • Each namespace can have as many sub-namespaces as it wishes.
  • Each namespace separator is converted to a DIRECTORY_SEPARATOR when loading from the file system.
  • Each “_” character in the CLASS NAME is converted to a DIRECTORY_SEPARATOR. The “_” character has no special meaning in the namespace.
  • The fully-qualified namespace and class is suffixed with “.php” when loading from the file system.
  • Alphabetic characters in vendor names, namespaces, and class names may be of any combination of lower case and upper case.


\Doctrine\Common\IsolatedClassLoader => /path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php

\Symfony\Core\Request => /path/to/project/lib/vendor/Symfony/Core/Request.php

\Zend\Acl => /path/to/project/lib/vendor/Zend/Acl.php

\Zend\Mail\Message => /path/to/project/lib/vendor/Zend/Mail/Message.php

Underscores in namespaces and class names:

\namespace\package\Class_Name => /path/to/project/lib/vendor/namespace/package/Class/Name.php

\namespace\package_name\Class_Name => /path/to/project/lib/vendor/namespace/package_name/Class/Name.php
The standards we set here should be the lowest common denominator for painless autoloader interoperability. You can test that you are following these standards by utilizing this sample SplClassLoader implementation which is able to load PHP 5.3 classes.

Example Implementation

Below is an example function to simply demonstrate how the above proposed standards are autoloaded.

function autoload($className)
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strripos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

require $fileName;

SplClassLoader Implementation

The following gist is a sample SplClassLoader implementation that can load your classes if you follow the autoloader interoperability standards proposed above. It is the current recommended way to load PHP 5.3 classes that follow these standards.

Zend_Form_Element_Daterange with jQuery UI datepicker

It’s pretty easy to create a wrapper around Zend_Form_Element_Text to make a datepicker, but creating a good, smart daterange picker is a little more tricky.

The only two requirements are jQuery UI and that you have some way of injecting JavaScript into your site layout (I use a $this->layout()->headJavascript).

Other than that, this should be pretty plug-and-play.

Here are the 3x files you’ll need:
1. Your view script for the actual element (check in here for how I’m dealing with the JavaScript):

2. The actual element

3. And a filter to parse out the actual daterange when you do $form->getValues():

Have fun!


class M_Form_Element_Daterange extends Zend_Form_Element_Select {
public function init() {

$this->setDecorators(array(array('ViewScript', array(
'viewScript' => 'misc/form/element/daterange.phtml',
'viewModule' => 'default',
'class' => 'form element'

return parent::init();



class M_Filter_Daterange implements Zend_Filter_Interface {

private $_param = null;

public function __construct($param, $options = array()) {
if (!is_string($param) || strlen($param) < 1) {
throw new Zend_Filter_Exception("param must be a string, and must have a length");
$this->_param = $param;

* (non-PHPdoc)
* @see Zend_Filter_Interface::filter()
public function filter($val) {
if ($val != 'custom') {
$rangestring = self::stringToRange($val);
if ($rangestring) {
return $rangestring;
if ($this->_param === null) {
throw new Zend_Filter_Exception("Must instantiate this class and pass a valid parameter");
$range = Zend_Controller_Front::getInstance()->getRequest()->getParam($this->_param, false);
$start = strtotime(Zend_Controller_Front::getInstance()->getRequest()->getParam($this->_param . '_start', false));
$end = strtotime(Zend_Controller_Front::getInstance()->getRequest()->getParam($this->_param . '_end', false));

if (!$start || !$end) {
return false;
return array(
'start' => date('Y-m-d', $start),
'end' => date('Y-m-d', $end),


* Converts a known relative date range string to an array of dates, returns false on failure
* @param string $datestring
* @return array|bool
static public function stringToRange($datestring) {
switch ($datestring) {
case 'yesterday':
$daterange = array(
'start' => date('Y-m-d', strtotime('yesterday')),
'end' => date('Y-m-d'),
case 'weektodate':
$daterange = array(
'start' => date('Y-m-d', strtotime('sunday this week')),
'end' => date('Y-m-d'),
case 'lastweek':
$daterange = array(
'start' => date('Y-m-d', strtotime('sunday last week')),
'end' => date('Y-m-d', strtotime('saturday -2 weeks')),
case 'monthtodate':
$daterange = array(
'start' => date('Y-m-d', strtotime('first day of this month')),
'end' => date('Y-m-d'),
case 'lastmonth':
$daterange = array(
'start' => date('Y-m-d', strtotime('first day of last month')),
'end' => date('Y-m-d', strtotime('last day of last month')),
case 'yeartodate':
$daterange = array(
'start' => date('Y-m-d', strtotime('first day of this year')),
'end' => date('Y-m-d'),
case 'lastyear':
$daterange = array(
'start' => date('Y-m-d', strtotime('first day of last year')),
'end' => date('Y-m-d', strtotime('last day of last year')),
case 'all':
$daterange = array(
'start' => date('Y-m-d', strtotime('1970-01-01')),
'end' => date('Y-m-d'),
return false;

return $daterange;



* Output a daterange element

* @var Zend_Form_Element
$element = $this->element;
$opts = $element->getDecorator('ViewScript')->getOptions();

$(document).ready(function() {
var dates = $(<?=json_encode('#' . $element->getName() . '_start, #' . $element->getName() . '_end')?>).datepicker({
changeMonth : true
, onSelect : function( selectedDate ) {
// don't let end date be after start date
var option = == <?=json_encode($element->getName() . '_start')?> ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(
instance.settings.dateFormat || $.datepicker._defaults.dateFormat
, selectedDate
, instance.settings
dates.not(this).datepicker("option", option, date);


$(<?=json_encode('#' . $element->getName())?>).change(function() {
if ($(this).val() == 'custom') {
$(<?=json_encode('#_custom_daterange_' . $element->getName() . '_start')?>).show();
$(<?=json_encode('#_custom_daterange_' . $element->getName() . '_end')?>).show();
} else {
$(<?=json_encode('#_custom_daterange_' . $element->getName() . '_start')?>).hide();
$(<?=json_encode('#_custom_daterange_' . $element->getName() . '_end')?>).hide();
$this->layout()->headJavascript .= ob_get_clean();

<table id="_custom_daterange_<?=htmlentities($element->getName())?>">
echo $this->{$element->helper}(
<tr style="display:none" id="_custom_daterange_<?=htmlentities($element->getName())?>_start">
<td><label for="<?=htmlentities($element->getName())?>_start">Start: </label></td>
<td><input id="<?=htmlentities($element->getName())?>_start" name="<?=htmlentities($element->getName())?>_start" type="text"></td>
<tr style="display:none" id="_custom_daterange_<?=htmlentities($element->getName())?>_end">
<td><label for="<?=htmlentities($element->getName())?>_end">End: </label></td>
<td><input id="<?=htmlentities($element->getName())?>_end" name="<?=htmlentities($element->getName())?>_end" type="text"></td>
<div class="error bold"><?=$this->formErrors($element->getMessages())?></div>
<div class="hint"><?=$element->getDescription()?></div>

Unfollow everyone on formspring

I’ve been creating accounts on various social networking sites lately for a project we’re working on, and I somehow managed to bulk-follow over a thousand people on with their “find friends” tool. Like seriously, I was following hundreds of Asian teenagers — no idea how that happened.

No worries though, I just fired up jash and jquerify (a no-conflict version, since uses prototype, which jquery doesn’t always play nice with) to bulk unfollow all of them.

Once you get jquerify and jash up, just put this bad boy in jash, and you’re good to go:

$jq.each($jq(".unfollow"), function() {
	var str ='-');
Unfollow all on Formspring - screenshot

Unfollow all on Formspring

Be prepared to wait!!

Zend_Form_Element_Hidden not really hidden

The point of having a hidden field is that it is truly hidden, and doesn’t require labels / etc. Unfortunately, Zend_Form_Element_Hidden doesn’t really recognise this. Here’s how to subclass it and get rid of that stuff so you can create an input that is hidden for real:

class M_Form_Element_Hidden extends Zend_Form_Element_Hidden {
   public function init() {
      return parent::init();

Autoload PhpThumb with Zend Framework

Here’s an easy way to autoload PhpThumb (an excellent & fast image resizing / manipulating PHP library) using Zend Framework without having to modify the PhpThumb source at all. First we need to make our own custom autoloader:

class M_Loader_Autoloader_PhpThumb implements Zend_Loader_Autoloader_Interface {

   static protected $php_thumb_classes = array(
      'PhpThumb'        => '',
      'ThumbBase'       => '',
      'PhpThumbFactory' => '',
      'GdThumb'         => '',
      'GdReflectionLib' => 'thumb_plugins/',

   * Autoload a class
   * @param   string $class
   * @return  mixed
   *          False [if unable to load $class]
   *          get_class($class) [if $class is successfully loaded]
   public function autoload($class) {
      $file = APPLICATION_PATH . '/../library/PhpThumb/' . self::$php_thumb_classes[$class];
      if (is_file($file)) {
         return $class;
      return false;

Then simply put this in your Bootstrap:

Zend_Loader_Autoloader::getInstance()->pushAutoloader(new M_Loader_Autoloader_PhpThumb());

Done. Now you can use PhpThumb in your controllers like this:

class PhotoController extends Zend_Controller_Action {
   public function indexAction() {
      $thumb = PhpThumbFactory::create("/path/to/image.jpg");
      $thumb->adaptiveResize(250, 250);

Script to generate command to push MySQL database changes between enviornments

Got sick of manually doing database dumps between our production, test, and development environments, so I just wrote a very handy script using Zend Framework to generate a command to push changes between environments as you make them.

You will have to tweak ssh_to to suit your needs (our test and production dbs are not separated at the moment, so that removes a layer of complexity for us), but if you have everything setup in application.ini like most people do, this should work almost out of box. You’ll need to setup the autoloader on your own.

usage: php push_db.php --to=dev --from=prod


#!/usr/bin/env php5
require_once(getcwd() . '/autoload.php');

$opts = new Zend_Console_Getopt(
      'from=s'    => 'From environment, with required string parameter',
      'to=s'        => 'To environment, with required string parameter',

$from = $opts->getOption('from');
$to = $opts->getOption('to');

foreach (array('from','to') as $env) {
      if (!in_array($$env, array('production','prod','testing','test','development','dev'))) {
         die('Error: invalid parameter ' . $env . " = '{$$env}'" . PHP_EOL);

$prod_env = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'production');
$test_env = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'testing');
$dev_env = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'development');

$to_server = array();
$from_server = array();
foreach (array('from','to') as $serv) {
   $server = $serv . '_server';
   switch ($$serv) {
      case 'production':
      case 'prod':
         ${$server}['host'] =                   $prod_env->database->params->host;
         ${$server}['username'] =                   $prod_env->database->params->username;
         ${$server}['password'] =                   $prod_env->database->params->password;
         ${$server}['dbname'] =                   $prod_env->database->params->dbname;
         ${$server}['ssh_to'] = 'me@foobar';
      case 'testing':
      case 'test':
         ${$server}['host'] = $test_env->database->params->host;
         ${$server}['username'] =                   $test_env->database->params->username;
         ${$server}['password'] =                   $test_env->database->params->password;
         ${$server}['dbname'] =                   $test_env->database->params->dbname;
         ${$server}['ssh_to'] = 'me@foobar';
      case 'development':
      case 'dev':
         ${$server}['host'] = $dev_env->database->params->host;
         ${$server}['username'] =                   $dev_env->database->params->username;
         ${$server}['password'] =                   $dev_env->database->params->password;
         ${$server}['dbname'] =                   $dev_env->database->params->dbname;
         ${$server}['ssh_to'] = 'me@foobar';

print "Run this command on " . $from . ':' . PHP_EOL;
echo 'mysqldump -u ' . $from_server['username'] . ' -p' . $from_server['password'] . ' ' . $from_server['dbname']
. ' | ssh ' . $from_server['ssh_to'] . ' "mysql -u ' . $to_server['username'] . ' -p' . $to_server['password'] . ' ' . $to_server['dbname'] . '"' . PHP_EOL;


As small after-work project inspired by FitFinder (which, unfortunately, has since been taken down per the demands of the UCL), several months ago Montmere Limited launched spotadoink, the 21st century catalyst to flirting.

It was hastily thrown together in just a few short hours, but the concept is fun: when you see someone who is attractive, tell the world where!

Unfortunately it has not seen much use since its launch, but as with anything else, who knows what the future holds.