Blogger Widgets

Search This Blog

Thursday, 10 January 2013

Some Intresting Implimentations using Pygame

                      Pygame is python module designed to writing games. Pygame was written by Pete Shinners and released under open source.It provides excellent GUI so that we can design the games easily rather than text based programmings.

A quick introduction about pygame is available here

Some Interesting Implementations using pygame is explained below
  •         Koch snowflake
  •         Conway's game of life
  •         Sierpinski triangle

Koch snowflake

    Is it possible to think a shape whose area is finite, but the perimeter is infinite?  Yes  ,Koch snow flake is an interesting mathematical curve whose area is converging, But the perimeter is infinite.It is an example of non euclidean geometry. Another property is that the koch curve is continues every where,but not differentiable  any where.

I construct this koch curve using pygame in recursive  fasion. Here I cunstuct a order-1 fractal first, then call that function repeatedly.

My recursive function is 

def koch(screen,order,a):
        if order == 0:
           for angles in [60,-120,60,0]:
           for angles  in [60,-120,60,0]:
               koch(screen, order - 1,a)  

Tuesday, 18 December 2012

OpenCV - Open Computer Vision in Python

                 OpenCV is a library used for real time computer vision.It is open source under BSD License. Here a quick start of OpenCV in python is explained.It is very useful module for robotics , Image processing, Object tracking etc.

We can directly explain a Helloworld example before actually study this - Here we open an image and change its pixel values and save its inverted colour image.
    image                              processed image

import cv2

cv2.namedWindow("Processed Image")

if __name__ == '__main__':
    import sys
    try: image = cv2.imread(sys.argv[1])
    except: image = cv2.imread("lena.jpg")

processedImage = image.copy()

height, width, nColors = processedImage.shape

for y in xrange(height):
    for x in xrange(width):
        B = processedImage.item(y, x, 0)
        G = processedImage.item(y, x, 1)
        R = processedImage.item(y, x, 2)
        processedImage.itemset(y, x, 0, 255 - B)
        processedImage.itemset(y, x, 1, 255 - G)
        processedImage.itemset(y, x, 2, 255 - R)

cv2.imshow("Image", image)
cv2.imshow("Processed Image", processedImage)


                    Where we first import opencv module and create two windows for image and processed image. And copy the given image to a variable named  "processedImage".Then we access its parameters height, width. The color of all pixels are inverted using for loop by accessing individual pixel informations.Then shows both the image.

Monday, 17 December 2012


Here I just gives a brief introduction for AVR programming in Linux. I'm using ubuntu 11.10 . Finally we can able to blink an LED( Hello world program). Here I'm uses ATMEGA8 and usbasp programmer.

Step1 : Install the tool chains required for AVR programming
  •           sudo apt-get install gcc-avr
  •           sudo apt-get install avrdude
  •           sudo apt-get install libc

Step2 : Next step is to write an Hello world program - Here it is to just
            blink an LED .save this as led.c
                      DDRB = 0xff;
                      PORTB = 0xff;
                    Where <avr/io.h> is the header file for AVR programming.DDRB is the data direction register of PORTB, by writing 0xff we set this as output port.Then we write PORTB = 0xff it will set PORTB (8pins) to HIGH.

Step3 : Here we want to compile the program and make it hex code . for that  use the following steps.
  •           convert led.c to the object file led.o
                 avr-gcc -mmcu=atmega8  led.c -o led.o
                 some times we need to optimize the code
                 avr-gcc -mmcu=atmega8 -Os led.c -o led.o

  •           then convert the object file to hex file
                 avr-objcopy -j .text -j .data -O ihex  led.o  led.hex

 Step3 : Connect the usbasp programmer to the usb of the lap top
usbasp programmer

usbasp - development board
Step 4: To burn the hex code in to the ATMEGA8 connect the development  board to usb-asp. Then connect to the usb of the laptop .Connect a LED with a resistor to PORTB. Then run the following command
  • sudo avrdude -c usbasp -p m8 -U flash:w:led.hex:a 

you can see that the led connected to portB is blinking

some more avr-programming codes are adde in my github

Wednesday, 12 December 2012

Weather App using Tornado

Tornado is a scalable, non-blocking web server and web application framework. It was developed by FriendFeed.The framework is distinct from most mainstream web server frameworks (and certainly most Python frameworks) 
because it is non-blocking and reasonably fast.

Starting with Tornado

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/", MainHandler),

if __name__ == "__main__":

Run this code using python and go to http://www.localhost:8888 will print 
"Hello, world" in firefox.

How we have done it ? 

The problem is to create a weather app using tornado frame work.For this we need to fetch the live whether data.I'm using to fetch climate data. I'm uses urllib library to get weather data from the weather server. And converted it to dict format using ast module in python. Then filter the required data(Temperature, Humidity, Pressure) from dict. Up to this first section of the project is completed.

Now I want to create a template

I'm create template in html . Now we need to put weather data's  (Temperature , Humidity, Pressure) in template. For integrating this values I'm uses jinja2 .

Main code for weather app

Created on 12-Dec-2012
@author: unais

This is the main program for the weather app

weather server used :

Here urllib is used to fetch climate data from

"jinja2" template engine is used to render html pages with tornado

Template is saved in /template/weather.html

we can give different city names in plase of "Palakkad" for getting weather datas of different citys
import urllib2
import ast
import tornado.ioloop
import tornado.web
import jinja2
import os

jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + "/templates"))

def getWeatherCondition(city) :
    try :
        url = ""
        url += city
        req = urllib2.Request(url)
    except Exception :
        print("Not a matched city")

def print_weather(place):
    Data_str =  getWeatherCondition(place)
    Data = ast.literal_eval(Data_str) # converting string to dict type
    Temperature =  Data['list'][0]['main']['temp']
    Humidity    =  Data['list'][0]['main']['humidity']
    Pressure    =  Data['list'][0]['main']['pressure']
    Result      =  place , Temperature , Humidity , Pressure
    return Result
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        weather_data = print_weather("Palakkad") # by changing the name we get the weather datas of different city's
        template_values = { 'place':weather_data[0], 'temperature': str(weather_data[1] -272.15), 'humidity': str(weather_data[2]), 'pressure': str(weather_data[3])}
        template = jinja_environment.get_template('weather.html')

application = tornado.web.Application([
    (r"/", MainHandler),

if __name__ == "__main__":

HTML code for template

<!DOCTYPE html>
<div style="width:450px;height:250px;border:1px solid #000;background-color:LightBlue;">
 <img border="0" src="sun.png" style="float:right; margin:20px 20px 15px 15px;border:0" alt=" " width="150" height="150">


<font size="8"><b>  {{temperature}}<sup>o</sup>C</b> </font>

<font size= "4"><b>   Humidity : {{humidity}}%</font></b>
<font size= "4"><b>   Pressure : {{pressure}} mbar</font></b>   

where we need create folder templates and save the above html file as weather.html

and run the python code
then go to http://localhost:8888 we can see like

 The complete code Click Here

Sunday, 30 September 2012

Basics of R : Statistical Programming Language for Data Analysis

                  R is a free software environment for statistical computing and graphics.It is an integrated suite of software facilities for data manipulation, calculation and graphical display. It has
  •  an effective data handling and storage facility,
  •  a suite of operators for calculations on arrays, in particular matrices,
  •  a large, coherent, integrated collection of intermediate tools for data  analysis,
  • graphical facilities for data analysis and display either directly at the computer or on hardcopy, and a well developed, simple and effective programming language (called ‘S’) which includesconditionals, loops, user defined recursive functions and input and output facilities.

       R is helpful when you dealing with data's of large size, for eg: Analyzing the amount of air contents of different countries  during one year (This data may contain numerical data's more than 3 GB) using classical methods may take days for its computation and analysis. But by using the simple coding by R language we can analyze it within minutes.

Saturday, 11 August 2012

Reverse Polish Calculator in C

                   Recently while done the exercises from KNR, I got an interesting excersise for calculator,..It is Reverse polish calculator. The major advantage of this is that this method saves our time, becouse here we can write a mathematical expression without using parentheses and brackets.
                 Here you never have to account for the parentheses while doing calculations. The process is similar to the way you learned math on paper. You can see the intermediary results as you perform your computations rather than just the answer at the end. This is an extremely helpful byproduct. Math teachers are using this feature to improve student understanding of mathematics. An intermediate result allows the user to check the results and correct errors more easily. It's easier to follow the stream of calculation. The user defines the priority of operators. RPN is logical because the user first gives the number and then tells what to do with it.

                     for eg : 
                       The reverse polish notation of (1 - 2) * (4 + 5) this
                        is entered as ----         1 2 - 4 5 + *

Saturday, 28 July 2012

Some tricky programs from KNR

Qn : 1 --   Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.
Explanation about the question :--                                 
xxx...xxxa....aax..xx and
_____________________    and the result will be

  for eg:
if     x =    10110101
and y =    10111010

and we want to find setbits(x,4,3,y)

then we want to replace  x =    10110101 the underlined bits to the last three bits of y.

ie the result must be x =    10101001

Blogger Widgets