Monday 20 May 2013

Backbone.js


Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions,views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.


Backbone.Events


Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events.

var object = {};

_.extend(object, Backbone.Events);

object.on("alert", function(msg) {
  alert("Triggered " + msg);
});

object.trigger("alert", "an event");

Catalog of Events 

  • "add" (model, collection, options) — when a model is added to a collection.
  • "remove" (model, collection, options) — when a model is removed from a collection.
  • "reset" (collection, options) — when the collection's entire contents have been replaced.
  • "sort" (collection, options) — when the collection has been re-sorted.
  • "change" (model, options) — when a model's attributes have changed.
  • "change:[attribute]" (model, value, options) — when a specific attribute has been updated.
  • "destroy" (model, collection, options) — when a model is destroyed.
  • "request" (model, xhr, options) — when a model (or collection) has started a request to the server.
  • "sync" (model, resp, options) — when a model (or collection) has been successfully synced with the server.
  • "error" (model, xhr, options) — when a model's save call fails on the server.
  • "invalid" (model, error, options) — when a model's validation fails on the client.
  • "route:[name]" (params) — Fired by the router when a specific route is matched.
  • "route" (router, route, params) — Fired by history (or router) when any route has been matched.
  • "all" — this special event fires for any triggered event, passing the event name as the first argument.


Backbone.Model


extendBackbone.Model.extend(properties, [classProperties]) 

To create a Model class of your own, you extend Backbone.Model and provide instance properties, as well as optional classProperties to be attached directly to the constructor function.

var Note = Backbone.Model.extend({

  initialize: function() { ... },

  author: function() { ... },

  coordinates: function() { ... },

  allowedToEdit: function(account) {
    return true;
  }

});

var PrivateNote = Note.extend({

  allowedToEdit: function(account) {
    return account.owns(this);
  }

});

Underscore Methods

Backbone proxies to Underscore.js to provide 6 object functions onBackbone.Model.


Backbone.Collection


extendBackbone.Collection.extend(properties, [classProperties]) 

To create a Collection class of your own, extend Backbone.Collection, providing instance properties, as well as optional classProperties to be attached directly to the collection's constructor function.

Underscore Methods 

Backbone proxies to Underscore.js to provide 28 iteration functions on Backbone.Collection.


Backbone.Router


extendBackbone.Router.extend(properties, [classProperties]) 

Get started by creating a custom router class. Define actions that are triggered when certain URL fragments are matched, and provide a routes hash that pairs routes to actions.

var Workspace = Backbone.Router.extend({

  routes: {
    "help":                 "help",    // #help
    "search/:query":        "search",  // #search/kiwis
    "search/:query/p:page": "search"   // #search/kiwis/p7
  },

  help: function() {
    ...
  },

  search: function(query, page) {
    ...
  }

});


Backbone.history


History serves as a global router (per frame) to handle hashchange events orpushState, match the appropriate route, and trigger callbacks. You shouldn't ever have to create one of these yourself since Backbone.history already contains one.


Backbone.sync


Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses jQuery.ajax to make a RESTful JSON request and returns a jqXHR.

The default sync handler maps CRUD to REST

  • create → POST   /collection
  • read → GET   /collection[/id]
  • update → PUT   /collection/id
  • delete → DELETE   /collection/id


Backbone.View


extendBackbone.View.extend(properties, [classProperties]) 

Get started with views by creating a custom view class. You'll want to override therender function, specify your declarative events, and perhaps the tagName,className, or id of the View's root element.

var DocumentRow = Backbone.View.extend({

  tagName: "li",

  className: "document-row",

  events: {
    "click .icon":          "open",
    "click .button.edit":   "openEditDialog",
    "click .button.delete": "destroy"
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
  }

  render: function() {
    ...
  }

});

Monday 6 May 2013

Some basic idea about Backbone.js


What is Backbone.js?


            Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions,views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.


What is a view?


              Backbone views are used to reflect what our applications’ data models look like. They are also used to listen to events and react accordingly.

SearchView = Backbone.View.extend({
initialize: function(){
alert("Alerts hi");
}
});
var search_view = new SearchView;

The “el” property


              The “el” property references the DOM object created in the browser. Every Backbone.js view has an “el” property, and if it not defined, Backbone.js will construct its own, which is an empty div element.Let us set our view’s “el” property to div#search_container, effectively making Backbone.View the owner of the DOM element.

<div id="search_container"></div>
<script type="text/javascript">
SearchView = Backbone.View.extend({
initialize: function(){
alert("Alerts hi");
}
});
var search_view = new SearchView({ el: $("#search_container") });
</script>

What is a model?


              Models are the heart of any JavaScript application, containing the interactive data as well as
a large part of the logic surrounding it: conversions, validations, computed properties, and
access control.

Person = Backbone.Model.extend({
initialize: function(){
alert("Welcome to this world");
}
});
var person = new Person({ name: "Thomas", age: 67, children: ['Ryan']});




What is a collection?


             Backbone collections are simply an ordered set of models. 

var Song = Backbone.Model.extend({
initialize: function(){
console.log("Music is the answer");
}
});

var Album = Backbone.Collection.extend({
model: Song
});

What is a router?


       Backbone routers are used for routing our applications URL’s when using hash tags(#).Defined routers should always contain at least one route and a function to map the particular route to.Also note that routes intepret anything after “#” tag in the url.






Monday 10 December 2012

Google app engine with Python 2.7



Explaining the webapp2 Framework


          App Engine includes a simple web application framework, called webapp2.

A webapp2 application has two parts:

  • One or more RequestHandler classes that process requests and build responses   
  • WSGIApplication instance that routes incoming requests to handlers based on the URL
     
import webapp2
class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp World!')

app = webapp2.WSGIApplication([('/', MainPage)],
                              debug=True)

  Using the Users Service

 
         Google App Engine provides several useful services based on Google infrastructure, accessible by applications using libraries included with the SDK. One such service is the Users service, which lets our application integrate with Google user accounts. With the Users service, our users can use the Google accounts they already have to sign in to our application.

import webapp2
from google.appengine.api import users
class MainPage(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()

        if user:
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.out.write('Hello, ' + user.nickname())
        else:
            self.redirect(users.create_login_url(self.request.uri))

app = webapp2.WSGIApplication([('/', MainPage)],
                              debug=True)
 

Handling Forms with webapp2

 

                This version has two handlers: MainPage, mapped to the URL /, displays a web form. Guestbook, mapped to the URL /sign, displays the data submitted by the web form.The Guestbook handler has a post() method instead of a get() method. This is because the form displayed by MainPage uses the HTTP POST method (method="post") to submit the form data. If for some reason we need a single handler to handle both GET and POST actions to the same URL, we can define a method for each action in the same class.The code for the post() method gets the form data from self.request. Before displaying it back to the user, it uses cgi.escape() to escape HTML special characters to their character entity equivalents. cgi is a module in the standard Python library.


Using the Datastore

 

                  App Engine's data repository, the High Replication Datastore (HRD), uses the Paxos algorithm to replicate data across multiple data centers .Data is written to the Datastore in objects known as entities. Each entity has a that uniquely identifies it.An entity can optionally designate another entity as its parent; the first entity is a child of the parent entity. The entities in the Datastore thus form a hierarchically structured space similar to the directory structure of a file system. An entity's parent, parent's parent, and so on recursively, are its ancestors; its children, children's children, and so on, are its descendants. An entity without a parent is a root entity.


Using Jinja2 Templates

 

Add the following code to the bottom of the configuration file app.yaml

libraries:- name: jinja2
  version: latest

Add following code to the top of the mainpage handler 

 

import jinja2 
import os

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

 

 Replace the MainPage handler with code that resembles the following:
 
 class MainPage(webapp2.RequestHandler):
    def get(self):
        guestbook_name=self.request.get('guestbook_name')
        greetings_query = Greeting.all().ancestor(
            guestbook_key(guestbook_name)).order('-date')
        greetings = greetings_query.fetch(10)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'greetings': greetings,
            'url': url,
            'url_linktext': url_linktext,
        }

        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))
 

Using Static Files

 

              Images, CSS stylesheets, JavaScript code, movies and Flash animations are all typically stored with a web application and served directly to the browser.

We create a configuration file   app.yaml with the following content

application: helloworldversion: 1runtime: python27api_version: 1threadsafe: true
handlers:- url: /stylesheets
  static_dir: stylesheets
- url: /.*
  script: helloworld.app
libraries:- name: jinja2
  version: latest
 
 Create a css file with following content for set background colour and font etc
 
body {
  font-family: Verdana, Helvetica, sans-serif;
  background-color: #DDDDDD;
} 
 
Using following codes in html file for access the css file

<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" /> 

After testing we can upload our file to google app engine using foolowing commands 

 python appcfg.py update  "set path"







 

Saturday 8 December 2012

Google App Engine


        Google App Engine lets us to run web applications on Google's infrastructure.App Engine applications are easy to build, easy to maintain, and easy to scale.With App Engine, there are no servers to maintain.

                Google App Engine supports apps written in several programming languages.With App Engine's there are 3 different types of runtime environment.

  • Java runtime environment
  • Python runtime environment
  • Go runtime environment  

 

The Python Runtime Environment

 

                With App Engine's Python runtime environment, we can implement our app using the Python programming language, and run it on an optimized Python interpreter.The primary Python runtime environment uses Python version 2.7.2. we can also choose the older Python 2.5.2 runtime.The Python environment includes the Python standard library. Of course, not all of the library's features can run in the sandbox environment.The Python environment provides rich Python APIs for the datastore, Google Accounts, URL fetch, and email services.

 

How To Use The App Engine To Host An Application


              At first we download and  install the Google App Engine SDK in our systemThen we can register our application with unique application id and application name in our google app engine account.We can create a folder in our system containing 3 files. First one is the file which to be upload to the google app engine,second is the configuration file called app.yaml this file describes which handler scripts should be used for which URLs.


                       application: nithinconwaysgameoflife
                       version: 1
                       api_version: 1
                       runtime: python
                       handlers:

                      - url: /.*
                      script: main.py 

here nithinconwaysgameoflife is the application id.
Third one is main.py ,the python file where we access our web application file.


                          import wsgiref.handlers
                          from google.appengine.ext import webapp
                          from google.appengine.ext.webapp import Request
                          from google.appengine.ext.webapp.util import run_wsgi_app
                          from google.appengine.ext.webapp import template

                          class mainh(webapp.RequestHandler):
                              def get(self):
                                  self.response.out.write(template.render("game.html",{}))  
      
                         def main():
                             app = webapp.WSGIApplication([
                                 (r'.*',mainh)], debug=True)
                             wsgiref.handlers.CGIHandler().run(app)


                          if __name__ == "__main__":
                                     main()

Testing the Application

 

With a handler script and configuration file mapping every URL to the handler, the application is complete. We can now test it with the web server included with the App Engine SDK.

Type the command on terminal


google_appengine/dev_appserver.py "path to applicationid folder"
 
we can test the application by visiting the following URL 


http:// localhost:8080/

 

Upload the application to google app engine 


$cd google_appengine


after enter the  google_appengine folder in the system.

Type the following command on terminal


python appcfg.py update " path to applicationid folder".


Enter your google user name and password at the prompt
Now we can see our application run with url  http://applicationid.appspot.com/ on google app engine



click here for see example

 

 


Wednesday 5 December 2012

CountDown Timer


         CountDown Timer is an application for set the time and start the counting down in seconds,minutes,hours etc.The language used for develop the countdown timer is javascript in html canvas.The main idea for contdown timer is refreshing the canvas on every call of setInterval( ) which is set for 1000ms.

      There is two text box for enter the time in minutes and seconds.Three buttons are available for start,stop and set.The start button is used for start counting down, the stop button is used for stop the timer and the set button is used for set the initial time.

There are four functions are mainly used for develop the timer.


function counter()

      This function is used for counting down in second and minutes based on some conditions which depend the initial value.This function return the message "Time out" when seconds ==00 and minutes ==00.

function start()

      This function is used for start the timer.within this function call of setInterval( ) which is set for 1000ms.

function set()

            This function is used for set the inital time in seconds and minutes.

function stop()

            This function is used for stop the timer.Within this function call clearInterval() .


Click here for download the code for CountDown Timer in javascript.


COUNTDOWN TIMER








COUNT DOWN TIMER
minutes: seconds:

Monday 3 December 2012

Conway's Game of Life



                 The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970.The "game" is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.


Rules

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

Algorithm 

               Life patterns are represented as two-dimensional arrays in computer memory. Typically two arrays are used, one to hold the current generation, and one in which to calculate its successor. Often 0 and 1 represent dead and live cells respectively. A nested for-loop considers each element of the current array in turn, counting the live neighbors of each cell to decide whether the corresponding element of the successor array should be 0 or 1. The successor array is displayed. For the next iteration the arrays swap roles so that the successor array in the last iteration becomes the current array in the next iteration.

Examples of patterns

                   Many different types of patterns occur in the Game of Life, including still lifes, oscillators, and patterns that translate themselves across the board.examples of these three classes are shown below, with live cells shown in black, and dead cells shown in white.


Still lifes                                               Oscillators                                                             Spaceships 

                                               

                                             
 block                                                   Blinker (period 2)                                                              Glider                                              

                                                           


                              
    Beehive                                                Toad (period 2)                                                        LWSS
                                                                                                 
                                   
              
                               
        Loaf                                                  Beacon (period 2)                             

                                    
            

        

      Boat                                          Pulsar (period 3)                                                                   
  
                                                




   Click here for downloading the Conway's Game of Life Code.

 

Play the game


  




Conway's Game of Life