Feeds:
Posts
Comments

Archive for the ‘Scripts’ Category

With the WA3002G4 wireless router i got recently from my friend i made a wifi hotspot in home. Haven’t been downloading a lot since my script to reboot old teracom router was not working with the new one.Thinking that I should do something on the day which will come only in every four years I modified the old script to work with the new wireless router and I am sharing it here.

#!/usr/bin/env expect

set username admin
set pass admin
set host 192.168.1.1

spawn telnet ${host}

expect -re "Login:"
send "${username}\r"

expect -re "Password:"
send "${pass}\r"

expect -re "Main Menu"
send "13\r"
send "1\r"
expect eof 
Advertisements

Read Full Post »

A script written by Adhil Azeez to generate Indian flag in php. Actually he wanted to share the code here on Independence day. But i was not able to post it that day. After that a series of things happened that prevented me from getting online and updating my blog. So here is the code..

<?php
/*
 * Filename: tricolor.php
 * Dependencies: GD Library mostly precombile with php 4.0+
 * Author: Adhil Azeez NV
 * Description: Generates Indian National Flag Image
 */

//Create a resource identifier for the image res in ration 3:2
$flag = imagecreate(1350, 900); 
if (!$flag) {
    die("Some error occured");
}
//Color identifiers definitions
$white = imagecolorallocate($flag, 255, 255, 255);
$saffron = imagecolorallocate($flag, 255, 153, 51);
$green = imagecolorallocate($flag, 18, 136, 7);
$blue = imagecolorallocate($flag, 00, 0, 137);

//Draw the tricolor sections.The white portion is no need to be specified since
//the background color is white.
imagefilledrectangle($flag, 0, 0, 1350, 300, $saffron);
imagefilledrectangle($flag, 0, 600, 1350, 900, $green);

//Draw the Ashoka Chakra
//The Circle can be created with imageellipse itself after setting the thickness.
//But unfortunetly due to a bug in GD library(reported more than 5 years ago :()
//the thickness is being ignored.
imagefilledellipse($flag, 675, 450, 240, 240, $blue);
imagefilledellipse($flag, 675, 450, 210, 210, $white);

//Draw the center small circle
imagefilledellipse($flag, 675, 450, 42, 42, $blue);

for ($angle = 0; $angle <= 360; $angle = $angle + 15) {

//Draw 24 small circles in the Ashoka Chakra at the border of the circle adjacent
// to 24-spoke
    $x = 675 + 105 * cos(deg2rad($angle+7.5));
    $y = 450 + 105 * sin(deg2rad($angle+7.5));
    imagefilledellipse($flag, $x, $y, 10.5, 10.5, $blue);

//Draw the 24 spooks
    $x1 = 675 + 8 * cos(deg2rad($angle));
    $y1 = 450 + 8 * sin(deg2rad($angle));
    $x2 = $x1 + 40 * cos(deg2rad($angle - 5));
    $y2 = $y1 + 40 * sin(deg2rad($angle - 5));
    $x3 = 675 + 105 * cos(deg2rad($angle));
    $y3 = 450 + 105 * sin(deg2rad($angle));
    $x4 = $x1 + 40 * cos(deg2rad($angle + 5));
    $y4 = $y1 + 40 * sin(deg2rad($angle + 5));
    imagefilledpolygon($flag, array($x1, $y1, $x2, $y2, $x3, $y3,$x4,$y4), 4, $blue);
}
//if the script being invocked from CLI and has a filename arguments then write
//the out put to the file else print to the outputstream.
if (isset($_SERVER['argv'][1])) {
    if(imagejpeg($flag, $_SERVER['argv'][1] . '.jpg', 100))
    	echo "National Flag saved to ".$_SERVER['argv'][1] . '.jpg';
    else
    	echo "Some error occured";
} else {
    header("Content-type: image/jpeg");
    imagejpeg($flag, null, 100);
}
imagedestroy($flag);
?>

Design

The script makes use of php GD library. It outputs the image to current
output stream or save to a file.

If php GD library have anti aliasing support then we can enable that for much
better render.Currently anti aliasing is not enabled in the script.

The output is in JPEG format but it can be changed to other format if necessary
with a few modification in the script.

Dependencies

PHP needs GD Library support. Most of the php distribution compiled with it.

Usage
php flag.php filename

Filename argument is optional. If not present the script will output to the
current output stream

for example:
php flag.php | display
will open the image in ImageMagick picture viewer

Read Full Post »

A slightly edited version of the script to restart router written by Madhusudan.C.S to make it work with teracom router given by bsnl.

#!/usr/bin/env expect

set username admin
set pass admin
set host 192.168.1.1

spawn telnet ${host}

expect -re "Login:"
send "${username}\r"

expect "Password:"
send "${pass}\r"

expect -re "successful"
send "console enable\r"
send "restart\r"
expect eof 

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:
				possible_words.append(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]
		sys.exit()
	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)
reactor.suggestThreadPoolSize(concurrent)


try:
	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
		else:
			actors_rating[actor_name] = 1
	if finished.next()==added:
		reactor.stop()
	
added = 0
for movie in top_100:
	added += 1	
	req = threads.deferToThread(populate_actors, movie.getID())

try:
	reactor.run()
except KeyboardInterrupt:
	reactor.stop()	

   
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
	else:
		count += 1	
	print rank,actor   
    
    

Dependency :
imdbpy

Read Full Post »

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

#!/usr/bin/python
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.

#!/usr/bin/python
#-*- 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
		HTMLParser.__init__(self)
	
	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 
			exit(0)
					


try :
	search_item = sys.argv[1]
except IndexError:
	print " syntax : %s <definiton> " % sys.argv[0]
	exit(1)
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()
	parser.feed(data)
			

Output in my terminal

malayalam meaning

Read Full Post »

Older Posts »

%d bloggers like this: