vishnusathyanesan

A Small Note On Scheme:-

I got a chance to read the famous text book of Structure and Interpretation of Programs (SICP)written by Harold Abelson and Gerald Jay Sussman. They are professors of Massachusetts Institute of Technology (MIT). This book contain everything about the functional programming language –Scheme. Scheme is one of the two main dialects of the programming language Lisp. At First I felt some difficulty to learn but later I realized that it was too good to learn and was rather interesting too. This book helps us to learn modular programming.

I read the first chapter of  SICP and have also done some exercises. Let us start from the basics of  Scheme. To start we need a mit-scheme interpreter , it can be installed by using this command sudo apt-get install mit-scheme.

We can take mit-scheme interpreter by just typing mit-scheme in terminal and it will look like this.

Scheme uses prefix notation and the basic arithmetic operations will look like this.


Here the things are named by using define for example

1]=> (define numb 4)

Then the value of numb will be 4.

Compound Procedures:

Compound operation can be given name and then referred to as unit. For example

1]=>(define (square x) (* x x))

This means that

The general form of procedure definition is

(define (<name> <formal parameters>) <body>)

We can use defined square to find square of a number. For example

1]=> (square 2)

;value:  4

Conditional Expressions:

Conditional expressions are of the form

(cond (<p1> <e1>)
       (<p2> <e2>)
       
       (<pn> <en>))
For example to find the absolute value of a number by using
conditional expression.
1]=>(define (abs x)
   (cond ((< x 0) (- x))
         (else x)))

The above code defines that if (x < 0) then the value of x will be -x
otherwise the value of x will be x.
After defining this we can find the absolute value by just giving
(abs -4).
Logical operations like and, or, not are also there in scheme.
The general form of these are
(and <exp1> … <expn>)
(or <exp1> … <expn>)
(not <exp>)

Procedures:
Procedures in Scheme are first class, meaning that they can be
passed as arguments,bound to variables and returned as values from
other procedures. Arguments are passed by value.

Linear Recursion and Iteration:

We can take an example to study about recursion and iteration.
The best example is that to find factorial of a number.

(define (factorial n)
   (if (= n 1)
       1
      (* n (factorial (- n 1)))))

The above code shows how to find factorial of a number by recursion.

(define (factorial n)
  (fact-iter 1 1 n))

(define (fact-iter product counter max-count)
  (if (> counter max-count)
       product
     (fact-iter (* counter product)
                 (+ counter 1)
                  max-count)))

The above code shows how to find factorial of a number by iterative method.

The codes of exercises that I have done is available here .

My Paint Application Using JavaScript ,CSS, HTML5

This is  one of my  favourite web application to implement paint  by using JavaScript, Css, HTML5. This  application mainly contains 3 tools  such as pencil,eraser and rectangle and also  8 beautiful colours. Here  css  make my application more beautiful and user friendly.  First step to make this application is that to make a drawing space by using html5 canvas.I have explained how to create html5 canvas in my earlier post related  canvas (html5 canvas). The next step is that to create a pencil tool. For this I want to draw when mouse drag occurs.  Take this mouse drag as the combination of 3 events in javascript and that 3 events are mousedown, mousemove and mouseup. For rectangle also these 3 events are used.

For  the above  3 events i am using 3 canvas event listeners to listen and the below code shows this.

canvas.addEventListener('mousedown', mousepoint, false);
canvas.addEventListener('mousemove', mousepoint, false);
canvas.addEventListener('mouseup',   mousepoint, false);

When mouse down event and mouse move event occurs the pencil tool will draw and when mouse up event occurs the drawing process will stop.The below code shows this mousedown,mousemove and mouseup functions.

this.mousedown = function (e) {
context.beginPath();
context.strokeStyle=color;
context.lineJoin='round';
context.lineWidth=size;
context.moveTo(e._x, e._y);
tool.started = true;

};
this.mousemove = function (e) {
if (tool.started) {
context.lineTo(e._x, e._y);
if(pen==1&&rectan==0){
context.stroke();
}
}
};
this.mouseup = function (e) {
if (tool.started) {
tool.mousemove(e);
tool.started = false;
}
};

