Friday, 5 April 2013

Paint application using html5 and javascript

         This is my basic paint application using Javascript and HTML5. This web application consist of tools to draw rectangle and circle with ten colors. HTML5 canvas is used for making the drawing space.Two canvases are used to draw shapes, the real canvas is used to store the shapes and temporary canvas is used for drawing shapes in temporarily . The color picker is made using the table method in html.The application works basically on three mouse events onmousedown, onmouseup and onmousemove.


           The script start drawing once the mousedown and mousemove event occurs and continue until the mousedown event occurs. The method used to draw rectangle and circle are different. For example, to draw a rectangle we need to know the left top coordinate plus the length and breadth of the rectangle.arc method is used to draw circles on canvas. The application also provide the facility to clear the canvas if anything drowned in it. Tools are selects using current_tool function in script.The function Draw is used to Drawing shapes like rectangle or circle in canvas.When we draw a shape, the values of shapes are pushed to Object(named data).


Paint with saving facility:

      
       This application also provides the facility to save our drawings.This is done by saving values about each object needed to regenerate the same drawing. for example, for a rectangle it would be the type of the object which is "rectangle", its beginning coordinates and end coordinates are saved to regenerate the rectangle.All the shapes are saved in same manner.Different functions are used to Drawing and regenerating same our drawings When we click the save button the data is transferred to the server as a json string where it is stored along with a name provided by the user . Since we have a save feature it is quite easy to implement the edit feature also.Just regenerate the drawing using the data received from the server,make some changes and save it with the same name or a new name ,as the user wishes. JSON is syntax for storing and exchanging text information.
The complete code is available Here.
 

Wednesday, 13 March 2013

FLASK


      Flask is a lightweight web application framework written in Python. Flask is called a microframework because it keeps the core simple but extensible. Helps both for development and deployment of web applications. Flask depends on two external libraries, Werkzeug and Jinja2. Werkzeug is a toolkit for WSGI, the standard Python interface between web applications and a variety of servers for both development and deployment. Jinja2 renders templates. Flask application can test in local machine by using local server. Then finally you can deploy it on web server.This post gives a good introduction to Flask.

Installation: 

        Install flask in your local machine using the command:
 
sudo apt-get install python-flask 

  Simple App: Hello world

        simple Flask application looks like this:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

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


              In this code first we imported the flask class.first argument is the name of the application's module.if you are using single module, you should use __name__. Next we create an instance of this class. we pass it the name of module. This is needed so that Flask knows where to look for templates, static files and soon. Then route() decorator is used to bind a function to URL

Just save it as hello.py and run with your Python interpreter. The local server is now running


$ python hello.py
    * Running on http://127.0.0.1:5000/ 

You should see your hello world message on http://127.0.0.1:5000/
To stop the server, use Control-C

STUDENTS APPLICATION IN FLASK


         In this tutorial  we will create a simple web application 'student details'. The student details application provide you entering details of students and get back all data by sorting order by age and mark, also provide remove option and search option. We will use Flask and SQLite database with Python


Creating Folders


Before we get started, let’s create the folders needed for this application where we drop our files:
/students-app
/static
/templates


          Directly into this folder we will then put our database schema as well as main module in the following steps. The files inside the static folder are available to users of the application via HTTP. Inside template folder Flask will looks for templates.

 Database


          First we want to create the database 'students.db' .The sqlite3 data base system had used for handling datas.For this application only a single table is needed and we only want to support SQLite so that is quite easy.The database is created using the link: http://zetcode.com/db/sqlitepythontutorial/

           The code used for storing data in data base is given below. The datatostore may a variable, list, tuple etc. Don't forget to import sqlite3 from Python library.

con = sqlite3.connect('students.db')
        cur = con.cursor()
        cur.execute("CREATE TABLE IF NOT EXISTS student(name text, sex text, age text, mark text)")
        cur.execute("INSERT INTO student VALUES(?, ?, ?, ?)", data)
        con.commit()
        con.close() 

          In this code first connected to the database students.db file. From the connection, we get the cursor object. The cursor is used to traverse the records from the result set.We call the execute() method of the cursor and execute the SQL statement. execute method is used for table creation and insert datas in it. the changes must be committed using the commit() method. In the final step, we release the resources.

Show Entries


           For displaying retrieved data in specific format you should use templates. the templates can handle variables.so it is very easy to handle retrieved data in specific order.

cur.execute("SELECT * FROM student")
rows = cur.fetchall()
entries = [dict(name=row[0], sex=row[1], age=row[2], mark=row[3]) for row in rows] return
render_template('show.html', entries=entries) 

         The SQL statement SELECT * FROM selects all data from student table.The fetchall() method gets all records. It returns a result set. Technically, it is a tuple of tuples. We print the data to the console, row by row.where the entries are passed to the template show.html.render_template is used for rending template into page.

The template show.html :

<!doctype html> 


<link rel=stylesheet type=text/css href="{{url_for('static',filename='style.css')}}">
<div class=metanav> 
<p><a href="/">home</a></p>
</div>
<h1>STUDENTS DETAILS</h1>
{%block body%}
<u1 class=entries>
{%for entry in entries%}
<li>{{entry.name}} {{entry.age|safe}} {{entry.mark safe}}
{%else%}
<li><em><center>Unbelievable. No entries here so far...!</em></center>
{% endfopr %}
</ul>
{% endblock %}

HTTP method


                HTTP knows different methods for accessing URL.We use two methods in this example, GET and POST.

@app.route('/details', methods = ['POST', 'GET']) 


           By default, a route only answers to GET requests, but that can be changed by providing the methods argument to the route() decorator.Using GET request The browser tells the server to just get the information stored on that page and send it and POST request is used for telling the browser  the server that it wants to post some new information to that URL and that the server must ensure the data is stored and only stored once.

For running the application use the command:

python students.py 

          The local server is now running visit http://127.0.0.1:5000/. You can see application in your browser.

if you want to see full source code, check out the link: https://github.com/rahulthrissur/Flask_app







Thursday, 7 February 2013

Google App Engine

        Google App Engine lets you run web applications on Google's infrastructure. With App Engine, you only pay for what you use. There are no set-up costs and no recurring fees. App Engine applications are easy to build, easy to maintain. Different data storage options it can be provided. In App Engine there is no servers to maintain an application. The applications are generally build and test on your local host, after the successful test it will upload  to Google, then it's ready to serve users.

         You can build your app using  Python , Java  , Go runtime  environments. These runtime environments are built to ensure that your application runs quickly, securely, and without interference from other apps on the system. App Engine can deal with heavy amount of data and it provide following 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
         This post will consider only the App engine with Python environment. Using these environment you can implement your app in Python programming language and run it on an optimized Python interpreter. The Python environment provides rich Python API's for the data store, Google accounts,  URL fetch and email services.   
 
         For our app engine implementation  use Python 2.7(download ) version, and  use the Python software development kit(download). The SDK versions are available for Linux, Mac-Os and Windows. Download  SDK for Linux and unzip it on your home, we will only handle  Linux Development environment.

Basic application development


          Let's begin by implementing a tiny application that displays a short message "Hello World". Create a directory helloworld. All the files for this application inside in these directory. Inside the helloworld directory, create a file name helloworld.py  and copy  the following contents

import webapp2

class MainPage(webapp2.RequestHandler):
  def get(self)
      self.response.headers['Content-Type'] = 'text/plain'
      self.response.write('Hello, World!')

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

         This Python script responds to request with an HTTP header that describes the content and message hello, world!, the webapp2, it is a light weighted web frame work for Python. The webapp2 application has two parts a request handler and a WSGIApplication. The requestHandler classes that process request and build response. The WSGIApplication instance that route incoming request to handle based on URLs.

        Next step to create a configuration file. An App Engine  applications has configuration file called app.yaml, this file describes which handler scripts should used for which URLs. Inside the helloworld directory, create a file named app.yaml and copy  the following contents.

application: helloworld
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /stylesheets
  static_dir: stylesheets

- url: /.*
  script: helloworld.app
Now you can test your first app using SDK using the command 
google_appengine/dev_appserver.py helloword/
The web server is now running visit http://localhost:8080/ you can see the message Hello, world!

Implementing a Student application

         Considering an example student information system.The application will provide you enter details of  students and  will get back all data by sorting order by mark and age, also providing delete option and search option.
Source code is available in github, you can clone it into the your local machine by running the code
git clone git@github.com:rahulthrissur/studentapp.git
Now you can see a folder in your local machine as student.


student/
 app.yaml
 test.html
 test.py
Just go through the some parts of code, for these application changed the app.yaml file as 


- url: /.*
  script: <python file name>.app
From python script test.py
app = webapp2.WSGIApplication([('/', MainPage),('/details', details), ('/sort1', sort1), ('/sort2', sort2),('/search',search), ('/remove', remove), ('/searchresult', searchresult)],
 debug=True)
