Python

Best Hello World App Ever :D

February 1st, 2010 0 Comments

Written in Python :D

See http://failboat.me/2009/cute-functions-creating-pseudo-operators-in-python/ for more details.

#Hello World

class Operator(object):
    def __init__(self, func, count=2):
        self._func_ = func
        self._args_ = []
        self._count_ = count
    def __ror__(self, first_arg):
        self._args_.append(first_arg)
        return self
    def __or__(self, arg):
        self._args_.append(arg)
        if len(self._args_) >= self._count_:
            return self(*self._args_)
        else:
            raise RuntimeError("Incorrect number of parameters")
    def __call__(self, *args, **kwargs):
        self._args_ = []
        return self._func_(*args, **kwargs)

def alpha(letter):
    @Operator
    def _alpha(a,b):
        return a+letter+b
    return _alpha

for c in range(65, 122):
    globals()[chr(c)] = alpha(chr(c))

print "H"|e|"l"|l|"o","W"|o|"r"|l|"d"

Gettings the most out of your bits

November 1st, 2009 0 Comments

The following will produce the bit representation of an ord(byte) in python

def bit(chr, i=0, str=''):
    if i > 7: return str
    coef = (2**(8-i-1))
    if chr >= coef: return bit(chr-coef, i+1, str+'1')
    return bit(chr, i+1, str+'0')

Example

print bit(ord(“a”))
01100001

Primitive Collision Detection – Circular objects

October 31st, 2009 0 Comments

Consider the following –

If you are designing a game, and have the players shaped as circles, how would you detect bullet collisions with the players?

Well, the problem with bullet collision detection is that you can’t just use traditional collision detection algorithms with static objects. The bullet itself can be seen as a continuous object, thus we need to devise a new way to solve the problem

[Python] Get Function Args

October 28th, 2009 0 Comments

getargs = lambda func: (func.func_code.co_varnames[:func.func_code.co_argcount])

Example Session


#Example Session

getargs = lambda func: (func.func_code.co_varnames[:func.func_code.co_argcount])
def addition(x,y):
    return x+y
print getargs(addition)
#('x', 'y')

Yep, it’s really that simple. No weird exec functions needed, no intrusive introspection via the disassembler.

Cute Functions – Creating pseudo-operators in Python

October 26th, 2009 1 Comments

I ran across something today that I found to be extremely interesting. Basically, the authors of Should_DSL, http://pypi.python.org/pypi/should_dsl/1.2.1, have attempted and succeeded in creating pseudo-operators based on operator-functions within an object.

Let me elaborate.

The goal of Should-DSL is to write should expectations in Python as clear and readable as possible, using “almost” natural language (with limitations from Python language).

And to be honest, they’ve got it all right.

Python limits function calls to callable objects through the () notation. However, custom functors can also have their own __call__ method invoked when an operator or a reverse operator is used on them. Take for example the following code

class WeirdFunc(object):
    def __init__(self, func):
        self.func = func
    def __radd__(self, arg):
        return self(arg)
    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)

@WeirdFunc
def one(other):
    return other+1

print "'3+one' will evaluate to %s"%(3+one)

Will yield ‘3+one’ will evaluate to 4

So taking this to a whole new level, the folks at Should_DSL have created their assertion operators to be as semantic as possible. The syntax taking form to look something like

from should_dsl import *
import unittest

class UsingShouldExample(unittest.TestCase):
...     def test_showing_should_not_be_works(self):
...         'hello world!' |should_not_be| 'Hello World!'
...
...     def test_showing_should_have_fails(self):
...         [1, 2, 3] |should_have| 5
...
...     def test_showing_should_have_works(self):
...         'hello world!' |should_have| 'world'
...
...     def test_showing_should_not_have_fails(self):
...         {'one': 1, 'two': 2} |should_not_have| 'two'
...
...     def test_showing_should_not_have_works(self):
...         ["that's", 'all', 'folks'] |should_not_have| 'that'

from cStringIO import StringIO
runner = unittest.TextTestRunner(stream=StringIO())
suite = unittest.TestLoader().loadTestsFromTestCase(UsingShouldExample)
runner.run(suite)

Notice that in place of self.assert*, the tests instead uses x |should_[not]_be| y, which while verbose, is intuitive when placed in the context of running tests (which are by convention much more tolerant of verbosity).

So how do they do it? The key here is that the ‘|’ operator can be functionalized as the __or__ and __xor__ method of any given object. Thus we can cache the values passed to __or__ (the second argument) and __xor__ (the first argument) and then pass that back to the __call__ method.

We can easily prototype a decorator class for this pseudo-operator object

class Operator(object):
    def __init__(self, func, count=2):
        self._func_ = func
        self._args_ = []
        self._count_ = count
    def __ror__(self, first_arg):
        self._args_.append(first_arg)
        return self
    def __or__(self, arg):
        self._args_.append(arg)
        if len(self._args_) >= self._count_:
            return self(*self._args_)
        else:
            raise RuntimeError("Incorrect number of parameters")
    def __call__(self, *args, **kwargs):
        self._args_ = []
        return self._func_(*args, **kwargs)

Here the variables are cached in the obj._args_ list, which is unpacked as the parameters of the __call__ method in the second ‘|’. An example usage would be as follows:

@Operator # Turns the plus function into the |plus| operator #
def plus(first, second):
    return first+second

print 1 |plus| 2
# Will return 3

Happy Coding

Python – Abstract Function class

August 2nd, 2009 0 Comments

Python is great. It’s dynamic, it’s flexible, and best of all, for almost all major datatypes, there’s an associated abstract class from which you can over-ride and build your own object out of.

Of course, Python doesn’t treat functions in this same way. But as developers we cope and we move on when we have to.

Until recently I’ve been blissfully oblivious of this fact, of course I’ve never had the need to overload the default functionality of a function and thus have never had needs of an abstract class for functions as well. As far as I’m concerned, using the def operator is much more simplistic than having to toil to create a brand new class and in doing so cheating python out of its gracefulness.

But a few days ago I had to write a program in which native python functions are given and the program needs to find out whether the functions’ opcodes matches and return true if it does. Naturally I assumed that the == operator for functions covers this aspect. I was shocked to find out that it doesn’t. Now I’m stuck with one of two ways out. I could write a messy block of code to manually check for the func_code.co_code, or I could write my own abstract class for function types and then just use the == operator to keep everything elegant.

Well, I must have been bored because rather then going along with writing an intermediate function to do the checking, I actually wrote a whole base-class to replicate a function’s, well, functionalities.

The class started off as it would for any other class, I knew that I wanted an object that’s callable, and when attributes are being requested would return instead those from the function that it’s derived from. I want to keep things as simple as possible so the only instance member of this class would be the actual function that it’s derived from.

The skeleton code for thus far goes like

Chroma-Hash implementation in Python

July 30th, 2009 0 Comments

I’ve just read an experiment by mattt.me about creating a multi-colored area beside the password area in order to let people who have extremely long passwords know that their passwords matches.

http://mattt.me/2009/07/chroma-hash-a-belated-introduction/

Personally I thought that this is an extremely neat concept, but of course, also extremely unsafe (unless the passwords aren’t hashed when they are stored…)

So now I got to thinking, what if we can implement this feature into the login box? Basically, the user types in his username and the chromahashed password is automatically visualized and the user can match it up with the chroma-hashed visualization? So in order to do that, the server could return segments of secure html color codes hashed from the user’s password and display it onto the screen so users can make sure that their passwords are correct.

Since I’m mostly a python developer, I’ve decided to create a port of Chroma-Hash for python (You have to admit, django’s pretty popular these days and who knows who else is going to be needing this) And so without further delays, I present to you pyChroma – A python port of Chroma-Hash

http://github.com/leegao/pyChroma/

Here’s the class __doc__

"""
@author: Lee Gao
@contact: http://6.dot.ch/
@note:
    This is a re-implementation of mattt*'s Chroma-Hash calculator.

http://mattt.me/2009/07/chroma-hash-a-belated-introduction/

@param param:
    password: The password to chroma-hash
    default: The number of colors to return
    _hash: If the password is already hashed by another algorithm or is
           already a MD5 hash, then the _hash function (which takes only one parameter)
           will return a MD5 compatible hash
           SHA1 will be implemented when mattt decides to update his Chroma-Hash specs
@return:
    chroma object with 1-4 HTML color items.
@ivar ivar:
    chroma.colors - array of the chroma-hashed colors
Example:
    from Chroma import chroma
    myColors = chroma("password")
"""

Auto-restart in (Python) and subprocess.Popen goodness

July 11th, 2009 0 Comments

This is an auto-restart script for Orbited, but it can be modified to be used with other apps. This is presuming that there’s only one instance with that name running.

Basically, this script takes into account the fact that if you use ps -e| grep orbited, it’ll output a list of pids of which their process names are orbited. So in this case, every 60 seconds after orbited crashes, if there’s no process in the system process list named orbited, then this script will auto-start the process.

import os, time
from subprocess import *

lookfor = "orbited"

while True:
	pslist = Popen(["ps", "-e"], stdout=PIPE)
	orbited = Popen(["grep", lookfor], stdin=pslist.stdout, stdout = PIPE)

	output =  orbited.communicate()[0]

	if len(output) == 0:
		os.system("orbited")

	time.sleep(60)

A more useful tool from subprocess.Popen is if you use it as a process list and as a noob friendly task manager.

from subprocess import *
import os

print ""

lookfor = raw_input("Which Process should be terminated? [orbited] >> ")

if len(lookfor) <= 0:
	lookfor = "orbited"

#Give you a list of all processes
print "All System Processes With the name of "+lookfor
print ""

#Popen(["ps", "-e"])
os.system("ps -e| grep " + lookfor)

#Here's the command that we want to have
#ps -e| grep orbited
#It's a bit tricky to implement this in python

pslist = Popen(["ps", "-e"], stdout=PIPE)
orbited = Popen(["grep", lookfor], stdin=pslist.stdout, stdout = PIPE)

output =  orbited.communicate()[0]

output  = output.split("\n")

print "\nPIDs. Type 'y' to Kill this service"

for proc in output:
	proc = proc.split()
	if len(proc)>0:
		#proc = proc[0]
		print "\t" + proc[0] + "\tName: " + proc[3]
		if raw_input("\tDo you wish to Kill this Service? (y/N) ").lower() == "y":
	 		print "\tkilled " + proc[0]
			Popen(["kill", proc[0]])

print ""