The mouse point function returns the mouse positions on these 3 events. The below code shows how to take mouse positions.

function mousepoint (e) {
if (e.layerX || e.layerX == 0) {
e._x = e.layerX;
e._y = e.layerY;
} else if (e.offsetX || e.offsetX == 0) {
e._x = e.offsetX;
e._y = e.offsetY;
}
var func = tool[e.type];
if (func) {
func(e);
}
}

The next is that to make an eraser. It is very simple and tricky. Eraser tool can be make by giving the colour of pencil tool as white. For this when the tool eraser takes then the eraser function calls the pencil function with colour white as its parameter  and the pencil tool itself will act as an eraser. The below code shows this.

function eraser(){
tool = new pencil(color='white');
}

The next is to add colours. This is also very simple. To add colours i give buttons for each colour and each button calls corresponding functions and each function returns colours. The below code shows an example of this.

function red(){
return color='red';
}

The above function will runs when red button press.
I am hosted my paint application in Google’s App Engine and you can run my application here .
My paint application codes are available here .

Conway’s Game Of Life :- My Own Javascript Implementation

Conway’s Game Of Life is a zero player game. That means its evolution is determined by its initial state. It consist of a cellular automation following four rules which where deserved by John Conway. The world in which the evolution of those cells takes place is an infinite two dimensional grid. Each cells either dead or alive and each cell has exactly eight neighbours. The states dead or alive is depending upon the neighbours state.

The Four rules are:

  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

I am here using html 5 canvas and javascript for the implementation of Conway’s Game Of Life. At first i am try to make a two dimensional grid by using javascript and i have done it. The below code shows how to draw grids by using html5 canvas and javascript.

function renderGrid(){
var i=0;
var j=0;
context.save();
context.lineWidth = 0.5;
context.strokeStyle = "red";
for(i = 0; i <= canvas.height; i = i + 10){
context.beginPath();
context.moveTo(0, i);
context.lineTo(canvas.width, i);
context.closePath();
context.stroke();
}
for(j = 0; j <= canvas.width; j = j + 10){
context.beginPath();
context.moveTo(j, 0);
context.lineTo(j, canvas.height);
context.closePath();
context.stroke();
}
}

I assign that the whole grid is as a two dimensional array and the values of that array as zero initially.Next step is to give life to some random cells. For this i am using an inbuilt math function Math.random() .After this i give value 1 to all the random life cells in the array.It helps to implement the four rules.The code below shows this.

for(i=-1;i<51;++i){
cell[i]=new Array();
for(j=-1;j<51;++j){
cell[i][j]=0;
}
}
function randomcell(){
for(var i=0;i<1000;++i){
xval=Math.floor((Math.random()*50)+0);
yval=Math.floor((Math.random()*50)+0);
cell[xval][yval]=1;
colouring(xval,yval,0);
}

}

Then i have applied the rules and give blue colour to the living cells and give white colour to dead cells.The colouring code is shown below

function colouring(i,j,x){
if(x==0){
context.fillStyle = 'blue';
context.fillRect(i*10,j*10, 9,9);
}
else if(x==1){
context.fillStyle = 'white';
context.fillRect(i*10,j*10, 9,9);
}

}

Here the value of x is that if the cell is dead then the value of x will be 1 and if the cell is alive then the value of x is 0. This is decided by using the four rules. You can access my full code from here .

You can also run my application from here .

My Views About Python Flask:-

Flask is a light weight Python web framework that steadily increasing popularity in web development world. It is simple to use and easy to understand. I like this python flask very much and it surprises too.I have taken the project(url shortening) that i have done earlier by using Python and Google’s App Engine to learn python-flask. Flask is based on Werkzeug WSGI toolkit and Jinja2 template engine.

Flask means that simple task should be simple. That means flask should not take a lot of code and it should not limit us. It is very simple than other web frameworks. Flask uses thread local objects internally so we don’t have to pass objects around the function to function within a request in order to stay thread safe. It is really an easy approach and saves lot of time. The main reason Flask is called a micro framework is the idea to keep the core simple but extensible. In Flask there are different libraries to handle database abstraction layer, form validation etc. flask protects against from one of the most common security problems of modern web applications: cross-site scripting(xss).

