IdeaMonk

thoughts, ideas, code and other things...

Wednesday, June 30, 2010

So Distribute!



Sitting with my new (in working-on-linux sense) pen tablet, with nothing much to do, I just scribbled down my newly developed understanding of why should we distribute processing and there isn't much point in increasing CPU speeds these days.

Zoom it to get a clear picture of the problems with just one processor.

Labels: , ,

Monday, June 28, 2010

Yet another Google Calculator shell in Python

For the sake of weekend hack and getting rid of some headache of post bangpypers meetup chicken overload of today's evening -
import re
import urllib
import mechanize
import unittest

class GCalc:
def __init__(self):
self.browser = mechanize.Browser()
self.browser.set_handle_robots(False)
self.browser.addheaders = \
[('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

def cleanup(self,text):
strip_tags = re.compile("<.*?>")
return strip_tags.sub('', text.replace("<sup>","^").replace("</sup>","").replace("×","X"))

def calc(self, query):
try:
raw_result = self.browser.open("http://www.google.com/search?hl=en&q="+urllib.quote_plus(query)).read()
return self.parse(raw_result)
except:
return "Failed to reach Google"

def parse(self, raw_result):
try:
result = raw_result.split('''<td style="vertical-align:top" >''')[1].split('</h2>')[0] + '</h2>'
return self.cleanup(result)
except:
return "Not a calculator query"

class TestGCalc(unittest.TestCase):
def setUp(self):
self.g = GCalc()

def test_numeric(self):
self.assertEqual(self.g.calc("4+5"), "4 + 5 = 9")

def test_bignumbers(self):
self.assertEqual(self.g.calc("234623476 * 59999999999"), "234 623 476 * 59 999 999 999 = 1.40774086 X 10^19")

def test_units(self):
self.assertEqual(self.g.calc("14 inch in mm"), "14 inch = 355.6 millimeters")
self.assertEqual(self.g.calc("one acre"), "one acre = 4\xc2\xa0046.85642 m^2")

def test_cacl(self):
self.assertEqual(self.g.calc("3 * PI / sin(3)"), "(3 * PI) / sin(3) = 66.7855543")

def test_facts(self):
self.assertEqual(self.g.calc("speed of light"), "the speed of light = 299\xc2\xa0792\xc2\xa0458 m / s")


if __name__=='__main__':
unittest.main()

Fork it here, have fun, curse me for crappy splits :)
Just learnt unittest a bit, ah so easy and useful :D

I guess you can notice the grand theme here - Its just ~ 50 lines of code packed up with a unit test and does the job!

I suggest you better not miss PyCon India 2010 in case you too are eager to do some productivity magic with you/your employees/students/etc.

Adios

Labels: ,

Monday, June 21, 2010

DWM-ified

Arch + Dwm + Conky + Dzen2 + links + vim + irssi (plus ram eaten by chrome, firefox, thunderbird, and eden) otherwise awesome at ~100MB, ideal light & fast setup for my netbook :)

Labels:

Saturday, June 12, 2010

No more self everywhere

A lot of people complain about how they have to write "self" repetitively in their OO code in Python. Here is a neat trick that doesn't get you rid of "self" but lets you put another name for it -

>>> class Foo:
... def __init__(me):
... me.var = "Hola"
...
... def say(me):
... print me.var
...
>>> f = Foo()
>>> f.say()
Hola
>>>

Labels: ,

Tuesday, June 01, 2010

Extending the DOM for more functionality

Reading some ExtJS examples today, I came across this -
function highlightWindow() {
var win= Ext.getCmp('myWindow');
var winBody = win.body;
winBody.highlight();
}

highlightWindow.defer(1000);
How beautiful is highlightWindow.defer(1000) :) It causes the function call to delay by 1s.

Something like this would be elegant compared to plugging in setTimeouts everywhere in your code. On some further exploration I found that I can extend functions too, I had seen one such useful extension of String class using String.prototype.foo = function() {...

We can do such things with functions too, for e.g this snippet would add a delay function to any existing functions -
Function.prototype.delay = function(ms){
setTimeout(this,ms); // call yourself after given delay
};
So now we can have a nice way to delay a function - eg. doMyWork.delay(5000) :)
Function.prototype.delay = function(ms){
setTimeout(this,ms); // call yourself after given delay
};

function foo(){
// just append some message to an element
document.getElementById("progress").innerHTML += "foo() got a call";
}

function doWork(){
document.getElementById("progress").innerHTML +=
"delaying foo() for 1000ms";
foo.delay(1000);
}
Another interesting use-case -
Lets say we wish to convert an array into CSV, we could let that be held inside array itself and call is like myarray.toCSV(), like this -
Array.prototype.toCSV = function(){
var csv = new String();
for (i=0; i<this.length-1; i++){
csv += this[i].toString() + ", ";
}
csv += this[ this.length-1 ].toString();
return csv;
};

Ah and you can even have your own DOM appender -
Element.prototype.append = function(message){
this.innerHTML += message + "<br />";
}

A working demo here - http://ideamonk.in/playground/extjs/extension.html
Further reading - Six missing functions in JavaScript arrays

Labels: