python singleton

A version of python singleton pattern, it is not very pretty and breaks a bunch of pep 20, but in some cases is useful.

Singleton Pattern

class Singleton(object):
    __instance = {}
    def __new__(cls, *args, **kwargs):
        if cls.__name__ not in cls.__instance:
            cls.__instance[cls.__name__] = super(cls.__class__, cls).__new__(cls, *args, **kwargs)
            setattr(cls.__instance[cls.__name__], '__init', True)
            setattr(cls.__instance[cls.__name__], '__init', False)
        return cls.__instance[cls.__name__]
    def __init__(self, *args, **kwargs):
        if getattr(self, '__init', False):
            # do initialization here

Alternatively consider the Borg Pattern below.

Borg Pattern

class Borg(object):
    __state = {}
    def __init__(self):
        self.__dict__ = self.__state
        if 'my_data' not in self.__dict__:
            # do initialization here, i.e.:
            self.my_data = 'initialize your data'


listening to posix style signals

A quick self reminder.

#include <stdio.h>
#include <string.h>
#include <signal.h>
void handler(int signal)
    printf("Signal: %s\n", strsignal(signal));
    if (signal == SIGABRT)
	raise(SIGKILL); // can't be caught or ignored
int main(int argc, char *argv[])
    signal(SIGABRT, handler); // Abort
    signal(SIGFPE, handler);  // Floating-Point Exception
    signal(SIGILL, handler);  // Illegal Instruction
    signal(SIGINT, handler);  // Interrupt
    signal(SIGSEGV, handler); // Segmentation Violation
    signal(SIGTERM, handler); // Terminate
    signal(SIGQUIT, handler); // Terminal quit
    printf("Hello Crazy World!\n");
    raise(SIGABRT); // raise Abort
    printf("I am never going to be printed...\n");
    return 0;


git memo

Git, in my opinion, is undoubtedly the best version control system, mostly, but not only, for its distributed nature, and the way branching and merging are handled.

However having used subversion for many years I find git learning curve a real pain, some of the commands are slightly arcane, therefore not easy to remember.

In this post I will try to keep a git memo of commands that I occasionally need and regularly forget:

create new repo with first commit and push

assuming new repo is called hayate

  • add hayate to gitosis config file (gitosis.conf)
    more on gitosis in this excellent tutorial:

    [group hayate]
    writable = hayate
    members = andrea@myhost

    then git add --all, git commit -a -m 'added hayate repo', git push
  • go in the hayate directory i.e. cd /var/www/hayate and type git init
  • git remote add origin
  • add and/or update files and directories
  • git add --all
  • git commit -a -m 'First hayate commit'
  • then for the first push: git push origin master:refs/heads/master which creates the master branch


  • git tag v1.0 -m 'my first tag'
  • git push --tags commits the tag
  • git tag -l list all tags

clone into current directory

  • git clone . <- note the dot (hayate directory will not be created)

change working branch

  • git branch -l lists local branches
  • git checkout <branch-name> switches working branch to “branch-name”

remove an added file or directory (before it is committed)

  • git reset <file-or-directory-name>

add submodule (an external repository) within local source tree

  • git submodule add <repo-url> <local-path>
    i.e. git submodule add hayate

checkout a submodule

  • git submodule update --init

create a new remote branch tracking it locally

  • git checkout -b <branch_name>
  • git push -u origin <branch_name>
  • git checkout <branch_name> to switch to the new branch

start tracking a remote branch

  • git checkout --track -b <local name> origin/<remote name>

delete a remote branch

  • git push origin --delete <branch_name>

delete local branch

  • git branch -D <branch_name>

revert a merge

  • git revert -m 1 merge_hash

to suppress the following warning

