Archive for the ‘Python’ Category

While i was working on the project onspot_v2, i came across with a specific need. onspot_v2 makes use of the django admin interface for data entry. When employees are entering data, ‘branch’ field in the form will get populated automatically as per the branch of the employee. When a manager is entering data using the form, an extra field should appear to select the ‘branch’ instead of automatically populating. Googling didn’t help much. Finally i thought of overriding the ModelAdmin.add_view() method which is invoked when you try to add an entry using the admin. I changed the editable property of the field ‘branch’ inside after checking the request.user and it worked out. Part of my code in admin.py

from django.contrib import admin
from books.models import Agent, PolicyIssue

class PolicyIssueAdmin(admin.ModelAdmin):
    def add_view(self, request, form_url='', extra_context=None):
        if request.user.get_profile().is_employee:
            self.model.branch.field.editable = False
            self.model.branch.field.editable = True
        return super(PolicyIssueAdmin, self).add_view(request, form_url)

admin.site.register(PolicyIssue, PolicyIssueAdmin)

Read Full Post »

Here is a python script to find solution for a jumbled word. Give a jumbled word as parameter, it will list the possible solutions.

import sys

dictfile = "/usr/share/dict/cracklib-small"

def get_words(text):
	""" Return a list of dict words """
	return text.split()

def get_possible_words(words,jword):
	""" Return a list of possible solutions """
	possible_words = []
	jword_length = len(jword)
	for word in words:
		jumbled_word = jword
		if len(word) == jword_length:
			letters = list(word)
			for letter in letters:
				if jumbled_word.find(letter) != -1:
					jumbled_word = jumbled_word.replace(letter,'',1)
			if not jumbled_word:
	return possible_words		
if __name__ == '__main__':
	words = get_words(file(dictfile).read())
	if len(sys.argv) != 2:
		print "python %s <jumbled word>" % sys.argv[0]
	jumbled_word = sys.argv[1]
	words = get_possible_words(words,jumbled_word)
	print "possible words :"
	print '\n'.join(words)

Don’t forget to change the ‘dictfile’ to the wordslist file you have in your system.

Here is the screenshot of script output.

Read Full Post »

Actually this is a sample question appeared in codejam contest conducted by mobme wireless. Imdbpy python module is used to retrieve movie informations from imdb.

For those who don’t know about this event : http://codejam.mobme.in/

Sample Question :

Write a program that ranks Hollywood actors based on the number of their appearances in a list of top 100 movies. There are a number of top movie lists on the Internet and it’s up to you to choose one. We’d prefer you choose one that has an open API.

Solution in Python :

#!/usr/bin/env python

__author__ = "Rag Sagar.V"
__email__ = '@'.join(['ragsagar','.'.join([_ for _ in ['gmail','com']])])

from twisted.internet import reactor, threads
import re,imdb,itertools

actors_rating = {} #actors_rating['actor name'] = rank
rank = 0
count = 1
current_rank = 0
concurrent = 5
finished = itertools.count(1)

	imdb_access = imdb.IMDb()
except imdb.IMDbError, err:
	print err
top_100 = imdb_access.get_top250_movies()[:100]

def populate_actors(mid):
	movie = imdb_access.get_movie(int(mid))
	#print movie
	for i in (0,1):
		actor_name =  movie['cast'][i]['name']
		if actors_rating.has_key(actor_name):
			actors_rating[actor_name] = actors_rating[actor_name] + 1
			actors_rating[actor_name] = 1
	if finished.next()==added:
added = 0
for movie in top_100:
	added += 1	
	req = threads.deferToThread(populate_actors, movie.getID())

except KeyboardInterrupt:

for actor in sorted(actors_rating, key=actors_rating.get, reverse=True):
	previous_rank = current_rank
	current_rank = actors_rating[actor]
	if previous_rank !=  current_rank :
		rank += count
		count = 1
		count += 1	
	print rank,actor   

Dependency :

Read Full Post »

Here is a python script to wish you Good Morning or Good Evening according to the time of the day.

import time

current_hour = time.strptime(time.ctime(time.time())).tm_hour

if current_hour < 12 :
	print "Good Morning!"
