Author Archives: neethutv

Unknown's avatar

About neethutv

Software Engineer in web OS at INXS Technologies ,chennai

A vertex colouring application in Node js

Standard

My first web application in Node js is an implementation of vertex colouring algorithm. Here the application is a graph colouring technique which takes a graph and provide a proper colour to each of nodes according to vertex colouring algorithm. Here the server side and client side program is implemented in javascript. The frontend consisting of HTML5 ,jquery ,javascript  .Client program consist of html5 canvas and we can draw a graph using javascript in the canavas.The program code is in one file which conatin both code of html5 and javascript.

 

 In this article i talk about only the server side programming using Node js .Node js is an open source ,low level ,evented ,nonblocking server side javascript.If you want to read more about Node js  please go to this link https://neethutv.wordpress.com/2012/02/27/a-simple-chat-server-in-node-js/   and come back. To create  this vertex colouring application we need following constraints :

  • We want to server web pages so need a HTTP server
  • Server need to answer differently to requests ,depending on the which URL the request was asking. So need some kind of router to map requests to request handlers
  • To fulfill the requests that arrive at the server and have been routed using the router ,need request handlers 
  • The  router also treat incoming post data such as here the adjacency list of the graph for input to colouring algorithm  and give it to the request handlers so need request data handling .Here request handlers mainly contain graph colouring algorithm.

So let us start our application.

A basic HTTP server

I create a main file called index.js  which is to start our application and server.js  where our HTTP server  code lives. Let us start with server module. Server.js conatin following code


var http =require('http');
var url=require("url");

function start(route ,handle) {
http.createServer(function (req, res) {

var pathname=url.parse(req.url).pathname;
console.log(pathname);
var body=route(handle ,pathname,res,req);
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
}
exports.start=start;

The first line requires the http module and  that with Node js and make it accessible through  the variable http:


var http =require('http');

Also we requires another module named as url. This module have utilities for URL resolution and parsing.

var url=require("url");

Making some code a module means we need to export those parts of its functionality that we want to provide to scripts that require our module. Here our main module is index.js so to load server module we need to add a line as in index.js a follows:

var server=require("./server");

For now our HTTP server need to export ,we add a function named start as in above program and export this function as:

exports.start=start;

The url module provide methods  which allow to parse pathname from url:


var pathname=url.parse(req.url).pathname;

Our application can now distinguish requests based on the URL path requested – this allows us to map requests to our request handlers based on the URL path using our (yet to be written) router.  Serever code contain another function named as route which will expalin later.

Route The Requests

We need to able to feed requested url and GET and POST parameter into our router, and based on this the router then need to decide which code to execute. So this is the third part of our application which will discuss later. Here is the code for router.js


function route(handle,pathname,res,req) {

console.log("About to route a request for " + pathname);
  if(typeof handle[pathname]==='function'){
      return handle[pathname](res,req);

  }else {

     console.log("No request handler found for " + pathname);
}
}

exports.route = route;

This code will explain later.

Routing to request Handlers

   Routing means we want to handle requests  to different URLs differently.In our application first we need a request for web page to draw a graph. And also we need another url which contain POST data, which is created after submitting the graph for colouring. Router is not the place actually  do something with the requests, Here requests are routed to request Handlers. Let us create a module called requestHandlers.js ,it is a placeholder function for every request handler and export these as methods of the module. Here  is the code is too big so you can refer my bitbucket repository.

requestHandlers.js  mainly contain two methods one is start which is to start the HTML page contain  canvas to draw graph. We can load this HTML page using a module named ‘fs’ in Node js. The code as follows ,


var fs=require('fs');

function start(res,req) {

console.log("Request handler 'start' was called.");

fs.readFile('index.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end()

});

return ;

}

But we need to pass the request handlers from our server into router, Here we have two handlers. Now we can use javascript object which are just collections of name/value pair ,and these values may be strings ,numbers ,functions. Here we use values as functions.We want to pass the list of requestHandlers as an object.Now let us start to look our main module index.js ,which contain following code

var server=require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");

var handle = {}

handle["/"] = requestHandlers.start;
handle["/graph"] = requestHandlers.colour;

server.start(router.route, handle);

We can see that handle is a collection of requesthandlers,map urls to corresponding request handlers.So whenever ‘/’ this url enters then execute the start function which resides on requestHandlers.js. We can also map different url’s to same request handler.If ‘/graph’ url enters then the colouring function will perform and return the coloured values.Also we need to use the function route() in server module:
route(handle ,pathname,res,req);

In our server program we have add handle parameter to our start() function and pass the handle object on the route() callback as its first parameter.Now here is the time to explain router.js.We need to check if a request handler for the given pathname exists,and if it does simply call according function.Because we can access our request handler functions from our object just as we would access an element of an associative array, we have his nice fluent handle[pathname]();

Handling the requests

Our requestHandlers.js contain two function one is to load html page which contain canvas to draw graph. After completed the graph just send the adjacency list by jquery/ajax. Then click the submit button another url will created  named as ‘/graph’, and this are send through using jquery. Then when ‘/graph’ enters on server program it will  execute the colouring algorithm.

Algorithm keeps a set of colours and the ‘availability list’ of colours for each node. First it takes each node in the order. It then checks the adjacentcy list of that node. If the first node in the list is coloured, it deletes that colour from the availability list. Then takes the next node from the adjacentcy list and the process continues. Last assigns the first colour in the availability list. This ensures the algorithm to take smallest number of colours. Then return the result as:


res.write(JSON.stringify(value_color)) ;

Then we can see the coloured graph on our web page. To get the complete code please visit my bitbucket repository https://bitbucket.org/neethuedappal/vertex-colouring-algorithm-using-node-js/changeset/3ed8b6e1599c




  

Node js – Server Side JavaScript

Standard

Now i have got a chance to learn a new technology  known as node js . I have developed  a simple chat server and a vertex colouring application in node js. Before we talk  about chat server  let’s  take a moment about node js .

What is node js

If we working with javascript then we don’t need to  worry about this name because  node js is allow to run javascript code in backend. Node.js is a platform built on  Chrome’s  javaScript runtime  for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Node js itself is a program that will have to be compiled and installed on our machine.Then we can use javascript to write programs that use  API of node js and are executed through “node programname.js“. It is an event loop based  instead of threads and is able to scale to millions of cuncurrent connections. There is many advantages that servers spend most of their  time to wait I/O operations .Every I/O operation in Node js is asynchrounous meaning that server can continue to process incoming requests while the I/O   operations taking place.Node js is working with call backs and non blocking I/O. Call back means any functions execute in node js program does work in the background after calling ,executing a call back function once it is done.

An Example : Web server.

When i have started to learn i just search many tutorial on the web about the node js and all are teach  me how to write a basic HTTP  web server in  node js.  At first we have to understand the Node js module system. There are many modules listed in the node js documentation. We need to load these modules by using require function. Here is a simple web server it says hello world.

var http=require('http');
http.createServer(function(request , response) {
 response.writeHead(200, {"Content-Type": "text/plain"});
 response.write("Hello World");
 response.end();

}).listen(8888);

Here i just wrote working of HTTP server. Let us  execute this script with Node js:

node  server.js

Now open your browser and point it at http://localhost:8888/ . This should display a web page that says ‘Hello world’.

Let us analyze our program. The first line requires the http module and  that with Node js and make it accessible through  the variable http. We then call one of the functions of http module: createServer . This function return an object and this object has a method named listen ,it take the port number our Http server is listen on. Here  we create a server and pass a function to the method creating it. Whenever our server receives a request, the function we passed will be called. Incoming request is handle  the function which we called. This concept in Node js is called callback .

Here the callback function passed two parameters  request and response. These are objects and we can use their methods to handle request and responses. Whenever a request is received ,it use the response.writeHead() function to send an HTTP status 200 and content-type in HTTP response header,and response.write()  function send the text ‘hello world ‘ finally response.end()  finish our response.

An practical example  – simple chat server

Building a chat server in Node js is very easy. Node js is make easy to  write event based network servers. We know that a chat server allows multiple clients connect to it . Each  client can write messages that are then broadcast to all other  users. Here is a simple program for a multichat server


net = require('net');
var sockets = [];

var s = net.Server(function(socket) {
 sockets.push(socket);
 socket.on('data', function(d) {
 for (var i=0; i < sockets.length; i++ ) {
    if(socket!=sockets[i]) {
      sockets[i].write(d);
    }
}
});
});
s.listen(8001);

Here is the flow of this simple program:

  • When a socket connects ,append the socket object to an array
  • When any client write to their connections ,then write data to all sockets except the client’s

The first line  allow access to contents of net module :

var net =require(‘net’)

This module also contain a Server function ,let we can use it and also we will need a place to hold all client connections so that we can write all of them when write the data.So we use an array named as sockets.

var sockets=[];

Then the next line starts a code that detemine what happen when each client connects,

var s = net.Server(function(socket) {

The only argument we pass into the Server is a function that will called each time when a client connects to server.Inside this function add each socket to the array.

sockets.push(socket);

Then the next piece of code set up an event handler to dictate what happens when a client sends data.

for (var i=0; i < sockets.length; i++ ) {
    if(socket!=sockets[i]) {
      sockets[i].write(d);
    }
}

The socket.on function registers an event handler with node so that it know what to do when certain events happens.Node js calls this particular event handler when data is received from the client.The structure of socket.on callis similar to the Server() call.Both of them we pass a function and the fucntion is called when something is happened.Call back approach is common in asynchronous networking frameworks.Here when any client send data to server ,this anonymous function is called and data is passed into the function. It iterates over the list of socket objects you have been accumulating and sends the same data to them all. Each client connection will receive the data.

To get the complete code visit my bitbucket repository as https://bitbucket.org/neethuedappal/node-js-programs/changeset/95a5ed2fee37

Python list comprehension

Standard

I think  list comprehension is one of  the advanced feature that make python more userfriendly and efficient . Do you know what is list comprehension ? how can be use it ? .This post will help you to learn some basic ideas about list comprehension in  python.

What is a list comprehension?

Mainly list comprehension  feature is indroduced in python version 2.0 . It  is an elegent way  to define and  create lists in python. Using list comprehension we can create  new list from an existing list  and each element in the new list  is the result of some operations applied to each element in the old list. List comprehension is not a complicated idea it fit a for loop,if statement and assignment all are in one line . Let me explain concept behind list comprehension using some examples.

Here is a simple program which create a list of  squares of even numbers in the range of 10

>>>L=[]

>>>for x in range(10):

   if x%2 ==0:

     L.append(x**2)
>>>L
[0,4,16,36,64]

Now i am going to write same program using list comprehension technique


>>L=[x**2  for x in range(10) if x %2==0]
>>L
[0,4,16,36,64]

above two codes are identical, you can see that list comprehension is more good and  you get to see more of the code in one view. Another important factor is that list comprehension is the complete substitute for lambda() functions as well as the functions map(),filter() ,reduce().

Basic syntax  is:

[expr for  item1 in  seq1 for item2 in seq2 … for itemx in seqx if condition]

  • the list comprehension starts with a ‘[‘ and ‘]’, to help you remember that the result is going to be a list
  • there’s an expression based on the variable used for each element in the old list
  • the word ‘for’ followed by the variable name to use followed by the word ‘in'
  • the old list

Here are some more examples using list comprehension

Cross product of two sets


>>>colours=["red","blue","yellow"]

>>things=["house'","car","tree"]

>>>coloured_things=[(x,y) x in colours for y in things]

print coloured_things

[('red', 'house'), ('red', 'car'), ('red', 'tree'), ('blue', 'house'), ('blue', 'car'), ('blue', 'tree'), ('yellow', 'house'), ('yellow', 'car'), ('yellow', 'tree')]

Following list comprehension create a pythagorean triples

>>>[(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2 == z**2]
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]

Calculation of prime numbers between 1 and 100

>>>noprimes = [j for i in range(2, 8) for j in range(i*2, 100, i)]
>>>primes = [x for x in range(2, 100) if x not in noprimes]
>>>print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>>

List comprehension and generator comprehension

If you don’t know about generators in python please go to this link https://neethutv.wordpress.com/2012/01/11/generators-an-advanced-concept-in-python/ and come back to this article. Generator  comprehensions are introduced with python 2.6. They are simply generator expressions with paranthesis .The syntax and way of working of generator comprehension is same way as list comprehension , but most important difference is that generator comprehension return a generator object instead of list. Generator comprehensions  always have to written in paranthesis.  Here some examples of generator comprehensions


>>>x = (x **2 for x in range())
>>>x
<generator object <genexpr> at 0xb76acb44>

>>>for i in x:

  print i

0,1,4,9,16

List comprehension is one of the simple and useful feature of python.  It is  faster than equivalent for loop, but map(),filter() ,reduce() are generally faster than list comprehension. One thing to note that list comprehension create a new list. The new list is rebound the same name.

l = [ foo(i) for i in l ]

but a new list is created ,any other name that refer to original list will not changed. This is a rarely problem so to avoid this type of problems just use slice assignment instead of normal assignment.

l[:] = [foo(i) for i in l]

I think list comprehension is quite easy to use and can make code that manipulates lists shorter and more readble.

Generators- An advanced concept in python

Standard

I have always heard about python generators , now i got a chance to study about this generators . I think generators are one of important and advanced  feature  in python .What are these generators ? A generator is a function that produce a sequence of result instead of a single value while maintainig the state of function. Generators are very useful and simplfy our code also  improve the performance. Most typical use of generator is to define iterator  ,iterators are  fundamental part of python and they are used in the  ‘for’ statement. To defining a generator we must know about iterator and its working because generators are powerful tool to create iterators. In this article i explaining about concepts of generators how it improve efficiency of python.

What is iterators ?

 We are familiar with iterations, because  they are fundamental concept in python .When we create a list we can read its items one by one .This process is called iteration. Python allow many type of iterations such as  iterating over list ,dictionary ,file etc. But we don’t know what happen behind a for loop. The for statement call  iter() function and this function return an object that have  a .next() method which can access element one at a time and it raise StopIteration exception  when there is no element and tell to for loop to terminate. This is the  basic working of iterator. When we read values using iteration all values are stored in memory and we can read  as our wish .

What is a generator ?

Generators are iterable but we can only read values once. Its because they do not store all the values in memory. We can also define generator as a function that remember the point in the function body where it last returned.

Eg :


def countdown(n):
    while n > 0:
    yield n
    n -= 1

Calling a generator function create and return a generator object.

 >>>x=countdown(3)
 >>>print x
 <generator object at 0x58490>

It does not start running the function ,instead it create a generator object .Also the function not really exit  and it goes to a suspended  state . Then for loop try to loop over this generated object ,  then function resume from its suspended state and run until the next yield statement and return that as the next item. This procedure will happen until the function exits and at which point the generator raises StopIteration , and the loop exits. In the above function named countdown(3) which print first 3 and then generator forgot 3 and then print 2 , that also forgot and last print 1. So that improved the performance of code because less memory is used . We can only once read values using generator object. If we want to read again all these values then we need to create again a generator object .

Let us look about importance of yield statement  in a generator function

Yield statement

Yield statement is an important part of a generating function  which have following specifications,

  • Only used in body of generating functions
  • Using a yield statement in a function definition causes that definition to create a generating function instead of normal function
  • Yield statement resume where the function left of
  • When a yield statement is executed state of a generator function is frozen and next time .next() function invoked the function will resume

Now we can try to run a for loop over the generator object of above generating function.

>>> x.next()

3

>>>x.next()

2

>>>x.next()

1

>>>x.next()

Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration

Next we want to look about generated expressions
Generated expressions

  Generated expressons same as list comprhensions in python . But   some differences are there which are follows,

  • Generator function do not construct a list
  •  Only useful purpose is iteration
  • Once consumed ,then can’nt reused
  • Instead of bracket parentheses is used
eg:

 >>>a=[1,2,3,4]
 >>>>c=(2*x for x in a)
<generator object at 0x58760>
 >>>for i in a:
print i
2
4
6
8
>>>sum(i*i for i in range(10))
285

So  generator  function  make python more effective and  efficient and i  hope that this article will help you to learn about some informations about generators  in python ,

Introduction to unit testing in python

Standard

In computer programming unit testing is a method by which individual units of source code are tested to determine if they are fit for use. As a dynamic language python it is easier to test than other languages .This  article will help you to learn about unit testing in python .

Unit testing in python mainly using the python standard library testing framework called unittest. Unit tests are for testing components of our code ,usually classes or functions.We can start from the standard libarary module unittest 

The unittest module

Python unit test sometimes referred to as “PyUnit” is a python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in turn, a Java version of Kent’s Smalltalk testing framework. unittest support test for automation , sharing of setup and shutdown code for tests, aggregation of tests  into collections and independance of tests from reporting frame work . The unittest module provide classes that make esay to support the above qualities for a set of tests.

Important concepts in unittest 

  • test fixure – represent preparation needed to perform one or more tests.
  • test case – smallest unit of testing ,it check for a specific response for a particular set of input. unittest provide a base class ,TestCase which  used to create test cases.
  • test suite – collection of test cases
  • test runner – component provide an environment in which tests can execute and provide outcome to user . runner use a graphical interface or textual interface or return a special value to indicate result of executing tests.

Creating test cases

Test cases are most fundamental part of unit testing. A test case answer a simple questions about the code it is testing also a test case run completely itself no need of any human input. It determine by itself whether the function it is testing has passed or failed, without any human interpreting the results. In PyUnit, test cases are represented by the TestCase class in the unittest module. To make your own test cases you must write subclasses of TestCase.

Here  a simple example which i do from the official python tutorial creating test cases , we  can test three functions from python random module.


import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

     def setUp(self):
         self.seq = range(10)

     def test_shuffle(self):
    # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))

    # should raise an exception for an immutable sequence
        self.assertRaises(TypeError, random.shuffle, (1,2,3))

     def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)

     def test_sample(self):

        self.assertRaises(ValueError,random.sample,self.seq,20)
        for element in random.sample(self.seq, 5):
          self.assertTrue(element in self.seq)

if __name__ == '__main__':
  unittest.main()

In python a test case is created by subclassing unittest base class TestCase as follows,

    class   TestSequenceFunctions(unittest.TestCase)

Testcase defining test methods whose names are starting with ‘test’.Test methods performing actions and assert methods are to verify the expected behaviour and results. In the above program three functions in random module are tested, and we use three test methods.Each test is call to assert methods to check results. When a setUp() method is defined, the test runner will run that method prior to each test and when a tearDown() method is defined then test runner will run that method after all methods.

Testing for equality

The most common type of assertion is the assertion of equality between two values. If the assertion fails we got the incorrect result and our test will fail. In above example we check whether the sorted list from 0-9 numbers  will equal to range(10). The result is true and test must pass.

assertEqual – This method test equality of two values, if the values are not equal test must fail and raise exception.

  self.assertEqual(self.seq, range(10))

asserNotEqual – This method check two values are not equal .

    self.assertNotEqual(1 + 2, 4)

Testing for exceptions

There is also testing for exceptions also known as testing for failure. It is not enough that function succed when given a good input , we must also test they fail when we given a bad input or they must fail as our expectations. TestCase class of unittest provide assertRaises method to check the expected exceptions ,which take following arguments,

  • Exception you are expecting
  • Function you are testing
  • Arguments you are passing to function

In the above program test method test_sample test the exception

self.assertRaises(ValueError,random.sample,self.seq,20)

Here we select 20 random sample numbers from the range(10).We know that result will raise an exceptions and we use the assertRaises to get our expected exception as ValueError.

Testing for the truth

Some tests are assert the truth of some condition.In the above program test_choice method test the truthness. We select a random element from the sequence and test the presence of truth of statement.

   element = random.choice(self.seq)
        self.assertTrue(element in self.seq)

Test Fixtures

Fixtures are the resources needed by  a test , For example  you are writing several tests for the same class ,those tests all need an instance of those class to use for testing. TestCase include functions to configure and clean up fixtures needed to our test. To configure  fixtures  override setUp() and clean up override tearDown().

Following a simple example to a test fixture ,

import unittest
class FixturesTest(unittest.TestCase):

     def setUp(self):
         print 'In setUp()'
         self.fixture = range(1, 10)

     def tearDown(self):
         print 'In tearDown()'
         del self.fixture

     def test(self):
         print 'in test()'
         self.failUnlessEqual(self.fixture, range(1, 10))

if __name__ == '__main__':
    unittest.main()</pre>

When we run this sample code we can see the order of execution of fixture and test method :

Running testes from the command line

unittest module contain a function called main ,which used to turn a test module into script that it will run the test conatins. unittest.main() automatically load test cases in the current module. When we excute our program in the command line as pyhton test_pgm.py then all tests will run and we get result as follows.

Bloom filter – A probabilistic datastructure in c

Standard

One of my project in c datastructures is to implement a bloom filter. Bloom filter is a space  efficient probabilistic datastructure in c.  like a set datastructure , the main function of bloom filter is to test whether a element is the member of a set. Probabilistic data structure means it tell us an element definitely not in the set or may be in the set. Bloom filter is an application of bitvector . When using bloom filter false positives are possible and  false negative does’nt.

The main datastructure of bloom filter is a bit array. Implementation of bloom filter contain hash functions to get the array positions.  An empty bloom filter contain all bits in the bit array zero .There are many hash functions in c which can be used to  implement bloom filter. Each hash function maps some elements in the array. To add an element in the array ,element must  pass through each hash functions and each  function returns a integer corresponding to the element. Then using this integer as the index in the array we set the corresponding bit as do in the bit vector implementation .

Let we can take a simple example of idea behind bloom filter.

We insert and search on a bloom filter of size  m=10 and the number of hash functions will be k=3.

Let H(x) denote the result of three hash functions and we can write it as a set { h1(x) ,h2(x) ,h3(x)}

This is our empty array

Then we inserting an element  x0. The element  must pass through 3 hash function and we obtain values as follows,

H(x0)= { 1, 4, 9}

Then array like this

Insert another element x1 ,  it also pass through hash function and we got a set as follows and we set the bit in bitarray

H(x1)={ 4, 5, 8}

Next we query for an element  y0 in bloom filter  it again pass through same hash function and we get

H(y0)= { 0 ,4, 8 } here the element is not in the set because of one of its bit is zero .

then H(y1)= { 1, 5, 8} here the element is present and it is a false positive

In my program i select two hash functions  FNV hash function and DJB hash functions. These are two of the most efficient  general purpose hash functions in c.

We can start from a dynamic array  named bloom and  allocate memory  using malloc() function in c. To add an element to this array we just pass the element through the two hash functions and set the bit in the bit vector at the index of  those hashes to 1. At first we pass the string to FNV   hash function ,it return a specific hash value using this we set the bit as 1 in bit vector ,second we pass through DJB hash function. This  hash function seems to have a good over-all distribution for many different data sets.  Again using the hash value we set the another bit in the bloom array . Here is a simple code of my program

To  test the membership of the element then hash the element with same hash function and check those values in the bitvector is set to 1. Element is pass through the same hash function used for insertion and we check those values in the bloom is 1 if it is true then element  may be present otherwise definitely not in the set . In the below code if both r1 1nd r2 true then element may be present.

 

Source code is available here  https://bitbucket.org/neethuedappal/c-data-structures/changeset/21b72694a7f0

Bit vector implementation in C

Standard

Bit vector implementation  provide space optimization  by using a re-sizable character array . This article will help you to understand implementation of bitvector in c programming.

 What is bit vector ?

Bit vector is composed of two words bit and vector. We already know bit and vector , bit is smallest unit of data in computer and it has single value either 0 or 1. Here vector defining a structure which is basically a re-sizable array . So bit vector is mean to pack values into an array so that no space is wasted. Bit vectors are array of bits. When we defining an integer array which can hold 10 elements  then each block in the array contain 32 bit and total size will be  320 bit but we does’nt use  entire  320 bit . So remaining  space will be waste. Bit vector implementation is a solution to this problem . Here we declare a character array  of some size and initialize it as zero  .

In my program i declare an array named bit vector and initilize as zero . To insert an element into this dynamic array some steps are there Insertion means only setting a bit as true not actual insertion .

Let we take element  ‘n ‘ as  ‘6’

  1. To insert  6   we need a block in the array  and a bit position .
  2.  To find the block were 6  belongs ,  dividing   6  by the  block size.  Here array  bitvector  contain array of character so the block size will be 8 bits.  6 /8  is  0  and 6 must be belongs to 0th block.
  3. To find bit position of  6 in the  0’th block take reminder of  6 %8 . So we get the bit position as 6
  4. Here no insertion of  element ‘6’ only setting the bit in the corresponding  bit position as 1.
  5. To set a bit  ,left shifted  1 p times, where p is bitposition, and OR it with the value in the block

bitvector[bitpostion] |= 1 << bit position

Now we set 6’th bit in 0’th block as 1.

To check whether a number is present or  not in bit array we need the  block which number belongs and also bitpostion.

  1. Find the block as do in the insertion
  2. Find the bitposition also.
  3. If the bit in the  bitposition is zero no element is there
  4. If the value returned by the bitwise AND with the value in the block and left shifing of 1 p times ,were p is bitposition will true then number is present in bit array.

To clear a bit  without affecting the all other bit in bit array the bit must be change to 0.

  1. So again shift a 1 left with bitposition
  2. Apply unary operator ~ to reverse all bits   , ~(1 <<bitposition)
  3. Then binary AND operator with value in the block size

These are the main steps to implement a bit vector and bit vector implement a set data structre  to store individual bits . Bit vector implementation in many languages provide space optimization.

Avl Tree- a self balanced binary search tree

Standard

We are familiar with binary search tree , an efficient  datastructure contain data as nodes. Avl tree is also  binary search tree. What is difference between binary search tree and avl tree ? The answer is  avl tree is self balanced , and it was first data structure which is self balanced. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation.  In avl tree height of two child subtrees of any node differ by atmost one .The balance factor of a node is the height of left subtree minus height of right subtree and a node with balance factor 1,0,-1 considered as balanced. Below an avl tree with 9 nodes and each node have a balance factor of 1 ,-1 or 0.

When inserting a new node or deleting en existing node , the resulting tree will disturb the balance of tree. An unbalanced state is defind as a state in which any subtree have a balance factor greater than 1 or less than one . Tree rotations are necessary  to retain the balanced state. A tree rotation move one node up and one node down in the tree.

Insertion 

Every time inserting a node in tree ,it is necessary to check  each of the nodes ancestors for consistency with the rules of avl. If the balance factor of each node remains  -1,0 ,+1 then no rotations are necessary  . In my program a function named  balance(p) return the balance factor  of the node p in the tree . The following code will check the balance condition.If a node in tree violate avl rule  ,then  rotation  will necessary then we get a balanced tree.

There are four cases to be considered in which two are symmetric to the other two. Let p be the root and we can observe different cases.

Right right case and right left case  

  • If the balance factor of p is less than or equal to -2 then right subtree of p overweight the left subtree ,then balance factor of right child of p  will be checked.
  • If the balance factor of right child  is -1 then single left rotation needed.

Left rotation can be done in following steps. Select a new node called pivot it will be the new root. Set right child of p as root and p takes the ownership  of  pivot’s left child , then p will be the left child of new root pivot.

Here a tree with 3 as root node and it is right heavy. Its balance factor is -2 so and balance factor of its right child is -1 then a single left rotation is takes place and the  resulting tree must be balanced.

  •  If the balance factor of  right child is +1 then two rotations are needed .Sometimes single rotation not sufficient to balance a unbalanced tree .Such cases two rotations necessory. First is right rotation with p’s right child as root and second is left rotation with p as root. After right rotations we get a unbalanced tree with right subtree left heavy .Then a left rotation is necessory to balance the tree. The tree below need two rotations ( double right rotations ) because balance factor of root’s right child is +1 ,after two rotation resulting tree will balanced.
Left-Left case and Left-Right case
If the balance factor of p is greater than or equal to +2 then left subtree of p overweight the right subtree. Then balance factor of left child will be checked .In these cases we use right rotations
  • If the balance factor of left child is +1 ,a single right rotations is needed.

Right rotation is just opposite of left rotation. Here set  p’s left child to pivot and it will be the new root . p takes ownership of the pivot’s right child as its left child . Pivot take ownership of p as its right child  .The code as follows

Then below tree is left heavy and it need a single right rotation and resulting tree obey rules of avl .
  • If the balance factor of  p’s left child is -1 ,then two rotations are necessory , First is left rotation with p’s left child as root and second is right rotation with p as root . The following tree  is left heavy with root as 5 and its left child is right heavy. So two rotations are needed to balance the tree.
Following above rules you shold be able to balance an avl tree following an insert or delete every time. After all rotation the balance factor must be recalculated and check again the rules of avl .

Storage classes and scope in C

Standard

Storage class in c help us to understand in which area of memory a particular variable is stored . Also defining scope and visibility of variables in the program. In c there are 4 important storage classes which are follows

  • auto
  • static
  • register
  • extern

What is scope and visibility of a variable in c ?

Scope of a variable is the part of program within which the variable can be used. That is check a variable is exist or not , if the variable is exist  means that variable does not destroy from memory. The part of program within which the variable can be used  is known as its scope. Visibility is the accessibility that is up to which part of program we can access the variable. Scope and visibility of each storage class is different. In the below figure scope of the static variable a is the outer red box and visbility of a is yellow colour part.

auto storage class

An auto storage class declares  automatic variables in c language . Automatic variables has lifetime locally and they use a keyword auto

Properties

  •  Default initial value of automatic variable is garbage
  • visibility is the block were it is declared
  • scope is within the block were variable is declared

In the above program the output will be 20garbage10, we know that  visibility of a variable is only were it is declared so the variable a=20 is only seen within the inner block.  Initialization of x is default so attempt to print x will be a garbage value. Outer  block contain initialization of a as 10 so it is only visible outside block. Scope of each  variable is within the block were it is declared.

static storage class

Static storage classes are allocate memory statically.  The keyword static is used to declare static variable in c. Static is used with all datatypes such as int , float , char,  double etc. Lifetime of static variable extends entire run of a program .

properties 

  • Default initial value of static variable is zero or null.
  • Same static variable can be declared many times but initialized only once.
  • If we declared static variable locally then its visibility will within a block where it has declared.
  • If we declared static variable as globaly  then visibility is only file in which it is declared.
  • If static variable declared locally or globally scope is entire program.

The program below help you to use static variables

extern  storage class 

extern storage class let us to declare objects and functions that several source file can use. extern is a keyword used to declare external variables in c. Static is only know to the current file but extern means a global variable in one file also used for accessing other files.

properties

  • It is default storage class of all global variables as well as functions in c.
  • When we use extern keyword it is only declaration no memory allowed .To allocating memory it must be initilized
  • Default initial value of external ariable is zero or null
  • We annot initilize external variables locally ,it will produce a compiler error.
  • Extern variable declared many time but initilized only once

register storage class in c

A register variables are placed on machine registers ie they store in cpu not in memory. Declaration as follows ,

register int a;

Here we requesting to compiler to store variable a in cpu and then compiler will decide were to store it. Compilers are free ti ignore the request .

  • Register variable execute faster than other variable because it is stored in cpu
  • CPU has limited amount of register so decision to select which variable as register is importent. So variable using many times can ctore in register
  • It is  not possible to take address of register variable it has not memory address.
  • Default value of register variable is garbage
  • Scope and visibilty is within the block

Canvas- Transformations and Animations

Standard

Canvas is a interesting feature in HTML5. Nowadays many developers use canvas to create powerful web applications. By definition canvas is  “a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly”. Canvas allow us to draw graphics using javascript. When we use canvas there is no need to install browser plug-ins like flash player. We can draw many shapes using properties in canvas. Currently canvas support 2D surface.

We can create a canvas in the browser using following code

<canvas id=”myCanvas” style=”width:300px; height:300px”></canvas>

This canvas will be invisible also canvas have x and y coordinates. Using following code we can get context of canvas.

var myCanvas = document.getElementById(“myCanvas”)
var context = myCanvas.getContext(“2d”)

Transformation functions

  • scale – allows you to scale the current context.
  • rotate – allows you to rotate the x and y coordinates of the current context.

State functions

  • save – allows you to save the current state of the context.
  • restore – allows you to restore the state of the context from a previously saved state.

Transformations &Animations

When the context is created, the transformation matrix must initially be the identity transform. It may then be adjusted using the transformation methods.

  • scale(x, y)      – changes the scaling transformation with the given characteristics
  • rotate(angle)  – changes the transformation matrix to apply a rotation transformation with the given characteristics
  • translate(x, y) – changes the transformation matrix to apply a translation transformation with the given characteristics
  • transform(m11, m12, m21, m22, dx, dy) – changes the transformation matrix to apply the matrix given by the arguments
  • setTransform(m11, m12, m21, m22, dx, dy) – changes the transformation matrix to the matrix given by the arguments.

Transformations and animations can work separately.  Let’s observe how is the  rotation. To rotate the context, pass in an angle and it will rotate on the canvas. The following example demonstrates draws a rectangle every 250 milliseconds and each rectangle is rotated, so the effect is like a spinning wheel.

var can = function () {
var canvas;
var context;

return {
draw: function () {
var r = Math.floor(Math.random() * 255) + 70;
var g = Math.floor(Math.random() * 255) + 70;
var b = Math.floor(Math.random() * 255) + 70;
var s = ‘rgba(‘ + r + ‘,’ + g + ‘,’ + b + ‘, 0.5)’;

context.rotate(0.2 * Math.PI);
context.fillStyle = s;
context.fillRect(10, 0, 150, 50);
},
init: function () {
canvas = document.getElementById(“myCanvas”);
context = canvas.getContext(“2d”);
context.translate(200, 250);
setInterval(can.draw, 250);
}
}
} ();

window.onload = can.init;

The output will be like this..