I’m Moved There!

Hey, finally I’ve moved my blog from wordpress.com free service to self-hosted wordpress.org blog. This is being hosted at Webfaction. I’m pretty much happy with the Webfaction service, we can host multiple websites and we can map multiple domains. Webfaction has one-click access to it’s services, it has smart and easy use user-interface and it’s pretty fast. Unlimited Websites, Unlimited Email addresses, Unlimited databases, Shell access, Backups and more. Old-style web hosting is dead!

I bought abhiomkar.in domain about 2 years back at Godaddy. And mapped it to Webfaction servers.

My new sub-domain for my blog: http://blog.abhiomkar.in

I will keep my new blog as active as possible. Please subscribe to my blog if you haven’t via Feedburner

See you there,
Abhinay Omkar
@abhiomkar

Posted in blog | Tagged , , , , , , , , ,

Javascript code challenge by Dropbox Team

I’ve found the below code challenge in the Dropbox’s Web Engineer Job post. Thanks to HN.
It was not that difficult, here is my solution to the first code challenge (Javascript) with complete explanation.

Question:
Given the following javascript code:

function countdown (num) {
        for (var i = 0; i <= num; i += 1) {
            setTimeout(function () {
                alert(num - i);
            }, i * 1000);
        }
    }

    countdown(5);

The desired result is a countdown from 5 to 0 using alert messages. Explain why the code only alerts -1, then fix the code so it works as expected.

Answer:
Let’s debug the code:
Debugging:

function countdown (num) {
    for (var i = 0; i <= num; i += 1) {
            setTimeout(function () {
                console.log("\nnum = " + num);
                console.log("\ni = " + i);
                alert(num - i);
                
            }, i * 1000);
        }
    }

countdown(5);

Output:
num = 5
i = 6
num = 5
i = 6
num = 5
i = 6
num = 5
i = 6
num = 5
i = 6


Hence, the code in question always alerts ‘-1′.

My fix for the above problem is:

function countdown (num) {
        for (var i = 0; i <= num; i += 1) {
            setTimeout(function () {
                if(i > num){
                    i = 0;
                }else{
                    i += 1;
                }
                alert(num - i);
                
            }, i * 1000);
        }
    }

countdown(5);

Explanation:
The alert box gives -1 every time (6 times), because the in-line function which has the alert() statement gets executed only after the loop is completed. By the time the loop is completely executed the value of ‘i’ will be 6. The program continues to execute and loop until the i<=num condition is satisfied. The in-line function which has alert() statement gets executed only after the specified time (i*1000) (that is, 0, 1000, 2000, 3000, 4000, 5000 in milliseconds) for six times with 1 sec delay for each alert box. So, The execution of loop gets'll be executed already before the first trigger of setTimeout().

So, the code is modified to reset the 'i' value to 0 when it is '6' and then keep increasing the 'i' value before alert() statement.

It was fun! :D

Note:
Note that, most of the browsers have a minimum delay set for setTimeout() call. Such as, 4ms to 10ms of minimum delay is set (depending on the browser) even though the timeout value (second parameter) is mentioned as ’0′ (zero). Check this out for more details – https://developer.mozilla.org/en/DOM/window.setTimeout

Posted in code, coding, debug, javascript | Tagged , , , , , , | 1 Comment

Advice from an Old Programmer

I was inspired by the write up in the book called  ‘Learn Python The Hard Way’, I didn’t read the whole book but, this page caught up my attention. It’s inspiring for programmers, so thought I would share with you all. Please drop me a comment if you do like it :)