elif current_hour == 12 :
	print "Good Noon!"
elif current_hour > 12 and current_hour < 18 :
	print "Good AfterNoon!"
elif current_hour >= 18 :
	print "Good Evening!"

Now if you want to display it when you open the console add the following line to your ~/.bashrc file.

python /path/to/the/script.py

Happy Hacking! 🙂

Read Full Post »

This time its the script to fetch the malayalam meanings of english words from malayalam wiktionary.

#-*- coding: utf-8 -*-
# https://ragsagar.wordpress.com

from HTMLParser import HTMLParser
import urllib2,sys

class Parser(HTMLParser):
	def __init__(self):
		self.in_header = False
		self.in_definition = False
	def handle_starttag(self, tag, attrs):
		if tag == 'li':
			self.in_header = True
		if tag == 'a' and self.in_header :
			self.in_definition = True
	def handle_endtag(self, tag):
	    	if tag == 'li':
			self.in_header = False
		if tag == 'a' :
			self.in_defintion = False
	def handle_data(self, data):
		if self.in_definition:
			print data 

try :
	search_item = sys.argv[1]
except IndexError:
	print " syntax : %s <definiton> " % sys.argv[0]
search_link = "http://ml.wiktionary.org/w/index.php?title=%s&printable=yes" % (urllib2.quote(search_item.encode('utf-8')))

request = urllib2.Request(search_link)
request.add_header('User-agent', 'Mozilla/5.0 (hb)')
try :
	response = urllib2.urlopen(request)
except urllib2.HTTPError :
	print "No definition found "
except urllib2.URLError :
	print "Unable to connect to internet "
else :
	parser = Parser()
	data = response.read()

Output in my terminal

malayalam meaning

Read Full Post »

Atlast i came up with a real rhythmbox plugin for setting the status message in pidgin as the current song title playing in Rhythmbox music player .I wrote it a few month before and was using it. Thought of sharing it before but didnt get time. Actually i forgot about my blog when i started microblogging. From now onwards i will be updating this blog regularly.( this is what i wanted to do always 😀 )

Download the plugin from here : http://ragsagar.freehostia.com/rb-nowplaying.tar.gz
To install it.
1) Extract the tarball.
2) Copy it to ~/.gnome2/rhythmbox/plugins/ (if no such directories exists, create them)
3) Open rhythmbox. Edit -> Plugins
4) Check ‘Now Playing Pidgin’

That’s it. If you are facing any problems do comment.

Read Full Post »

About Infix and Postfix

In an expression if the operators are placed between the operands, it is known as infix notation ( eg A+B) . On the other hand if the operators are placed after the operands then the expression is in postfix notation .( eg AB+)

Infix Notation                            Postfix Notation

(A-C)*B                                              AC-B*

A+(B*C)                                            ABC*+

(A+B)/(C-D)                                      AB+CD-/



postfix = []
temp = []
operator = -10
operand = -20
leftparentheses = -30
rightparentheses = -40
empty = -50

def precedence(s):
	if s is '(':
		return 0
	elif s is '+' or '-':
		return 1
	elif s is '*' or '/' or '%':
		return 2
		return 99 
def typeof(s):
	if s is '(':
		return leftparentheses
	elif s is ')':
		return rightparentheses
	elif s is '+' or s is '-' or s is '*' or s is '%' or s is '/':
		return operator
	elif s is ' ':
		return empty	
	else :
		return operand							

infix = raw_input("Enter the infix notation : ")
for i in infix :
	type = typeof(i)
	if type is leftparentheses :
	elif type is rightparentheses :
		next = temp.pop()
		while next is not '(':
			next = temp.pop()
	elif type is operand:
	elif type is operator:
		p = precedence(i)
		while len(temp) is not 0 and p <= precedence(temp[-1]) :
	elif type is empty:
while len(temp) > 0 :
print "It's postfix notation is ",''.join(postfix)		

Code Explanation

Above code converts infix notation in variable infix into postfix notation and stores in postfix list. This algorithm makes use of list temp to hold operators and left parantheses in the infix notation. The postfix list will be constructed from left to right using operands from infix and operators which are removed from temp.



Read Full Post »

Older Posts »

%d bloggers like this: