Saturday, 22 March 2014

Why AngularJS?

AngularJS is an open source JavaScript framework maintained by Google,that assist making single page web application with MVC framework ,it also  support  for testing.
          AngularJS is a MVC framework that defines numerous concepts to properly organize your web application.Your application is defined with modules that can depend from one to the others. It enhances HTML by attaching directives to your pages with new attributes or tags and expressions in order to define very powerful templates directly in your HTML. It also encapsulates the behavior of your application in controllers which are instantiated by dependency injection.  Use of dependency injection, AngularJS helps you structure and test your JavaScript code very easily. Finally, utility code can easily be divided into services that can be injected in your controllers. Now let’s have a closer look at all those features.

Expressions

 In order to create views ,AngularJS help you to directly execute expression from HTML page.

 <div>1+2 = {{1+2}}</div>  

the page will display 1+2 = 3

Directives

Directives are one of the most powerful feature of AngularJS. They allow  to extend HTML  the needs of web applications. Directives specify how  page should be structured for the data available in a given scope.

There is several directives most people uses ngRepeat


  <tbody>  
    <tr ng-repeat="driver in driversList">  
     <td>{{$index + 1}}</td>  
     <td>  
      <img src="img/flags/{{driver.Driver.nationality}}.png" />  
      {{driver.Driver.givenName}}&nbsp;{{driver.Driver.familyName}}  
     </td>  
     <td>{{driver.Constructors[0].name}}</td>  
     <td>{{driver.points}}</td>  
    </tr>  
   </tbody>  

by this you can possible looping through the driversList.

Filters

In order to change the way data are displayed in your page, AngularJS provides you with the filter mechanism.

Just look at the code:

 <tr ng-repeat="driver in driversList | filter: searchFilter">  

The searchFilter will filter the driverList.

Partial Views

AngularJS is single page web application .So we have only one real HTML page ,its content can be changed  without download a new page.

     In order to build an application, We define a main page (index.html) which acts as a container for  web application. In this page, we can bind part of our application to a specific AngularJS module with the directive “ngApp”. We can bind the whole page to a single AngularJS module if you want. After that, you can use the directive “ngView" in order to use partial views.

index.html look like:

 <body ng-app="F1FeederApp">  
   <ng-view>  
   </ng-view>  
 </body>  

Controllers

      In AngularJS, the controller is where the behavior of your application is located. Controllers are used to populate the scope with all the necessary data for the view. Using proper separation of concerns, controllers should never contain anything related to the DOM.

REST communication

In order to communicate with a restful server, AngularJS provides two services $http and $resource. $http is a small layer on top of XmlHttpRequest while $resource is working at a higher level of abstraction, both can perform the same job.

 ergastAPI.getDrivers = function() {  
    return $http({  
     method: 'JSONP',   
     url: 'http://ergast.com/api/f1/2013/driverStandings.json?callback=JSON_CALLBACK'  
    });  
   }  

                               
                                                            Using AngularJS i created an application which gives status of F1 Championship standings,for live demo  . To see code repo .

Monday, 17 March 2014

Graph Coloring

Graph coloring is part of graph theory ,which has great practical importance. The default graph coloring, vertex coloring means coloring of vertices of a graph in such a way that , no adjacent vertices share same colour.
  The problem of coloring of a graph has several application such as scheduling, register application in compilers, frequency assignment in mobile radios , etc.
How graph coloring is possible.

  1. Let G=(V,E) be the graph to be colored , where V and E are vertices set and edges set respectively 
  2. Compute the  degree of each vertices in 
  3. Make a list uncolored which holds V in descending order of their degrees
  4. Initialize currentColor to zero
  5. WHILE length of uncolored greater than zero
  6. Initialize first to the first element of uncolored
  7. Remove first from uncolored
  8. Initialize color(first) to currentColor
  9. Initialize coloredWithCurrent to {first}
  10. FOR each vertex v in uncolored
  11. IF adjacent list of v and coloredWithCurrent(currentColor) has no common elements
  12. Set color(v) to currentColor
  13. Add v to coloredWithCurrent(currentColor)
  14. Remove v from uncolored
  15. ENDIF
  16. ENDFOR
  17. Increment currentColor
  18. ENDWHILE 
   The idea of vertex coloring above take the vertex V and also, it's decreasingly arranged based on the number of adjacent  vertices for each vertex v in V.For this we need a adjacency list of the graph .The main idea of the graph coloring by above algorithm is that, it assigns current colour for vertices if the adjacency list of that vertex does not contain elements in the list of vertices which are already assigned the current color. If it contains, a new colour is assigned for the current vertex.
       I have implemented a web application based on above theory , in that we can create  vertices and edges after that just click the button "color it". Click here  to see my graph coloring application deployed on heroku. I used HTML 5JavaScript  and python-django for developing this. The source code link  . 

Tuesday, 4 March 2014

Unit Test In Python

Unit testing is testing individual "unit" or function of a program. Here we use TDD test driven development that is first write the test case then write the code . In python unit test is possible by "unittest" module .

  "isodd.py" is a program to convert any number to odd:
 class IsoddError(Exception): pass   
 class TypeError(IsoddError):pass  
 def isOdd(n):  
   if type(n)==int :  
      if n%2 != 0 :   
        return n  
      else:   
        return n+1        
   else:       
     raise TypeError,"Invalid"  

