Desi Founder @ Work

25 Oct, 2009

Startupping Hajj

Posted by: sharjeel In: Uncategorized

For a Startup Founder getting psyched up for Hajj is simple: There are gonna be extremely hard times, you'll have to do a lot of things yourself, you should stay patient, be calm, don't complain, be very resourceful during the hard times and expect a lifetime reward if you do it well. Wait, you've been through this before, haven't you? :)

25 Oct, 2009

Migrating from XP to Windows 7

Posted by: sharjeel In: Uncategorized

I've been using MS Windows since version 3.1 and ever since Vista is the only OS by Microsoft which I haven't even tried; and I'm glad I didn't. No comments required on this. However I must say the next effort by Microsoft, i.e. Windows 7 is commendable. I tried to switch over to Mac but the non-standard shortcut keys of Mac for a keyboard ninja like me, and a few minutes of usage with Release Candidate new OS successfully proselytized me to Windows 7.

However Windows 7 doesn't have built in support for upgrading from XP. One could follow the painful procedures of upgrading XP to Vista first and then to 7 and struggle with driver issues. Here is a much convenient way.

For me, the most important thing was to retain my profile settings and then my programs as well. Setting up

Windows 7 comes with a utility called Migration Wizard. It lets you backup your settings and restore on a fresh install.

To use it, just boot your Windows XP and insert your Windows 7 installation disc. From the folder \support\migwiz\ run migwiz.exe. It'll let you choose the stuff you want to backup. Keep the file at a safe place (e.g. a USB disc). Now install Windows 7 and run the same tool. This time choose the restoration option and point it to the file in which you saved settings. It'll take some time but it is worth it.

Here is a detailed tutorial: http://www.howtogeek.com/howto/3179/migrate-xp-to-windows-7-with-easy-transfer-and-a-usb-drive/

Sharjeel Ahmed Qureshi

88-E Allama Iqbal Road, Garhi Shahu, Lahore, Pakistan

(Off): +92-42-6132170 (Cell): +92-322-4736374

Email: sharjeel@2scomplement.com URL: http://vcard.acm.org/~sharjeel

Objective

To create value for people using technology

08 Sep, 2009

Future Secondary School English Examination 2.0

Posted by: sharjeel In: Uncategorized

Looking at the way technology is influencing our everyday speaking and writing styles, I think it won't be long before even the most traditional of our schools would get influenced. I remember back in 1997 when I was doing my matriculation studies at Crescent Model School, the teachers did adopt to write letters the way email is indented (i.e. double new line between paragraphs and no indentation at the starting line)

Based on these thoughts, I think the future exams of English might look something like this:

Board of Intermediate & Secondary Education Pakistan
Matriculation Exam - English B
Date: 10th March 2015

Total Marks: 100
Time Duration: 1 hour 45 Minutes

Q1. Write a blog post entry on one of the following having no more than 2000 characters (20 Marks)

  • Life in a Big City
  • Ev0lut10n of cont3mp0r4ry scr1pt$

Q2. Suggest titles for flickr photos tagged with following keywords

a) thirsty, crow, pitcher, pebbles (5 marks)
b) lol, cheeseburger, computer, router (5 marks)

Q3. Write an SMS to your Uncle thanking him for the gift he sent. You may concatenate two SMS to avail 300 characters limit. (10 marks)

Q4. Write an e-mail application to your headmaster requesting him to allow the use of social networks on the school network (15 marks)

Q5. Write a snail mail letter, having no more than 100 words, to your grandfather inviting him to use GMail (15 marks)

Q6. a) Translate into English: "Hy Dad. Rcvd da cash. Cudnt buy books cuz Friendz wanna party. LoL! GTG. Thx. TC" (10 marks)

b) Translate the following Roman Urdu into English "Zindigi k nashebo faraz mein insan par aisa waqt ata hai jab uss ko har taraf andher nazar ata ha" (10 Marks)