Installation:

We can easily install python-flask from synaptic package manager or by simply typing the command sudo apt-get install python-flask .

For example we can have a look on a simple Flask minimal application.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

Save the above code as new.py at this time make sure that not to call our application as flask.py because this would conflict with Flask itself. This is the basic hello world application in python-flask.Now we can run this simple application by giving python new.py.The application run on the python-flask server and it looks like this

The below code shows how to render templates in python-flask.
@app.route('/')

def home_page(name=None):

       return render_template('main.html',name=name)

More documentation and examples of python-flask are  available from here .

My own python-flask application codes available here .

HTML5 CANVAS:- A Simple Reference

One of my favorite feature in HTML5 is Canvas element.The canvas element is a part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images. It is a low level, procedural model that updates a bit map and does not have a built-in scene graph.HTML 5 Canvas is a Drawable region defined in html code with height and width attributes.By using JavaScript we can draw on canvas.

A Canvas is specified with the <canvas> element.The following code creates a Canvas element with width 200 and height 200 in an HTML page.

<html>
<body>
<canvas id="example" width="200" height="200" style="border: <span class=;" hiddenspellerror="" pre="">4px solid black;"></canvas>
</body>
</html>

The Canvas will look like this:

 

Draw With JavaScript:

To draw a red rectangle on this canvas we want to use javascript.

For example:


var example = document.getElementById('example');
 var context = example.getContext('2d');
 context.fillStyle = 'red';
 context.fillRect(30, 30, 50, 50);

The rectangle filled with red color in the canvas will look like this

Like this canvas has several methods for drawing circle, characters, paths, and adding images.


var example = document.getElementById('example');

This line defines that the JavaScript uses id to find the <canvas> element.
After this then create a context object and this is shown in the below line.

 var context = example.getContext('2d');

The next two lines draw the red rectangle.

 context.fillStyle = 'red';
 context.fillRect(30, 30, 50, 50);

For more examples on HTML5 Canvas click here

Graph Coloring Application

This is my second web application and this application is an implementation of graph coloring problem by using HTML Canvas. Here i am using Google App Engine to run my application. I have explained about it in my earlier post  Google App Engine. My application contains server side and client side. Client side handles the request from user and server side respond to the user request. Both of the server program and client program are written in javascript. Client program uses HTML5 CANVAS to draw and color graph. Client program sends the adjacency list to the server program by using jquery and server program generates colour list by using that adjacency list. This colour list will send back to the client.

HTML5 CANVAS:

HTML5 CANVAS is used to draw the graph in my graph coloring application. HTML5 CANVAS is a very useful to draw graphics. It uses javascript. A canvas is a drawable region defined in HTML code with height and width attributes.Here i am using a Canvas of width=1000 and height=450.

<canvas id="myCanvas" width="1000" height="450" style="border:8px solid red;"></canvas>

This defines that a square shaped Canvas of id “myCanvas” with a width and height of 1000 and 450 respectively with a red border. We can access this by using javascript.
The Canvas element has no drawing ability of its own. So it is done by using javascript. The javasctipt uses id to find Canvas element.
For example:

var c= document.getElementById("myCanvas");

Then the javascript create a context object.
For example:

var cxt = c.getContext("2d");

The getContext(“2d”) is a built in HTML5 object and it help us to draw rectangles,squares,circles etc.

Java Script:

Here javascript is using to Draw elements in Canvas.I take first the mouse position to draw nodes and lines. Double click is used to draw nodes and single click is used to draw lines.

function getCursorPosition(e)
 {
 var x;
 var y;
 if (e.pageX != undefined && e.pageY != undefined)
 {
 x = e.pageX;
 y = e.pageY;
 }
 else
 {
 x = e.clientX + document.body.scrollLeft +
 document.documentElement.scrollLeft;
 y = e.clientY + document.body.scrollTop +
 document.documentElement.scrollTop;

}
 x -= c.offsetLeft;
 y -= c.offsetTop;
 var cell = new Cell(x,y);
 return cell;
 }

The above code gives the both x and y as the co-ordinates of mouse and it will help to draw nodes and lines. In my program i take these drawing node and line as two events and i am using two event listeners. They are

c.addEventListener("dblclick", halmaOnClick, false);

When Double click is done this event will call the function “halmOnClick” and it draws a node.

function halmaOnClick(e)
 {

cell = getCursorPosition(e);
 cxt.fillStyle="#000000";
 cxt.beginPath();
 cxt.arc(cell.x,cell.y,15,0,Math.PI*2,true);
 cxt.closePath();
 cxt.fill();
 cxt.font = "10pt Calibri";
 cxt.fillStyle = "#0000ff";
 cxt.fillText(l,cell.x + 6, cell.y-12);
 list.push(l);
 l = l+1;
 elm.push(cell);
 }

This is the function that draws the nodes.

c.addEventListener("click", line, false);

When single click is done this event will call the function “click” and draw lines.

function line(e)
 {
 if (click== 0)
 {
 cell = getCursorPosition(e);
 x1 = cell.x;
 y1 = cell.y;
 cxt.beginPath();
 cxt.moveTo(x1,y1);
 click = 1;
 points(x1,y1);
 }
 else
 {
 cell = getCursorPosition(e);
 x2=cell.x;
 y2= cell.y;
 cxt.lineTo(x2,y2);
 cxt.stroke();
 click = 0;
 points(x2,y2);
 }
 }

This is the function that draws lines.

jQuery:

I am using JQuery to send adjacency list and receive colour list. The sending of adjacency list to the server is by using the .get method in jquery.

$(document).ready(function(){
 $("#colouring").click(function(){
 $.get("http://localhost:8080/sign",{adj:JSON.stringify(adj)}, function(response){
 res(response);

});
 });

The above code is used to send the adjacency list and receive colour list by using jquery. The adjacency list is send by the jquery in the form of a JSON object.
The compleate code of my application can be take from here.
To launch my application click  here .

My Web Application- URL SHORTENER

Now a days Web Applications are familiar to everyone. Everyone can access the application from any where , at any time and do there jobs at any time. Here my Web Application is a URL SHORTENER. It is used to make longest URLs short. And here i am using Google’s App Engine. Google App Engine is reliable because our application run in a secure environment.  I am also using python libraries in my application.

The front end of my application is a HTML page and the back end is using python. The HTML page contains a box to enter the URL and a short button to submit the URL. Then the python program runs in the back end and the python program takes the URL by using self.request.get() function. And gives back shortened URL as output to the HTML page. My URL shortening application contains four files they are

  1. app.yaml
  2. main.html
  3. main.py
  4. index.html
  • The app.yaml file is the configuration file.
  • The main.html file contains the application the home page.
  • The main.py contains the python program to shorten URL.
  • The index.html file is auto generated and it is automatically updated whenever the dev_appserver detects that new type of  query is run.

My Web Application using the Webapp framework and it contains 3 parts and they ar

  • One or more Request handlers.

* Class main Renders the main HTML page.


class Short(webapp.RequestHandler):
  def post(self):
  match=re.search('[(www.)(http//:)]\S+',self.request.get('orgurl'))
  if match:
     url= self.request.get('orgurl')
     match= re.search("(http://)(\S+)",url)
     if match:
        url=match.group(2)
     else:
        url = "http://" + url
     match = re.search("\.(\w+).",url)
     if match:
        list = match.group(1)
        new="vn"+list[0]+list[-1]+str(random.randrange(100,1000))
        sho = db.GqlQuery("SELECT * FROM Shorten WHERE url =:1",url)
        results= sho.fetch(2)
        if results:
           for result in results:
               match = re.search("http",result.url)
               if not match:
                      result.url = 'http://'+result.url
               linkurl='<a href=%s>http://urlshvishnu.appspot.com/%s</a>'%(result.url,result.shurl)
        else:
            dbobject = Shorten()
            dbobject.url=url
            dbobject.shurl=new
            dbobject.put()
            match=re.search("http",url)
            if not match:
               url = 'http://'+url
               linkurl='<a href=%s>http://urlshvishnu.appspot.com/%s</a>'%(url,dbobject.shurl)
            else:
               linkurl='<a href=%s>http://urlshvishnu.appspot.com/%s</a>'%(url,dbobject.shurl)
               self.response.out.write('<body background="images/vvv.gif"><body style="background-color:lightblue;"><h1><i><b>SHORTEND URL:<blink>%s</blink></i></b></h1>'%(linkurl))
     else:
         linkurl = '<body background="images/vvv.gif"><body style="background-color:lightblue;"><h1><i><h1 style="text-align:center;"><b><blink>ENTER A VALID URL</blink></i></b></h1><img src="images/error.jpg">'
         self.response.out.write(linkurl)

  else:
      linkurl =' <body background="images/vvv.gif"><body style="background-color:lightblue;"><h1><i><h1 style="text-align:center;"><b><blink>ENTER A VALID URL</blink></i></b></h1><img src="images/error.jpg">'
      self.response.out.write(linkurl)

* Class Short contains the main python program to shorten URL. Here using python’s special libraries.

* Class Shorten is a Database Model and it stores both original URL and Shortened URL. Original URL in url and Shortened URL in shurl.

  • A WSGI Application instance that routes incoming requests to handlers based on the URLs.

* This code defines 3 request handlers 1:main mapped to root URL ‘/’, 2: Short mapped to ‘/html’ and 3: redirectin mapped to ‘/vn’.

  • A main routine that runs the WSGI Application using a CGI adaptor.

* The function run_wsgi_app(application) takes a WSGIApplication instance and runs it in App Engines CGI environment.

GOOGLE APP ENGINE

Google App Engine:

Google App Engine is a platform for developing and hosting web applications in Google managed data centers. We can create web applications and host it by using Google App engine. It supports 3 languages Python , Java and Go. App Engine applications are easy to build, easy to maintain easy to scale as your traffic and data storage needs grow. We can share our application with the world. We can serve our application by using a free name on the appspot.com domain. (example: urlshvishnu.appspot.com).

Features:

  • Dynamic web serving, with full support for common web technologies
  • Persistent storage with queries, sorting and transactions
  • Automatic scaling and load balancing
  • APIs for authenticating users and sending email using Google Accounts
  • A fully featured local development environment that simulates Google App Engine on your computer
  • Task queues for performing work outside of the scope of a web request
  • Scheduled tasks for triggering events at specified times and regular intervals

Google App Engine in Python Environment:

We can implement our application using python programming language with App Engine’s python runtime environment and we can also run it on an optimized python interpreter. It uses python versions 2.5.2 by default and it also choose the experimental python 2.7.2 runtime.Python environment includes the standard library. App Engine includes rich API s for the Datastore , Google Accounts, URL Fetch and Email services. App Engine also provides a simple python web application framework called webapp to make it easy to start web applications. To make the web applications and to upload we need to download the App Engine SDK for python environment.

In Google App Engine here we uses two commands from SDK.They are

  •  dev_appserver.py  ———- The development webserver.
  • appcfg.py —————– For uploading and updating our applications to App Engine.

Here the App Engine applications communicates with the webserver using the CGI standard.

Implementing Applications:

step 1: Create a directory.

step 2: Inside the directory create a python file that contains our application program.

step 3: create a configuration file called app.yaml

After all these we need to test our application.

To test the application

  • python google_appengine/dev_appserver.py  (filename)/

Now we can see that the webserver is running. We can test the application by visiting the URL http://localhost:8080/.

We can modify the application while the webserver is running.To see the changes we have done while running just reload that page.

To shutdown the webserver press ctrl+c.

To upload our application

  • python  appcfg.py  filename/

To update the application

  • python  appcfg.py  update filename/

For Example of an application with App Engine:

  • Create a directory named helloworld
  • Create a python file named helloworld.py with following contents.
 print 'Content-Type: text/plain'
 print '' 
 print 'Hello, world!'
  • Then create a file named app.yaml with following contents.
 application: helloworld
 version: 1 
 runtime: python
 api_version: 1

 handlers:
 - url: /.*
 script: helloworld.py
  1. Here helloworld is the application identifier  and we select a unique identifier when we register  our application with App Engine.
  2. The version number 1 of this is application code.
  3. Runtime and api version shows that code runs in the python environment, version 1.
  4. -url : /.*   Shows that every request to a URL whose path matches the regular expression /.*(all URLs) should be handled by the helloworld.py script.

Now we want to upload this application by this command python appcfg.py helloworld/ .


						
					

Dictionaries and Files

Dictionary:

Python’s key or value hash table structure is called a “dict”. The structure of dict looks like this ” dict = {key1:value1, key2:value2, …}”. The empty dictionary can be make by giving “dict={}”. Dictionary is a very useful method in python.

  • dict can be build up by starting with empty string…….
  • For example of making a dict,

$ dict={}

         $ dict[‘a’]=’alpha’ —— # here ‘a’ is the key and ‘alpha’ is the value.

         $ dict[‘o’]=’omega’

         $ print dict  ——-# prints the dictionary like this… { ‘a’ : ‘alpha’, ‘o’ : ‘omega’ }

dict with keys 'a' 'o' 'g'

  • We can print the values of a dict by ” print dict.values()
  • We can also print keys by ” print dict.keys()”
  • We cannot create a duplicate key in dict but we can create multiple values to a key.
  • We can get the value of a key by “ dict.get(‘name of key’)” ——– # Returns if key is present else returns nothing.
  • We can check if there key is present or not by ….

$  ‘a’ in dict —– #if a is present then it returns ‘true’ otherwise returns ‘false’

Note: The elements in a dictionary is not in a sorted order but we can sort this in the basis of keys and values.

  • We can sort the dictionary by……

$ for key in sorted(dict.keys()):

$    print key, dict[key]  # Prints the keys and its corresponding value in sorted order.

Files:

File input or output in c/c++ requires several header files and defining a series of streams or file objects. Python is similar to that but it is simpler.

Opening a file in read and write mode:

  • Open a file in read mode ” f = open( ‘file.txt’ , ‘r’ ) “. —# opens file ‘file.txt’ into a variable f.
  • Open a file in write mode ” f = open(‘ file.txt ‘ , ‘w’) “.
  • We can also use ‘a’ instead of ‘w’ or ‘r’ to append. ” f = open( ‘ file.txt ‘ , ‘ a ‘) “
  • When finished use f.close().
  • We can read the lines in a file to a list by lines = f.readlines(). —– read the lines to the list ‘lines’.
  • We can also read the entire file to a string by text = f.read() ——- reads the entire file contents into the string ‘text’

						
					

Linux Tips

1:Automount NTFS drivers in ubuntu:

>>It’s simple no need to edit fstab.
>>Just install ntfs-config.
>>To install ntf.s-config sudo apt-get install ntfs-config
>>Then take System->Administration->NTFS configuration tool.
>> Then type password and tick both boxes.
>> ……..Finished……..

2:Configuring sudo password:
>>Type sudo passwd in terminal it shows to
Enter new UNIX password:(type your new password)
Retype new UNIX password:(retype your password)
>>It sets your new password.. Now you can enter root by simply typing su in terminal…

3: To Establish Connection Between to Computers with lan cables:

  • Take Connection manager.
  • Then take Edit connections.
  • Then Edit the auto eth0 if exists in wired connection.
  • If not add new. There should give the mac address this will get by typing ifconfig in the terminal.
  • Then take IPV4 settings
  • Change the method to manual
  • Then edit the address netmask and gateway for example give addrs: 192.168.2.8 netmask 255.255.255.0 gatteway: 192.168.2.0
  • Then save the changes and now you got connection established.

4: Data Transfer using scp:

  • scp -r (file want to copy) (ipaddrs of receiver) : (destination)
  • example:  scp -r  /media/songs/song.mp3 192.168.2.3:/home/vishnu/Desktop/

5:Formating Pendrive using command line:

  • Step 1: Unmount pendrive by using umount /dev/sdb1 (the name ‘sdb1’ is different in all system.)
  • The name of the device can be taken by sudo fdisk -l
  • Step 2: mkfs.vfat -n ‘label or name’ -I /dev/sdb1

Post Navigation