Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Simple Countdown Clock - Python and xdaliclock

Here is a simple countdown clock script which you can use. It is simply
sending -countdown argument properly to the xdaliclock binary.

I find having this script in my /usr/local/bin pretty useful.




#!/usr/bin/python
# A Simple Countdown Clock using xdaliclock
# usage: countdown [time]
# time defaults to 1 hour.

import time
import sys
import subprocess

try:
hours = float(sys.argv[1])
except IndexError:
hours = 1
hours = int(time.time()) + int(hours * 3600)
command = 'xdaliclock -countdown %d' % hours
subprocess.Popen(command.split())

power 2 in python using lshift

left shifting 1 in python does a pow 2 operation. I was just doing some performance comparison and here is an interesting result.

$ python -mtimeit 'pow(2,64)'
1000000 loops, best of 3: 1.18 usec per loop
12:31 AM:senthil@:~
$ python -mtimeit 'getattr(1,"__lshift__")(64)'
1000000 loops, best of 3: 0.356 usec per loop
12:32 AM:senthil@:~


I don't know the reason for this difference, I shall update the post when i find out why.

Py3k PEPS at APAC PyCon

I went to Singapore to attend APAC PyCon and also to meet Shalini. It was a good 4 days for me. I presented a talk on Py3K PEPS at APAC Pycon.

The Conference Experience was very good. I had a chance to meet Mark Hammond and discuss a lot of Windows Related things with him with. His presentation on raindrop, couch db and and his perspective on Windows development was very good. It was good to meet in person Liew Beng Keat, the organizer of the Conference who had done a lot of hard work to put this together. I also met Steve Holden, who was present along with his wife, I assume they had a good holiday time at SG, as it is a shopper's paradise. It was good to the warmth in Steve's welcome and this makes him a very good organizer, I guess.

On the first day, the talks I enjoyed the most were Mark's Couch DB talk, wherein I gained good knowledge of JSON based Non-Relational database and a javascript based map-reduce framework. The concept was very interesting. The final talk by Wesley Chun drew in a huge enthusiasm. Wesley did a very nice presentation on Py3k and explaining its features and kind of potrayed the picture that it would take long time for people to move to Py3k. Well, it could be true, but as I debated with him, it would be very good to just potray positively how Py3k is a more symmetrical in many ways that Py2k. His point of view was pragmatism and training for corporations. I tend to agree with him to an extent, but I still believe that for some "good programmer" to start learning Python, Python 3 is a very well designed a symmetrical one rather than Python 2. The libraries and packages will catch up soon.

I also enjoyed Graham Dumpleton's short pitch on mod_wsgi and flask. I still use mod_python and plan to move to more web-development related libraries soon.

My presentation on Py3k PEPS was on next day, it went well and was attended by a small interested audience. Following Presentation by Martin Faassen was very good too. He presented a perspecive on creating libraries, the creative aspect of development of software. Steve Holden's Metaclass Madness talk was enlightening too. It was short presentation and a consise one. It would good to write an article based on his presentation if its not already there. Because Python Metaclasses are something which does not have a lot of literature around in the web. The Q&A in the Metaclass'es talk was good one, as one person asked as when do the metaclasses take effective if we were to wrap teh private methods ( which was denoted by startswith('__') and and it turned out that Class mangles them to _Classname__privatemethod and the metaclass wrapper comes to affect later only). If I write an article, I shall discuss this in more detail. There are some interesting studies which can be done on Metaclass vs Class decorators.

I also attended Noufal's game related talk. It was good one which was attended by a sizable audience. He walked through the code and explained the physics of the game. It was good to see that if developing games we can use real world physics in games using libraries, Interesting. Also, I am not sure, how effective showing a lot of code in the talk is effective. It is very difficult to follow through. Somethings slides with less bullets and easily chew-able points make the presentation more grasping and provide useful inputs to the audience.

The singpass coder's tournament was good one too. I managed to come into Second round. My trials some with functional programming and mis-reading of problem statements cost me some time. But it was a very enjoyable game. A person by name 'Che' from China won the iPad and Noufal got the $100 Amazon Web-services coupon.

On Both days, Shalini came to pick me up from the conference and we went for a stroll in the nearby park of Fort Canning. It was good to talk, walking in the park and saw a lot of people practicing tai-chi. On Saturday we visited a lot of friends, inviting them for our marriage reception at Singapore, we also went to Jackie Chan movie, "The Karate Kid", it was fun. I liked the part where the kid shows his dancing skills on DDR to his girlfriend and she in turn amazes him after acting very shy. The concept of kung-fu as a way of life is also good. On Sunday we did some purchasing, spent a wonderful afternoon at home and in the evening I headed back to India.

float.as_integer_ration

From python2.6, you can get a the integer ratio of a float.

$ ./python
Python 2.7b1+ (trunk:80674M, May 1 2010, 08:23:48)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 3.14.as_integer_ratio()
(7070651414971679, 2251799813685248)
>>> x*1.0/y
3.14
>>>

Greedy vs Non-Greedy in Re - Good Example

Here is a good example to explain greedy vs, non-greedy search using module re in Python.



*?, +?, ??

The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.

How identation works for Python programs?

It is well explained in this article.

It is the lexical analyzer that takes care of the indentation and not the python parser. Lexical analyzer maintains a stack for the indentation.
1) First for no indentation, it would stored 0 in the stack [0]
2) Next when any Indentation occurs, it denotes it by token INDENT and pushes the indent value to the stack[0]. Think of it as a beinging { brace in the C program. And if we visualized, the can be only one INDENT statement per line.
4) When de-indent occurs in a line, as many values are popped out of the stack as the new reduced indentation till the value on the top of the stack is equal to new indentation (if not equal, error) and for each value popped out a DEDENT token in written. (Like multiple end }} in C)

A simple code like this



if x:
if true:
print 'yes'
print 'end'


Would be written as:

<if><x><:>                           # Stack[0]
<INDENT><if><true><:>  # Stack [0,4]
<INDENT><print><'><yes><'> # Stack [0,4,8]
<DEDENT><DEDENT><print><'><end><'> #Stack[0]

The parser would just consider the as <INDENT> as { of the block and  <DEDENT>  as } of the block would be able to parse it as logical blocks.

That was a well written article again.

Lambda functions

I often forget the syntax and usage of lambda functions, the following examples should help as a reminder.


>>> def function(x):
... return x*3
...
>>> function(2)
6
>>> func_with_lambda = lambda x: x*2
>>> func_with_lambda(2)
4
>>> (lambda x: x*2)(2)
4
>>>

Soc application accepted

wow! my Google Soc application to Python Software Foundation got accepted. My mentor will be George D. Montana. Thank you G-SOC and PSF.

enumerate function in python; pyTip

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.



>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe