Skip to main content

Posts about python (old posts, page 4)

Raising Windows using Python

Posting a small snippet of code, that I've been using for months now, on the request of a friend 1.

It basically checks for open windows of a program and brings them to the foreground or starts the program. I use it for my 3 most commonly used programs — Emacs(Mod4+E), Firefox(Mod4+F) and the Terminal(Mod4+T). I'm using a neat tool called xdotool 2 to search for windows using titles.

  • Mod4+E is mapped to ~/bin/raise.py emacs

Similarly, for firefox and terminal.

#!/usr/bin/env python
import subprocess
import sys

if len(sys.argv) < 2:
    print "Usage %s window-name" %(sys.argv[0])
    exit(1)

program = sys.argv[1]

# Having different variables helps, in case of some programs.
window = program

# search for windows titled "window"
search = subprocess.Popen("xdotool search --class %s" %(window),
			  stdout=subprocess.PIPE, shell="FALSE")
search_output = search.stdout.readlines()
search.stdout.close()
print search_output

search_output = [each.strip() for each in search_output]

# Raise the first window or start the program
if len(search_output) is not 0:
    subprocess.Popen("xdotool windowactivate %s"
		     %(search_output[0]), shell="FALSE")
else:
    subprocess.Popen(program, shell="FALSE")

Feel free to use it as you like. :)

Any improvements and suggestions are welcome.

Footnotes:

1

dusual on twitter

2

xdotool - Homepage

Augmented assignment in Python

If you are new to Python, you should probably stop reading here. But, if you have used Python and numpy, then read on. Before, that try these bits of code.

import numpy
a = numpy.array([1,2])
a = a + 0.5j
print a

The "same thing", in a slightly different way.

import numpy
a = numpy.array([1,2])
a += 0.5j
print a

Both the code blocks, look really the same, until you look carefully. Under normal circumstances a = a + b and a += b behave exactly similarly, and we really don't need to bother about the differences between them.

But, +=, which is an augmented assignment operator, actually tries to perform the operation in-place, unlike the other statement where + actually returns a new object which is again being referenced by the name a.

But, when dealing with numpy arrays, this will lead to trouble. When assigning to an array, it's dtype is not changed and hence the trouble.

The right way to use the augmented assignment operator, would be:

import numpy
a = numpy.array([1,2], dtype=complex)
a += 0.5j
print a

The same thing is explained in this thread. Also, Thanks to Bhanukiran for asking me this.

Notes from Pycon

Just back after attending PyCon India '10. It was not as exciting as I hoped it would be. That's generally the case with any conference I attend. (I guess, I expect too much from them. :P)

The keynote by David Goodger (pronounced like Badger :) was "Good". It was a very simple one talking of how to get Python into the workplace. His simple recommendation was to use Python if we saw any opportunity where it could be used, without bothering about permissions, convincing people etc. "It's better to ask for forgiveness, than for permission." He spoke of myths around Python – scripting language, dynamic language, too much white space, toy language, nobody uses it. He concluded the talk, by saying mentioning Indian driving to be an indication of some quick reflexes that we Indians have. ;) On the whole it was an enlightening, humorous and enjoyable talk.

I didn't attend too many of other talks. Amongst the ones that I did attend, I particularly liked the one by Asim Mittal on using the Nintendo Wii with Python.

On some thought about my experiences at conferences, I think conferences shouldn't have any talks at all. Or atleast, I shouldn't be attending conferences for talks. They are an excuse to catch-up with people. Conferences should have only lightning talks of 10 mins and sprints. Talks, with an extensive explanation of stuff that can be easily found on the web, are a waste of time.

PyCon India '10

Looks like PyCon India 2010 is going to be great fun! With 80 talk submissions, quite a few interesting ones, this time's PyCon should be much better than last year's. Also, David Goodger of docutils and ReST fame will be the keynote speaker!

  • Dates: [2010-09-25 Sat]–[2010-09-26 Sun]
  • Venue: MSRIT, Bangalore
  • RSVP here!

supporter-small.png

Sage Days 25, Mumbai, India

What is 'Sage Days'?

Sage Days is a confluence of present and prospective SAGE Users and Developers. It is an opportunity to come together to share ideas, brainstorm and hack on Sage. Sage Days 25 is the 25th version of Sage Days, and is being organized in Mumbai, India. In order to cater to an Indian audience and scenario, this version has been tweaked slightly. Sage Days 25 has beginner level tutorials, in addition to the usual talks and sprints, to help new users get started with Sage and help promote the use of Sage in India.

What is Sage?

Sage is a free, open-source mathematics software system licensed under the GPL. It combines the power of numerous existing open-source packages into a common Python-based interface. It's mission is to create a "viable free open source alternative to Magma, Maple, Mathematica and Matlab". Sage has tools for a broad range of mathematical areas like Linear Algebra, Calculus, Symbolic Math, Plotting, Rings & Groups, Graph Theory, Number Theory and Cryptography. Essentially, "it can do anything from mapping a 12-dimensional object to calculating rainfall patterns under global warming" - as Science Daily puts it . Eager to get started? Start here. Apart from being feature rich, it's usability is one of it's greatest strengths. Sage Notebook, a web-interface for all the math you'll ever want to do, is really the killer feature! As the Sage Marketing page says, "The SAGE GUI surely works on your computer box, because it just runs in Firefox!". Try it Now!

Why should you attend?

Sage Days 25 is being attended by the creator and lead developer of Sage, Prof. William Stein. It will also be attended by other developers of Sage. This would be a great opportunity to meet and interact with them! The conference will be attended by a plethora of enthusiastic people from all over the country who use Sage or are interested in doing so. The conference will also see the presence of many mathematicians interested in software. Who knows, you may run into someone you'd want to collaborate with, for your future work! This event will be a great learning experience, if you are even remotely interested in math and software for it!

When and Where?

  • Venue: IIT-Bombay, Mumbai, India
  • Dates: August 9-12, 2010
  • Tentative Schedule
  • Register Here
  • Click here for more info

talk at GNUnify' 10

Shantanu and I conducted a workshop on Scipy at GNUnify '10. It was intended to be an introduction to Scipy and Numpy through Image processing. We expected an audience which was python literate. But GNUnify's schedule wasn't too favorable for us. Ours was the first talk scheduled and we ended up getting people who only "heard" of Python, the language.

We had planned quite a bit of stuff expecting a python literate audience. But unfortunately, we had to start almost from scratch and couldn't do all of what we planned. Still, the workshop wasn't too bad. Nobody left mid-way during the 2 hour workshop; nobody was dozing either. I would have liked my first talk at a FOSS event to be better, though.

Slides and Images that we used. Shantanu's post on the talk is here.

numpy, pacman and me

I'm now officially a part of the Arch Linux community! Arch Linux is a lightweight and flexible Linux® distribution that tries to Keep It Simple.

I have started using arch from less than a week or so. It took me a while, not too long, to realize the beauty of this distro. I was trying to tweak the settings of my org-mode's remember (on Karmic), trying to make it work the way I liked it. After breaking my head with .emacs and lisp for a while, I realized the version of my org-mode was way different from the version of the docs, I was reading. It didn't take long to figure out, which version of org-mode to get. As a matter of curiosity, I checked AUR for the version, and true to Arch's reputation it was bleeding edge! I was still using Karmic, since I hadn't got my Arch installation working the way I like it, yet. Out of laziness. sudo reboot; to hell with laziness!

I was setting up things I regularly use, tweaking my way around. After a day or so, I find python-numpy is out of date. And to top it, an orphaned package! I didn't feel one bit good about this. After some futile attempts to suppress my discomfort, I sat down to work.

After an afternoon of effort, I created my first PKGBUILD. :) I now have python-numpy installed using pacman! Pleasure to join the Arch User Community! Also, thanks to lifeeth and Lynus Vaz, for the sparks.

PS: I'm using Arch with Openbox. It's neat! PPS: org-mode is really awesome! It's a world in itself. life in plain text, truly!]

A Byte of Python

This post's been inspired by a wonderful book, "A Byte of Python"1 by Swaroop C H. The book has been revised after a gap of nearly 4 years and the wait is worth it! I thoroughly loved the book, and I'm happy to be accompanied by so many2 others3. This book has filled me with a sense of joy and pride. The pride, of being part of such a wonderful community, a beautiful crowd. Further, it is a matter of pride, the book's been authored by an Indian - its quite rare to find such books written by people in this part of the world.

I have loved python, the moment I started using it. There are quite a few occasions, where I did something, just because I had the power of Python with me. Python is undoubtedly amongst the best, not just as a first programming language, but to give the user a sense of "do-able-ity" and I am thoroughly enjoying it.

>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Footnotes:

1

A Byte of Python

2

Python - Notes – Swaroop CH

3

Book updated for Python 3000 – Swaroop CH

Update Script

Well, this isn't an update of how I'm doing on my sabbatical. Its just been 3 days and I'm doing pretty fine. I just finished writing a script to keep my blogs page in sync with my google-reader (well not exactly). The script parses an xml export of my google-reader-subscriptions and updates the edits the html of my unnought-blogs page. period.

There are a couple of things I don't like about this script.

Firstly, I don't want to keep exporting my google-reader-subscription each time I make changes. The script should be able to directly sync with my google-reader without me having to export the file. [I have read about the atom subscriptions feed of Google Reader, but haven't been able to get it right.] Hopefully, I'll be able to do it in the near future.

Secondly, The blog author's name is non-existent. I can't do anything about this though.

Also, In the process, I had the chance to look a geeky ad. I found it at the weirdest of places!

header: X-hacker: If you're reading this, you should visit automattic.com/jobs and apply to join the fun, mention this header.

ps :

  1. The source is GPLv2 licensed.
  2. Get in touch, if you'd like to have a look.

Lafoot or Lafoobot!

Summer'08! I'm at home, doing nothing practically. :| No Internships, No Projects, No GRE plans (a little pushing for GRE has just started from the junta around.)

Just to kill some time and to learn some Python, I have begun to write an IRC chat bot &lt;lafoobot&gt; [Lafoot + Bot]. The present haven of lafoobot is #fosskelog @ irc.freenode.net. Join in, if you want to have a chat! ;) Lafoobot can presently do very few things

  • "Yoyo", a newly joined user
  • "Hello"/ "Yoyo", a user or pass on a Hello/Yoyo from user to another.
  • Gives Local time / GMT
  • Gives a random word and its meaning [put in for the junta preparing for GRE ;)]
  • Gives out an MOTD or a fortune when it first joins \\#fosskelog
  • Googles a search term and returns the top 5 results (This is my favourite feature and this is the reason partially for this post. "!google lafoobot" doesn't return anything. Hopefully not anymore.)

If you have ideas for any other features or if you want to have a look at the source, comment here or join #fosskelog. lafoobot's code is licensed under GPLv2!

Other than this, the summer has been relatively uneventful but for the two FOSS events I attended. Yes, two events, Sat and Sun, both by Twincling (There are two different Twinclings! Don't ask me why) Hoping to have some more action this summer!

PS: There's a Big discussion presently on whether lafoobot is a he or a she. ;) What do you think?