How to write test cases :

  1. First  write known result with known output
  2. Check the above cases
  3. next check failure of isOdd
here is the TDD code for isOdd:
 class TestData(unittest.TestCase):  
      TestData=( (0,1),  
           (1,1),  
                 (-1,-1),  
           (-2,-1),  
           (8,9),  
           (10,11),  
           (55,55),  
           (100,101) )  
      def testIsOddTestData(self):  
           """isOdd give known result with known output"""  
           for integer,fn_value in self.TestData:  
                result=isodd.isOdd(integer)  
                self.assertEqual(fn_value, result)  
 class IsOddBadInput(unittest.TestCase):  
      def testIsOddInput(self):  
           """isOdd fails for bad input"""  
           self.assertRaises(isodd.TypeError, isodd.isOdd, 'hello')  
   

To see the source code click here

Wednesday, 22 January 2014

Back-End NodeJS

NodeJS give me the ability to write back-end code in JavaScript. It's the better framework to build real time applications.We can create applications using pure JavaScript.

Setup Environment

    First thing to do  get NodeJS installed on your system. For installation in Linux link .
After  installing NodeJS we have to setup the following.


  1. ExpressJS -  this will manage the server and the response to the user.
  2. Template engine 
  3. Socket.io - allows for real time communication between the front-end and back-end

Creating Application
    There is two ways to create applications in Node.
      First create a file named package.json in your project directory and add the dependencies . 
 {  
   "name": "login app",  
   "version": "0.0.0",  
   "description": "Authentication",  
   "dependencies": {  
     "socket.io": "latest",  
     "express": "latest",  
     "jade": "latest"  
   },  
   "author": "developer"  
 }  

Navigate to project folder and execute
 npm install  

Within a few seconds, you’ll have all the necessary dependencies downloaded to the node_modules directory.
            The other way is using ExpressJS we can create application follow the link.

         Developing the back end create a file app.js with the following core expressjs code.

 var express = require("express");  
 var app = express();  
 var port = 3000;  
 app.get("/", function(req, res){  
   res.send("It works!");  
 });  
 app.listen(port);  
 console.log("Listening on port " + port);  

To initialize the application execute:

 node app.js  

Now the server is running go to browser and open http://localhost:3000/ and see:
'it works' 
                           Also we can develop the front end using static and socket.io.
  To see my application  click here .
My code can be found here.

Tuesday, 21 January 2014

NoSQL with MongoDB

NoSQL is designed for distributed data stores where very large scale of data storing is needed. It is different from traditional relational database management systems and are developed to manage data that do not necessarily follow a fixed schema. 
This avoids joins and are easy to scale.

Categories of NoSQL database
  • Key-value store (eg. Voldermort, Tokyo Cabinet, Riak)
  • Graph (eg. FlockDB, AllegroGraph)
  • Big tables/column families (eg. Cassandra, Hypertable ) 
  • Document store (eg. CouchDB, MongoDB)
Now we discuss about MongoDB
Setup MongoDB

    Let's see how to get started with MongoDB. Get the installation instructions from here.
    After the MongoDB installation, your database ready and starts running on your system. You can check if your system is running MongoDB, by typing mongo in the Terminal. If it is, there will be shell version number and some other details of MongoDB, printed on the terminal. 
     Let's make Mongo as back-end in our project. Here i created a paint-application using flask and
MongoDB  .The same application in Django link.

To get MongoDB in Python we need install module PyMongo by typing
  
$ pip install pymongo 

To connect to the database, we create a database instance- a connection object by including the following in our python logic.

 from pymongo import Connection  
 conn_obj = Connection()  
 db = conn_obj.our_db_name  

Now we are ready to use our MongoDB database through the python code. 

 db.collection_name.find()  

It's also possible to get the specific item in the collection. 

 db.collection_name.find_one({"color": "Orange", })  

Reading all the documents of the specified kind, is by, 

 db.collection_name.find({"color": "Orange", })  

More option can be found here.

Friday, 17 January 2014

Paint app in Django

I have modified Paint app using Django frame work. Only the back-end is changed other things remains same.
The URL configuration used in Django is url.py.

 from django.conf.urls import patterns, include, url  
 from mysite.views import home,current_datetime,gallery,save,load  
 urlpatterns = patterns('',  
   url('^$', home),  
   url(r'^time/$', current_datetime),  
   url(r'^gallery/$', gallery),  
   url(r'^save/$', save),  
   url(r'^gallery/([^/]+)$', load),  
 )  

Database used is PostgreSQL

The other important thing is views used in Django which  renders the template ,respond to GET and POST request ,and also inserting and retrieving data into database. The code can be found here 

Friday, 13 December 2013

Paint app with flask

This application based on flask back-end and data base is using PostgreSQL and html-canvas in front end.
   When each picture is drawn details are stored as a json object. Like while a circle is drawn each detail is stored as a json object and pushed to a list.This list of objects is send to the database(here PostgreSQL) and it is shown in the gallery.
    We can load the images which is stored in database using galley
 I created a paint app with flask to see the code goto the link