Q7 a) Tweet your friend inviting him to spend coming summer vacations with you (5 Marks)

b) Update your Facebook status telling everyone that you won't be available for the next few days but would still keep in touch via net (5 marks)

20 Aug, 2009

Filter crappy posted videos from Facebook feed

Posted by: sharjeel In: Programming

Once Facebook's feed used to be very useful informing you about the updates of friends by their status, . I feel my Facebook feed has been hijacked by redundant and time wasting posted videos. So I wrote a small GreaseMonkey script to filter out posted videos. Here it is:

 
 
// ==UserScript==
// @name           Facebook Remove Vids
// @namespace
// @description    Removes videos from your Facebook Feed
// @include        http://www.facebook.com/*home.php*
// @include        http://www.new.facebook.com/*home.php*
// ==/UserScript==
 
function cleanUpPage() {
	var stories = document.getElementsByClassName("UIIntentionalStory");
 
	for ( var i = 0; i < stories.length; i++ ) {
		var sHTML = stories[i].innerHTML;
		if ( sHTML.match("class=\"UIMediaItem_video") || sHTML.match("class=\"swfvideo") ) {
			stories[i].style.display = "none";
		}
	}
}
 
window.addEventListener("load",
	function() {
		t = setInterval(cleanUpPage, 1000);
	}
	, false);
 

I must say that after removing those videos, very little has been left in my feed :)

22 Jul, 2009

Attempt Retries decorator in Python

Posted by: sharjeel In: Programming

In certain situations particularly when dealing with networks and distributed systems you'd want your program to retry certain a particular operation certain number of times in case it fails before giving up. For instance your program is trying to connect to a mail server which is due to network connectivity temporarily giving socket error.

The simple way is to put a loop, try certain number of times and if the result still fails give up.

I found this pattern normal so I wrote a decorator in Python which can be generically used.

 
def attempt_retries(func, retries=3, delay=3, IgnoreException=Exception):
    """
    Decorator for ignoring certain exception for certain number times and retrying with certain delay
    e.g.   func = @retry(connect_imap, 10, 5, SocketError) # Tries ten times
    e.g.2. retry(connect_imap)(username, password)
    """
    def dec(*args, **kwargs):
        for i in range(retries-1):
            try:
                return func(*args, **kwargs)
            except IgnoreException:
                sleep(delay)
        func(*args, **kwargs)
    return dec
 

Usage:

 
attempt_retries( server_connect, 10, 20, SocketError ) ( host, user, pass)
 

or

 
r_server_connect = attempt_retries( server_connect, 10, 50, SocketError )
r_server_connect( host, user, pass)
 
Tags:

14 Jun, 2009

Ins and Outs

Posted by: sharjeel In: carputer| nerds| technology

Some recent ins and outs of my daily tech-life:

Windows 7 is in - XP and Mac OS X*  are out
Ubuntu Server is in - Fedora and RedHat are out

Flock & Chrome are in - Firefox & Safari 4 are out
Postbox is in - Thunderbird is out
XChat2 is in - mIRC is out
MSN Messenger stays in due to locked contacts :(
Google Talk: Always in :)