(from the book ‘Learn Python The Hard Way’, CHAPTER TWENTY, PAGE 43)
by Zed A. Shaw:
You’ve finished this book and now you have decided to continue on with programming. Maybe it will be a career for you, or maybe you’ll just do it as a hobby. For whatever reason you’ll need some advice to make sure you continue on the right path and get the most enjoyment out of your newly chosen hobby.
I have been programming for a very long time. So long that it is incredibly boring to me. At the time that I wrote this book I knew about 20 programming languages and could learn new ones in about a day to a week depending on how weird they were. Eventually though this just became boring and couldn’t hold my interest.
What I discovered after this journey of learning was that the languages didn’t matter, it was what you did with them. Actually, I always knew that, but I’d get distracted by the languages and forget it periodically. Now I never forget it, and neither should you.
The programming language you learn and use does not matter. Do not get sucked into the religion surrounding programing languages as that will only blind you to their true purpose of being your tool for doing interesting things.
Programming as an intellectual activity is the only art form that allows you to create interactive art. You can create projects that other people can play with and you can talk to them indirectly. No other art form is quite this interactive. Movies go out to the audience. Paintings don’t move. Code goes both ways.
Programming as a profession is only moderately interesting. It can be a good job, but if you want to make about the same money and be happier you could actually just go run a fast food joint. You are much better off using code as your secret weapon in another profession.
People who can code in the world of technology companies are a dime a dozen and get no respect. People who can code in biology, medicine, government, sociology, physics, history, and mathematics are respected and can do amazing things to advance those disciplines.
Of course, all of this advice is pointless. If you liked learning to write software with this book then you should try to use it to improve your life anyway you can. You should go out and explore this weird wonderful new intellectual pursuit that barely anyone in the last 50 years has been able to explore. Might as well enjoy it while you can.
Finally, I will say that learning to create software changes you and makes you different. Not better or worse, just different. You may find that people treat you harshly because you can create software, maybe using words like “nerd”. Maybe you’ll find that because you can dissect their logic that they hate arguing with you. You may even find that simply knowing how a computer works makes you annoying and weird to them.
To this I only have one piece of advice: they can go to hell. The world needs more weird people who know how things work and who love to figure it all out. When they treat you like this, just remember that this is your journey, not theirs. Being different is not a crime, and people who tell you it is are just jealous that you’ve picked up a skill they never in their wildest dreams could acquire.
You can code. They cannot. That is pretty damn cool.
Posted in career, coding, programming, Uncategorized | Tagged , , , , , ,

Downloading Youtube Videos using Python (One-liner)

If you just want to get or look into the code, here it is -

gist: 398604 – GitHub

Explanation:

I’ll walk through the code to explain how it works.

We need urllib and urlparse python modules so we import them -

from urllib import urlopen, unquote; from urlparse import parse_qs, urlparse;

youtube_watchurl is a self explanatory, we store the Youtube Watch URL here -

youtube_watchurl="http://www.youtube.com/watch?v=NeSuirvA6UE&playnext_from=TL&videos=MS3Hq4oBj08"

We need the v parameter value from the above Youtube Watch URL (Example: v=NeSuirvA6UE )

urlparse(youtube_watchurl).query returns the query part of the above URL i.e., “v=NeSuirvA6UE&playnext_from=TL&videos=MS3Hq4oBj08″. We need the value of ‘v’ parameter from this query string. parse_qs() function returns parameter name and value in dictionary format. parse_qs(…)['v'][0] returns the value of ‘v’ parameter.

video_id = parse_qs(urlparse(youtube_watchurl).query)['v'][0];

The below GET request will retrieve all video response like video title, description, tag, view count, rating etc and most importantly it also includes token string.

Just try

curl "http://www.youtube.com/get_video_info?&video_id=NeSuirvA6UE"

to see the response from youtube. We need to parse the token string from the above response.
 

urlopen('http://www.youtube.com/get_video_info?&video_id=' + video_id).read().decode('utf-8')

Similarly, as we have retrieve ‘v’ parameter value we retrieve the ‘token’ parameter value using below piece of code.

parse_qs(unquote(urlopen('http://www.youtube.com/get_video_info?&video_id=' + video_id).read().decode('utf-8')))['token'][0])

example token value:

vjVQa1PpcFNWkxk6GpwXYrIxVZ-1iDcF_E9emDZ4UKA%3D

Now we have video id and token string, let’s put these value into the direct url to download the video. The format of the Direct URL:

http://www.youtube.com/get_video?video_id=video_id&t=token&fmt=18

Example Direct URL:

http://www.youtube.com/get_video?video_id=NeSuirvA6UE&t=vjVQa1PpcFNWkxk6GpwXYrIxVZ-1iDcF_E9emDZ4UKA%3D&fmt=18

The above URL redirected me to below URL