The WSGIApplication that use to route incoming request to handle based on URLs. Here define all URLs and corresponding routing. 
Using class define all the pages.
class <page name>(webapp2.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'html'
    self.response.write("html contents")
You can write simple html file  inside the python script but it is not a good practice, use always templates, will discuss later.
Designing of html page refer  the links

Consider the next page 'details'.
class details(webapp2.RequestHandler):
 def get(self):
  self.response.out.write(template.render("test.html",{}));
 def post(self):
  name=self.request.get('student_name')
  sex=self.request.get('sex')
  age=self.request.get('age')
  mark=self.request.get('mark')
  data=student(key_name =name, Name=name, Sex=sex, Age=age, Mark=mark)
  data.put()
  self.redirect("/")
The get part of the page use a template, test.html file to provide enter the details of student. The test.html file was defined separate and rendered to python script. To use templat in python script import:

from google.appengine.ext.webapp import template
 The template is separate the presentation document from its data, also handle the variables in template files.
The  post part of the page get the values from the test.html and store it in variables. For handling data, define a class. Define the table name  and entry details.

from google.appengine.ext import db
class student(db.Model):
 Name = db.StringProperty()
 Age = db.StringProperty()
 Sex = db.StringProperty()
 Mark = db.StringProperty()
Selt.redirect use to redirect to main page
self.redirect("/")
Now retrieve the stored data using GQLQuery. Get data from the table student sort by age. Using a iteration function  separate all the data.

self.response.write("Details of all student sorted by Age")
  data = db.GqlQuery('SELECT * FROM student ORDER BY Age ASC')

  self.response.headers['Content-Type'] = 'text/plain'   
  for i in data:
      self.response.write('\n'+i.Name +' '+i.Sex+' '+i.Age+' '+i.Mark+ '\n')
For delete the details of student using key_name, was set when storing data.
address_k = db.Key.from_path('student', <key_name>)
db.delete(address_k)
For searching  detail of a student by name.
For running the application use the command
google_appengine/dev_appserver.py student/
The web server is now running visit http://localhost:8080/

Upload the application

You can it upload into Google server. Follow the steps:
First register the application using the link  https://appengine.google.com/

Edit the app.yaml file, then change the value of application: setting from helloworld to your registered application id(my id  myApp1) and using the command upload

google_appengine/appcfy.py update student/ 

Now run your application from Google server.

if you want to see full source code , here is the link:https://github.com/rahulthrissur/studentapp

Thursday, 10 January 2013

PYGAME- “Sierpinski Triangle”

           
             The Sierpinski triangle fractal was first introduced in  1915 by Waclaw Sierpinski , who described some of the triangle’s interesting properties .  The Sierpinski triangle is a geometric pattern formed by connecting the  midpoints of the sides of a triangle. It is at the s most  interesting and  simplest fractal shapes in existence. Because one of  the neatest things about Sierpinski's triangle is how many different and easy  ways there are to generate it . This is one of the basic examples of self-similar  sets, that is  it is a mathematically generated pattern that can be reproducible at any  magnification or reduction.

Construction


  1)  Start with any triangle in a plane. The canonical Sierpinski triangle uses a
       equilateral triangle with a base parallel to the horizontal axis

  2)  Connect the midpoints of each side to form four separate triangles, and  cut
        out the triangle in the center

  3)  Each of the three  remaining triangles, perform this same act








Formation after each iteration
-->

Tuesday, 8 January 2013

PYGAME- “ Koch Snowflake ”


 
-->
             Fractals are one example of "algorithmic art" . Here discussing about a particular kind of fractal known as the Koch Snowflake. A fractal is an image that keeps on repeating itself every new time it gets smaller and smaller. The snowflake is a fractal of the Koch curve. Helge von Koch who is responsible for the snowflake. He wrote about the fractal snowflake in a paper written in 1906. The most interesting part about a Koch snowflake is that when you continue this creating process the curve is infinitely long but has an finite area. This means the the sides of the snowflake are never ending but at the same time the area it encloses is only going to be 1.6 times bigger then the original area of the original triangle. 

-->

Design Steps


Constructing a Koch snowflake is a 
 step by step process.

Step1

Start with an equilateral triangle.

Step2


Split each side into three equal segments.

step3


Create an smaller equilateral triangle in the middle of the three parts from step 2

step4


Remove the line segment that is the base of the triangle from step 3

-->
              If you continue repeating this procedure, the curve will never self-intersect, and in the limit you get a shape known as the Koch snowflake. Each time you repeat the process this is call an iteration. To find the number of sides all you need to know is how many iterations you have completed.