Archive

Archive for April, 2010

Javascript: zero padding numbers

April 24, 2010 2 comments

There are many ways to accomplish this in js but the following is the one I found to be the best: Let’s say you need to pad a number with leading zeros so the total digits of the number will be 5, simply do a

String('00000'+n).slice(-5);

n is the number to be padded.

[ credit goes to http://gugod.org/2007/09/padding-zero-in-javascript.html ]

Advertisements

Write neater php code with variable substitution

April 14, 2010 1 comment

Whenever I see php codes like the following:
$html="<ul><li><a href=\"".$href."\" class=\"".$class."\">click</a></li></ul>";

I feel dizzy. With variable substitution, the above code can be easily written as
$html="<ul><li><a href='$href' class='$class'>click</a></li></ul>";

( Of course if you want to be strict about the resulting html code, you can also use function sprintf like the following:

$html=sprintf('<ul><li><a href="%s" class="%s">click</a></li></ul>', $href, $class);

)

Variable substitution also works with arrays, curl brackets are required to put around the array element, for example:

$a=array('food'=>'orange', 'name'=>'Somebody');
echo "{$a['name']} ate {$a['food']} today.";

Variable substitution also works great with heredoc:

$day="Monday";
$temp="72";
echo <<<EOD

Dear My Friend,
$day’s temperature is $temp. Let’s go out and have some fun!

Sincerely Yours,
rc

EOD;

Make good use of string formatting with python

April 8, 2010 Leave a comment

Sometimes it’s better to separate program from content (MVC web programming is a good example). With python’s string formatting feature, this can be done quite easily. I am going to borrow a party emailing example from “Unix Shells by Example” and simplify it a bit. Let’s say I am going to hold a party and I am going to email my friends asking each of them to bring something for the party. I start by writing the following python script (main.py) and the email template (content)

main.py:

#!/usr/bin/env python
        
def main():
        friends=[
                { 'name':'Leah', 'stuff':'some cookies' },
                { 'name':'Michael', 'stuff':'a lot of beers' },
                { 'name':'Rachael', 'stuff':'a red wine' }
        ]
                
        with open('content') as f:
                content=f.read()

        for friend in friends:
                print(content % friend)
        

if __name__=='__main__':
        main()

content:

Dear %(name)s,
We are going to have a party this Friday night at my place, please make sure to bring %(stuff)s.

Sincerely Yours,
Party Animal

Save both files and at command prompt, run

python main.py