http://v12.lscache4.c.youtube.com/videoplayback?ip=0.0.0.0&sparams=id,expire,ip,ipbits,itag,algorithm,burst,factor,oc:U0dWSFZUVl9FSkNNNl9OTlpB&fexp=903801,903206&algorithm=throttle-factor&itag=18&ipbits=0&burst=40&sver=3&expire=1273698000&key=yt1&signature=5F8E3C3EABC00FE77AB5699811B13957CA95CFFD.14D37482C6E22D91D08770C6630EE3BE3BF9732D&factor=1.25&id=35e4ae8abbc0e941
The Direct URL may not work for more time after generating the token.

And that’s it we use the above direct link to download and write it to a file

open(video_id+'.mp4', 'wb').write(urlopen("http://www.youtube.com/get_video?video_id=%s&t=%s&fmt=18"%(video_id, parse_qs(unquote(urlopen('http://www.youtube.com/get_video_info?&video_id=' + video_id).read().decode('utf-8')))['token'][0])).read())

Here is the complete code:

gist: 398604 – GitHub

Inspired from Downloading YouTube Videos with a Perl One-Liner - http://www.catonmat.net/blog/downloading-youtube-videos-with-a-perl-one-liner/

and

Stackoverflow: http://stackoverflow.com/questions/2678051/cant-download-youtube-video/2679042#2679042   (Coded in Python 3)

Posted in Uncategorized | 1 Comment

Backup any Flickr Photostream with FlickrBird

I named it FlickrBird! It was a one night hack written in Python. I wrote it to Backup any Flickr Photostream.

As of now It doesn’t require any non-builtin python modules to run this script except flickrapi for python (Get it from here – http://stuvel.eu/projects/flickrapi). You just need a Python. You can suspend the download in-between & resume download later. I code it later for EXIF data.

Give a try and let me know your suggestions :)
Code is at Githubhttp://github.com/abhiomkar/FlickrBird

Run flickrbird.py

Screenshot running FlickrBird on Mac OS X - Flickr Backup Tool

How to use on Mac OS X / Linux?

Open Terminal and enter below commands

mkdir MyFlickrBackup
cd MyFlickrBackup
#Download FlickrBird Script
wget http://github.com/abhiomkar/FlickrBird/raw/master/flickrbird.py
#Give execute permissions to run it
chmod +x flickrbird.py
#Yah! run it...
./flickrbird.py
Posted in code, hacks, python | Tagged , , , , , | 8 Comments

MacPorts to Homebrew : New Packaging system for Mac OS X

EDIT: This blog and blog post is moved to blog.abhiomkar.in

I just wanted to post a blog on Homebrew because, I started loving it already. Homebrew is the new modern package management system for Mac OS X wich beats MacPorts. Yah! Homebrew is faster.

Homebrew is a Packaging system for Mac OS X 10.5 and above; heavy optimisations, no redundant packages and a bonus beer theme.

Here how you can install Homebrew on your Mac:

I prefer installing homebrew in /usr/local directory.

sudo curl -L http://github.com/mxcl/homebrew/tarball/master | sudo tar xz --strip 1 -C /usr/local

to avoid using sudo when installing packages, change the owner recursively on /usr/local directory

sudo chown -R `whoami` /usr/local

That’s it. Homebrew installed.

Now, Let’s install wget using homebrew

MacBook:~ abhinay$ brew install wget
==> Downloading http://ftp.gnu.org/gnu/wget/wget-1.12.tar.bz2
File already downloaded and cached to /Users/abhinay/Library/Caches/Homebrew
==> ./configure --disable-debug --prefix=/usr/local/Cellar/wget/1.12
==> make install
/usr/local/Cellar/wget/1.12: 9 files, 784K, built in 37 seconds

Really easy! isn’t it?

Have fun!

Note:
If you are facing problem because of MacPorts, try to uninstall it – Uninstall Instructions

and Do check out homebrew homepage on github: http://github.com/mxcl/homebrew

And one more thing, You should have xcode installed on your Mac – if already don’t have xcode, you can download from here – http://developer.apple.com/technology/xcode.html (Or you can install xcode from your second installation CD of Mac OS X)

Posted in Uncategorized | 14 Comments

2010: Wish You Happy New Year! (52000+ blog views)

I wish you all happy new year, have fun!

WoW! My blog crossed 50,000 Views. Thanks to all of you! Here is my new year greetings to you! :)

Happy New Year! :)

Posted in Uncategorized