warning: You did not specify any refspecs to push, and the current remote
warning: has not configured any push refspecs. The default action in this
warning: case is to push all matching refspecs, that is, all branches
warning: that exist both locally and remotely will be updated. This may
warning: not necessarily be what you want to happen.
warning: You can specify what action you want to take in this case, and
warning: avoid seeing this message again, by configuring ‘push.default’ to:
warning: ‘nothing’ : Do not push anything
warning: ‘matching’ : Push all matching branches (default)
warning: ‘tracking’ : Push the current branch to whatever it is tracking
warning: ‘current’ : Push the current branch

  • git config [--global] push.default current (–global is optional)


TIC – Text Image Converter

This is a php5 library (two classes) I wrote to convert TrueType Font text into an image, using the GD library.
The project is hosted and can be downloaded from github: (it includes an example, documentation and some free fonts)
or using git: git clone git://
Documentation is also available online here:

To extend the library to add support for other Font types just extend the TIC abstract class and implement the create and dimension methods.

See example below on how to use it:

 * @file image.php
require_once 'lib/tic.php';
    ->setText('Hello World !')
    ->setBgColor(0x00, 0xff, 0xff)
    ->setFontColor(0x00, 0x00, 0x00)

Than in your html:

<img src="image.php" alt="TIC" />

That will output the following image:


The library is under the LGPL license, which means you can freely use it for commercial and non commercial applications, please post a comment for feedbacks, bugs, or links of projects where you have use it.

Zend_Layout example

Table of contents for Zend Framework

  1. Zend Framework and Smarty integration
  2. A better Zend Framework & Smarty integration
  3. Zend_Layout example

This example focuses on 3 aspects of the Zend Framework (v1.6):
the Zend_Layout mechanism, modules and helpers, including the ActionStack helper and a custom helper. (Please note that there is no Smarty involved in this example).

The main objective of this post is to demonstrate how components of ZF work together to produce a simple application, for this reason I will focus on the code that holds things together rather than going through line by line.

If you have any questions or things are not clear please leave a comment.

As in the previous posts in the series you can download the full working example here: (3.36 MB). (Note: the compressed file includes the ZF library hence about 3MB)
Please glance at the previous post on this series for hints on how to set up this example on your working server.

Lets start where all begins: bootstrap.php … 

Scrolling Text: the JavaScript Way

I am developing a site and on one of the pages I added an updateable (from a custom CMS) scrolling text banner.
The client was really impressed and asked me to make one on the front page as well.

I thought of sharing this because although to make a scrolling text banner in javascript is quite easy is still producing a good effect (when not overused) specially when the text can be updated at will from a CMS.

Here is the code that does most of the work:

 * @param elem Element (div) containing the text to scroll
function scrollText(elem)
    if (elem) {
        var str = elem.innerHTML;
        // get the first character of the string
        var firstChar = str.substr(0,1);
        // get the whole text except the first character
        var sub = elem.innerHTML.substr(1);
        // attach the first character at the end of the string and replace the element content
        elem.innerHTML = sub.concat(firstChar);

The above function is called at regular intervals using the following line of code:

setInterval('scrollText(document.getElementById("text-to-scroll"))', 333);

Unzip the following file: (999 bytes) to see the complete example.

A better Zend Framework & Smarty integration

Table of contents for Zend Framework

  1. Zend Framework and Smarty integration
  2. A better Zend Framework & Smarty integration
  3. Zend_Layout example

Since the first post on this series I have been working with the Zend Framework and Smarty extensively and I have greatly improved my previous integration between Smarty template engine and ZF.

I have prepared and example that you can download from the following link: (3.5 MB) the compressed file includes the ZF and Smarty packages.
The zip file should unpack as follow: … 

Linux pipe find with rm

find /path/to/dir -name name_of_file_to_match | xargs /bin/rm

I use often the above command to clean a directory from all the back up files created by emacs, so for example if I am developing a site at: /var/www/a-site/ then at the end of the day or at the beginning of a new one I clean up the directory as follow:
find /var/www/a-site -name '*~' | xargs rm
Be careful with the above command, specially if you run it as root and you get wrong the regex you could delete things you didn’t mean to !