Google Desktop is in - Yahoo Gadgets and Launchy are out
TrueCrypt is in - Other File encryption tools are out
VLCPlayer & Foobar2000 are in - WMPlayer & KLite are out
GIMP is in - Photoshop is out (I'm a thrifty developer)

Dropbox would so be in - Manual rsync scripts would be out

Console2 is in - Standard Command Prompt is out
IPython is in - Bash is (almost) out
GNUWin32 is in - Cygwin is out

Aptana is in - Standard Eclipse is out
Notepad++ is in - Notepad is out
Emacs is in - Vim is out
PyScripter is in - Other Python only IDEs are out
Putty connection manager is in - PuttyTabs is out

Python, C, C++ are in - Java, PHP are out
NginX is in - Apache2 is out

Mobile:
Windows Mobile 6.1 are in - WM6.0 and 5.x are out
WM 6.5 would soon be in - iPhone, Blackberry & Symbian probably will never make it! Android may come under consideration.
Windows Mobile Device Center is in - ActiveSync is out
HTC Touch Pro would soon be in - TyTN II would be out
TouchFlo 3D is in - Standard Today is out
Opera Mobile is in - Opera Mini is out
Skype & Windows Messenger are in - Fring is out

Desktop Linux box:
Ubuntu 9 is in - 8.04 LTS is out
KDE4.2 is in - GNome & KDE 3.x are out

Carputer:
Ubuntu is in - XP is out
Gnome is in - KDE is out
Hildon is in - RoadRunner is out
Android Linux apps would soon be in -
Microcontrolled power control is in - Direct switches are out
SAIMA (Sharjeel's Artificially Intelligent Machine for Automation) is in - SMSLib is out

* I tried Mac-OS-X for a while. Loved it for awesome user interface, bundled out of the box applications but at the same time hated it for poor keyboard shortcuts and hardware restrictions. I would have switched but Microsoft did a REALLY good job at Win7.

Does Facebook really need to be worried about how to become Twitter? I don't think so. Facebook has grown out so successfully and elegantly that it becomes a benchmark itself for others to follow. Facebook serves a certain distinguished sets of audience than that of Twitter and I think by just poking into other spaces Facebook would simply loose its stickiness and its loyal userbase.

Facebook has just announced that its users would soon be able to have their own usernames. At the first glance it seems to serve a genuine need. For instance, when we developed the Facebook SMS application, we had a hard time letting users send SMS to their Facebook friends. Had every user got a unique username, it would have been as simple as "@username <the message>". But it has its own implication as well.

One of the things I love about Facebook is that they've kept the profiles and their related data sanitized. I believe it is one of the major reasons why Facebook succeeded while other Social Networks lagged behind despite initially having a wider audience. For instance one of the things that fended me off Orkut was that every friend of mine had a funny name and I couldn't figure out who was who. I would get notifications like "Kachoo-Kooma-123 wrote in your scrapbook", "G3n.X Guy has written a testimonial" without having any idea who these guys were. Later on I would come to know that these are updated "elite" names of people sitting next to me.

On the other hand Facebook has worked hard to keep the profiles real, accurate and spam-free. This has helped even technology averse people join Facebook who have hard time figuring out how to interpret "RT @sharjeelq #facebook now offrz usernames http://tinyurl/blablabla". With proper checks to disallow funny names and rigorous privacy settings to encourage putting accurate information they've kept the site accessible to ordinary (non-1337) humans.

Clearly there is a distinction between the general users of Facebook and Twitter. While twitter users may be more progressive, it is a fact that Facebook users are fond of Facebook not because everyone is on Facebook but because what Facebook is in its current form. They are going to allow people to choose usernames for themselves and disallowing funny usernames is not possible at all. Usernames are supposed to be globally unique and when people having common names like Muhammad Hassan would not be able to get sane usernames like hassan, muhammadhassan, mhassan etc. they'd come up with creative names like mhs1pk. And when you would see "Sharjeel: Hassan, it's been long since I saw you. Where are you these days?" replaced with the culture of "sharjeelq: @mhs1pk wru?", you wouldn't want to stick much to Facebook if you are not a twitter fan or like 1337 stuff.

Introduction of usernames in Facebook is bound to make a significant change in the current userbase of Facebook. Let's see if they get benefit from the new audience!

Tags:

23 Apr, 2009

OpenLaszlo: First Impression

Posted by: sharjeel In: Programming

OpenLaszlo is a framework which, officially, is for creating Rich Internet Applications. It takes a higher level markup language Laszlo and converts it into SWF Flash or DHTML. Like many other tools, you are not bound to create only Internet Apps using OpenLaszlo; go ahead if you wanna create your restaurants digital menu card, interface to your car's sensors or for create a skinned menu for your phone.

I just wrote my first piece of code in OpenLaszlo and the experience has turned out be pretty ambivalent. On one hand I feel having lot of power and control to generate a Flash application. On the other hand I feel very restricted due to poor documentation, lack of supporting editors and a language I feel isn't powerful enough and hence inappropriate.

Let me share my experience:

I saw OpenLaszlo couple of years back and thought it to be pretty cool, but kept on my stack of to-learn technologies until yesterday when I encountered a simple problem: My friend had to prepare his PhD proposal defense presentation and he wanted me to create him a three minute count down timer animation for a particular slide. I thought I'd generate an SWF using Flash and embed it in PowerPoint. Then I thought maybe it is a good oppurtunity to learn OpenLaszlo. Alas, this simple problem which I estimated to be a one hour excercise turned out to be 8 hour long nighter marathon; even at the end I couldn't produce something really impressive.

The main reason I took time was lack of good documentation and examples. The basic tutorial is pretty neat but afterwards everything is messed up. I thought maybe I should, just like learning any other language/tool, take a look at examples on net but it turns out that there are few examples as opposed to one would expect. The reference is pretty complex and the guide is not only hard to understand, but seems outdated as well. I couldn't get some things running which were stated in the documentation (I'm pretty sure I was doing what the documentation says).

But that is Ok as with any open source project, documentation and support gets mature over time. However there are other things that deter you from using OpenLaszlo i.e. lack of tools. The running process is horrible for the first time user. There are no editors out there. The best I could do was use Notepad++ was HTML or XML as language. The most annoying this is that there is no debugger. There IS a debug console but not a debugger.

To me, the biggest limitation was the language, the markup language. I felt that I had to hit the keyboard five more times as I would in a scripting language like Python to achieve the same task. For simple UI element level stuff it seems OK but whenever I needed to introduce some logic, I felt as if I were writing code in machine language: so much stuff to do.

For instance, take a look at this piece of code:

 
 <class name="box" bgcolor="red"
         height="100" width="100" />
 
  <class name="borderedbox" extends="box"
         width="${size}" height="${size}"
         onmouseover="this.changeSize(50)"
         onmouseout="this.changeSize(-50)">
    <attribute name="size" value="100"/>
    <attribute name="bordersize" value="3"/>
    <view bgcolor="yellow"
          x="${parent.bordersize}"
          y="${parent.bordersize}"
          width="${parent.width - parent.bordersize*2}"
          height="${parent.height - parent.bordersize*2}"/>
 
    <method name="changeSize" args="pixels">
      this.animate('size', pixels, 500, true);
    </method>
  </class>
 

If instead of a Markup language, had it been modeled in an object oriented script language it would have been much more succinct and readable. Let's see how almost same thing could be modeled in Python:

class Box:
	height=100
	width=100
	bgcolor="red"

class BorderedBox(Box):
	bgcolor="yellow"
	size=100
	bordersize=3

    unnamed_view = view(bgcolor="yellow", x=self.bordersize, y=self.bordersize,
	                      width=self.width - self.bordersize * 2,
                          height=self.height - self.bordersize * 2)
	def __init__(self):
	    self.width = self.size
		self.height = self.size
	    onMouseOver=lambda:self.changeSize(50)
        onMouseOut=lambda:self.changeSize(-50)

	def changeSize(self):
	    somehow_embed_js(""" this.animate('size', pixels, 500, true); """);

Of course it has its own limitations and cannot achieve all what the markup can, I still think that the trade-off would deter people from using it.

Sometimes you want your File Transfer tool to map certain folders on your dev machine to remote folders on your different remote machines. Wouldn't it be great if you could choose a particular file in your project, click it and it automatically uploads in appropriate folder on desired server?

For instance I have an XP dev machine with a project in folder "D:\workspace\saima" and another in "D:\workspace\ismspk". I would like all files in any sub-directory in "saima" to upload on my server "saima" in the appropriate sub-directory in "/home/saima/workspace/". Same goes for rest of my projects and servers. Of course I'd like to do it with a simple click rather than choosing the sessions and folders in my FTP client every time I make a change in a file.

I tried such an option with FileZilla and WinSCP but couldn't find any such option (maybe there exists one). So I thought about writing my own. Since I'm running XP with RSA keys setup with pageant, pscp (Putty SCP Client) was a good choice. Though other command-line utilities such as rsync etc. may do the job pretty as well.

I wrote a small Python script which I linked to my "Send To" menu. To add something in your Send-To menu, goto run, type "sendto" and create a new link here. I created a link to my Python Script and named it "Upload".

UPDATE: For Windows 7, type "shell:sendto" in your explorer bar to make a Send-To shortcut

Here is how it looks like

Here is the Python script I wrote

"""
Author: Sharjeel Ahmed Qureshi
Description: Script for uploading files via pscp
You need to setup putty sessions and your RSA keys first.
Make sure that pageant is running and pscp is in your PATH variable.
Works for windows only
You are free to use this script anyway you like
"""
 
from os import path, popen
import sys
 
import logging
logger = logging
logger.basicConfig(level=logging.DEBUG)
 
FILES_TO_UPLOAD = sys.argv[1:]
 
# PATH_RULES is a config variable which is list of path rules
# Each path rule is a list of three members:
#    ['Local Drive + Directory', 'putty session name', 'remote directory']
# e.g.
# PATH_RULES = [
#    ['d:/workspace/saima/', 'saima', '/home/saima/workspace/'],
#    ['d:/workspace/smsfriends/', 'facebooksms', '/home/fbsms/public_html/www/smsfriends/'], ]
 
try:
    PATH_RULES = [
        # ['localdir', 'puttysession', 'remote_dir'],
        ]
 
    for i in PATH_RULES: i[0] = path.abspath(i[0]).lower()
    if not PATH_RULES: raise Exception("No rules defined!")
except Exception, e:
    logging.exception("There was an loading the config. Check your rules: %s" % e.message)
 
def err(msg):
    logging.error(msg)
    sys.stderr.write(msg + '\n')
 
def match_server(filename):
    """ Gets matching server for a given filename including fullpath """
    global PATH_RULES
    filename = path.abspath(filename).lower()
    for r in PATH_RULES:
        if path.dirname( filename ).startswith( r[0] ):
            psession = r[1]
            r_path = r[2] + filename.rsplit(r[0],1)[1].replace('\\', '/')
            return (psession, r_path)
    return None
 
def upload(filename):
 
    if path.isdir(filename):
        err("Directory Upload is currently not supported")
 
    server = match_server(filename)
    if not server:
        err("No rule available about uploading this file")
        return
    psession, r_path = server
    cmd = "pscp %s %s:%s" % (filename, psession, r_path)
    # logger.debug("Executing command %s" % cmd)
    print cmd
    print popen(cmd).read()
 
for f in FILES_TO_UPLOAD:
    try:
        upload(f)
    except:
        logging.exception("Error while uploading %s" % f)
 
raw_input("Press ENTER to Continue")
Tags: ,

16 Feb, 2009

Python: Copy to clipboard

Posted by: sharjeel In: Programming

I use this small utility function for debugging certain Python scripts, especially those for processing data, e.g. moving some bits of information to Excel.

The idea is pretty simple. Just pass it some information and it'll be available in your clipboard.

 
import sys
import win32clipboard as wc
import win32con
 
def copy_to_clipboard(msg):
   if sys.platform == 'win32':
      wc.OpenClipboard()
      wc.EmptyClipboard()
      wc.SetClipboardData(win32con.CF_TEXT, msg)
      wc.CloseClipboard()

It works on Win32 and you need CTypes installed.