Saturday 22 October 2011

AJAX & Web.py : how to load a data from a server by using jQuery.get() method.

We have already discussed some basic ideas about ajax and web.py in the previous post ,so now we are going to discuss some more functions that you can perform with ajax.

The Jquery.get() method is used to perform AJAX HTTP GET request.This is an easy way to send a simple GET request to a server.It allows a single callback function to be specified,that will be executed when the request is completed.


Syntax :   jQuery.get ( url , [data] , [callback] , [type] )


url          :  The corresponding URL to load.
data        :  key/value pair that will be send to the sever (*optional).
callback :  (Function) A function to be executed whenever the data is loaded successfully (*optional).
type        :  Type of data to be returned to callback function "xml","html","script","json" etc (*optional).


Now lets look at the working of JQuery.get() method here with the help of an example.


Qn: create a web.py URL that should return a random number between 1 & 1000,and create another URL it should display a text box and a button,when you hit the button,random numbers should be displayed inside the text box.


Before we are going to start You have to create a directory named static in the same folder where you are going to create this application.The HTML template will put in this directory.
First of all you all know that you have to map the URL's to the corresponding classes,here the root URL will map to 'rand_num' class and the second URL ('/random') will map to the 'return_num' class.

If we are using any HTML templates you have to define it by using the line 'render=web.template.render('template/'),then only it can fetch the code from the template directory,that why we already created a directory called template.


our web.py program displayed below.


program name : random.py


import web
import random

urls = (
    '/', 'rand_num',
    '/random','return_num')

app = web.application(urls, globals(), True)
render = web.template.render('templates/')


class rand_num:
    def GET(self):
      return render.random()

class return_num:
    def GET(self):
      return  random.randint(1,1000)

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


Then we have to define the class('/rand_num') for the root URL. the root URL should have to display a text box and a button,so that you have to call the corresponding HTML template ,here the method render.random() will returns a rendering of the HTML template 'random'.you have to specify the exact name of the html template that located in the templates directory here to fetch it from the directory when the code runs.


After that we have to define the class ('return_num') for the random number generation i.e when the browser get form this URL,it should return a random number between 1 - 1000 .We have a module in python called random ,by importing this module we can call random.randint() method to get random numbers between certain ranges,here we can use random.randint(1,1000) to get the random numbers between 1-1000.


Now lets look at the html template 'random.html' located in the templates directory.


<html>
        <head>
        <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script>
        
        <script type="text/javascript">
        jQuery(document).ready(function(){
        jQuery("button").click(function(){
          jQuery.get("/random",function(result){
             jQuery("#text1").val(result);
          });
        });});
        </script>
        </head>

        <body>

        <input type = "text" id = "text1" />

        <h2>Hit the button to view random numbers</h2>

        <button>Click</button>

        </body>
</html>


Here the url ("/random") specified in the jQuery.get() method specifies the corresponding url to load.and then the callback function specified here will execute when the data is loaded successfully.


Here when we press the button the jQuery.get() method will invoke and it will load the url "/random'.we have already defined the "return_num" class for the "/random" url that ,it returns only a random number between 1-1000.So when the data i.e (random number) is loaded successfully,then the callback function will execute and variable name "result" will contain the returned value.Then finally we just displayed it inside the text box.

Sunday 7 August 2011

Unix tool : make

The make utility is a software engineering tool for managing and maintaining computer programs.Make  provides most help when the program consists of many component files.
By creating a descriptor file containing dependency rules,macros and suffix rules,you can instruct make to automatically rebuild your program whenever one of the program's component files is modified.

To prepare to use make ,You must write a file called makefile the describes the relationships among files in your program,and the states the commands for updating each file.In a program,typically the executable file is updated from object files to decide which of the file needs to be updated.For each of those files,it issues the commands recorded in the data base.

Simple example:

This is an example descriptor file to build an executable file called prog1.it requires the source file file1.cc,file2.cc,and file3.cc.An include file mydefs.h,is required by files file1.cc and file2.cc.If you wanted to compile this file from the command line using C++ the command would be
        %  CC -o prog1 file1.cc file2.cc file3.cc
This command line is rather long to be entered many times as a program is developed and is prone to typing errors. A descriptor file could run the same command better by using the simple command
    % make prog1
or if prog1 is the first target defined in the descriptor file
    % make
No we are going to see how to write a descriptor file,this example descriptor file is much longer than the necessary but it is useful for describing what is gong on.

prog1 : file1.o file2.o file3.o
        CC -o prog1 file1.o file2.o file3.o
  
file1.o : file1.cc mydefs.h
        CC -c file1.cc
  
file2.o : file2.cc mydefs.h
        CC -c file2.cc
  
file3.o : file3.cc
        CC -c file3.cc
  
clean :
        rm file1.o file2.o file3.o
 


Let's go through the example to see what make does by executing with the command make prog1 and assuming the program has never been compiled.
  1. Make finds the target prog1 and sees that it depends on the object files file1.o file2.o file3.o

  2. make next looks to see if any of the three object files are listed as targets. They are so make looks at each target to see what it depends on. make sees that file1.o depends on the files file1.cc andmydefs.h.

  3. Now make looks to see if either of these files are listed as targets and since they aren't it executes the commands given in file1.o's rule and compiles file1.cc to get the object file.

  4. make looks at the targets file2.o and file3.o and compiles these object files in a similar fashion.

  5. make now has all the object files required to make prog1 and does so by executing the commands in its rule.

Unix tool : AWK

What is AWK?


AWK is a programming language designed for processing text-based data, either in files or data streams. It is an example of a programming language that extensively uses the string datatype, associative arrays , and regular expressions.

There are three variations of AWK:

AWK - the original from AT&T
NAWK - A newer, improved version from AT&T
GAWK - The Free Software foundation's version

AWK is an excellent filter and report writer.AWK also has string manipulation functions, so it can search for particular strings and modify the output.

The essential organization of an AWK program follows the form:

pattern { action }

The pattern specifies when the action is performed.i.e the pattern specifies a test that is performed with each line read as input. If the condition is true, then the action is taken. 


Lets look some examples,First of all create a file named "file1.txt", and write somthing like "unix tool awk " in the body and then save,then type the following command in terminal


$awk '{print $1}' file1.txt

The output will be
'unix', i.e it will print the first word in the body of the file.

Two other important patterns can be specified by the keywords "BEGIN" and "END.",these two words specify actions to be taken before any lines are read.and after the last line is read.THe AWK program below:


  BEGIN  ( print "START" )
                 ( print                    )
  END       ( print "STOP"    )


We can make this into a typical AWK program :


Firt of create two files like "sample1.txt "with body " sam 15 groupA" & "sample2.txt" with body "neil 13 groupB" ,then write our AWK program as described below and save the file with extention (.awk) in the same directory that your sample file resides  ,Here my awk program will be "file1.awk"


 AWK is also an interpreter,Here we making the file executable by adding the first line in the beginning of the file i.e (" #!/bin/awk  -f ").

programe name : file1.awk

#!/bin/awk -f

  BEGIN { print "Name\tAge\tGroup" }

  { print $1, "\t" ,$2, "\t" ,$3 }

  END { print " - DONE -" }



Then change the permission with the chmod  command (i.e "chmod +x file1.awk" ),and then the script becomes a new command.Here the "-f" option following "#!/bin/awk"  make the file execute directly i.e " awk -f file1.awk".

Then run the file by typing "$ awk -f file1.awk sample1.txt sample2.txt" in your terminal.then you will get the following output.
sreehari@~/sed awk make/awk09:54:02$ $awk -f file1.awk sample1.txt sample2.txt

    Name     Age   Group

    sam      15    groupA

    neil     13    groupB

    - DONE -



This is just a brief introduction to on AWK,You can find more about AWK by using the following document. AwK-Tutorial

Unix tool : Sed


What is Sed?


This post will help you to get the answer of the above question,The same question persuaded me to understand the concept and also to write this post about what i have learned about Sed.

sed(stream editor) is a tool which allows you to perform large-scale, noninteractive editing tasks. For example, sed can replace all the occurrences of a given word in a file with a different word, or delete all lines containing a target string from a file.Sed is particularly used when working with large files .

Substitution command  S:

Sed has several commands,but the essential command i.e used by most is substitute command : S
The substitute command changes all occurrences of the regular expression into a new value.

To try this command , create a file named "file1.txt" and write something like "sed is fun" in the body of that file,then run the following command in terminal.

      $sed s/fun/cool/ <file1.txt >file2.txt

After you run the command you can see a new file created in the same directory with a name file2.txt , when you open the file you can see that the text is changed to "sed is cool".here the command will substitute the content "fun" in the old file (file1.txt) to "cool" in the new file (file2.txt).

Try the following command those who want to test the working in terminal.
  
      $echo fun | sed s/fun/cool/

This will output as "cool" in terminal.

      $echo sed is fun | sed 's/fun/cool/'

This will output as "sed is cool" in terminal.

There are four parts to this substitute command:

s                      Substitute command.
/ . . / . . /          Delimiter.
fun                  Regular Expression Pattern Search Pattern
cool                 Replacement string. 

The search pattern is on the left hand side and the replacement string is on the right hand side.

Using "&"as the matched string :

By using the "&" symbol you can match the patterns as you like,

      $echo sed is fun | sed 's/[a-z][a-z][a-z]/(&)/'

This will ouput as " (sed) is fun ",  [a-z] matches single letter ,here 3 [a-z] will match 3 letters like(sed).

You can have any number of  "&"  in the replacement string,like

      $echo sed is fun | sed 's/[a-z][a-z][a-z]/(&&)/'

This will output as "(sedsed) is fun".

If you want to match the entire string then you have to make changes like,

      $echo sed is fun | sed 's/[a-z]* [a-z]* [a-z]*/(&)/'

  It will output as " (sed is fun)".

If you want to display the matched string 3 times then try,

      $echo sed is fun | sed 's/[a-z]* [a-z]* [a-z]*/(&)(&)(&)/'

The output will be "(sed is fun)(sed is fun)(sed is fun)".

If we have a text file like "sed is fun 123",then you should change the code like this to get the whole text inside the bracket.
   
      $echo "sed is fun 123" | sed 's/[a-z]* [a-z]* [a-z]* [0-9]*/(&)/'

Then the output will be "(sed is fun 123)".

Using \1 to keep part of the pattern:-

If you want to remove the numbers from the above example,then you should try like,

     $echo sed is fun 123 | sed 's/\([a-z]* [a-z]* [a-z]*\).*/\1/'

It will remove the numbers and the output will be "sed is fun".

If you want to switch the words around, you can remember the patterns and change the order around:

     $echo sed is fun 123 | sed 's/\([a-z]*\) \([a-z]*\) \([a-z]*\).*/\3 \2 \1/'

The output will be "fun is sed".

Substitute flags:

You can add additional flags after the last delimiter. These flags can specify what happens when there is more than one occurrence of a pattern on a single line, and what to do if a substitution is found.

      $sed 's/[^ ]*/(&)/' <file1.txt>file2.txt

This will put parenthesis around the first word, i.e the first word in the body of your second file have a parenthesis around it.

If you want it to make change of  every word add a "g" after the last delimiter and use the work-around:

      $sed 's/[^ ]*/(&)/g' <file1.txt>file2.txt

The output will be "(sed) (is) (fun)".

These are some basic commands ,there are several other commands that can be used with Sed.


Tuesday 26 July 2011

AJAX & web.py : some quick reference



This post will give you some basic ideas about how to use AJAX with web.py. 

You all know that web.py is a simple web framework for python,the main thing i liked about web.py is that it is very simple to use and more effective too.web.py frame work can run its own basic web server .

About AJAX(Asynchronous Java script and XML) you all know that it is very helpful to create interactive web applications.With Ajax, web applications can send data to, and retrieve data from, a server asynchronously , i.e you can updates the parts of web page without reloading the whole page.

So here i would like to describe some examples that we can experiment with AJAX & web.py.

The Ajax application that we are going to discuss here contain one "div" section and a button. The "div" section will be used to display the contents return form the server.


<html>
<body>
          
<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>

</body>
</html>


With jQuery AJAX, you can request TXT, HTML, XML or JSON data from a remote server using both HTTP Get and HTTP Post.And you can load remote data directly into selected HTML elements of your web page!

Next, add a <script> tag to the page's head section. The script section contains the AJAX load function.The jQuery load() method is a simple AJAX function. It has the following syntax:

$(selector).load(url,data,callback)

Next we are adding the <script> tag  under <head> section,This section contains jQuery load method.

<head>
      <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery 1.4.2.min.js"></script>
      <script type="text/javascript">
      $(document).ready(function(){
        $("button").click(function(){
           $("div").load("http://127.0.0.1:8080/static/test.txt");    
        });
      });
      </script>
 </head>



Here the  load function will load desired contents from the specified URL.(What this URL actually functions is described in the below section,you will get exact picture after you read the whole thing)

Next we are going to implement this code with web.py.


Before we move on to web.py,We have to create a folder named "static" in the same folder that your program resides,and put your text file (here the file is "test.txt" ) inside the "static" folder.Then check that you are able to access the file by typing the URL (" http://127.0.0.1:8080/static/test.txt ") in your browser search bar.If the browser displays the contents properly then you can implement this on aJax load function.


The whole program described below.


Program name -- Code.py

import web

  urls = (
    '/', 'main')


  app = web.application(urls, globals(),True)


  class main:
      def GET(self):
          return'''
          <html>
          <head>
          <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script>
          <script type="text/javascript">
          $(document).ready(function(){
            $("button").click(function(){
              $("div").load("http://127.0.0.1:8080/static/test.txt");
            });
          });

          </script>
          </head>
          <body>
            
          <div><h2>Let AJAX change this text</h2></div>
          <button>Change Content</button>

          </body>
          </html>'''


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


How to run the program:


Web.py comes with a built-in web server that you all know. We have created our program file called  " code.py ",just save the file and  run the following command in terminal to start your application.


sreehari@sreehari-desktop:~/web.py$ python code.py
  http://0.0.0.0:8080/



Then goto your browser and type " http://127.0.0.1:8080/ " in your search bar , you will get a web page with a text " Let AJAX change this text " and it also contains a button,when you hit the button the text will change and new text from the text file will be loaded and displayed in your browser.

Monday 18 July 2011

A simple exercise in web.py

 This is just a simple exercise that will help you to understand the basics of web.py.

Qn: Create a webpage that should contain a text box,so that you can input your names,the page should also provide a submit button to submit the details that you entered in a text box.when you submit it the names should be saved in a text file and whole the names that we entered should be displayed in another URL.

1st step: Import the module Web.py,to use the tools provided by web.py. Map the first URL (" / ") to a class named "main".and map the second URL ("/Details") to a class named  "details".


import web

  urls = (
    '/','main',
    '/Details','details')

  app = web.application(urls, globals(), True)


2nd step: Next we have to define the class named "main".The function GET() is actually displays the content in your browser when you opens a webpage.When you opens the first page it should displays a form,so thats why ,we are writing the HTML code to create a form under GET() function.Here we are specifying the method attribute of form as POST to invoke the POST request .

class main:
    def GET(self):
    return'''
    <html>
    <head>
    <title>web.py</title>
    </head>

    <body>

    <h1>A simple exercise in web.py</h1>

    <form name="form" method = "POST">

    Name: <input type="text" name="user"/>

    <input type="submit" value="Submit" />

    </form>
    </body>
    </html>'''



3rd step: The GET() function that we introduced above will only serve the pages ,but here we have to update the values to another webpage.Thats why we are using a POST function.The line "form = web.input()" creates a storage objects that contains all  variables passed into it.Then we open a file named "file.txt" in append mode,then write the input values  into the file by using " f.write(form.user) ". Then Web.redirect('/Details') will redirect the user to a new URL(" /Details ") ,i.e when we submit the form it will guide you to the next page that contain all the details that you entered before.

def POST(self):

   form =  web.input()
   f=open("file.txt",'a')
   f.write(form.user)
   f.write("\n")
   f.close()

   raise web.redirect('/Details')

4th step: We have to define the class for the URL("/Define").Here we are using GET() function to display the contents.so to displays the contents in the text file we just simply opens the file in read mode.and then read the values by using "f.read()" function and then assigned it to a variable named data,when we return the variable it will displays all the values that we read from the text file in the next URL.

class details:

  def GET(self):

    f=open("file.txt",'r')
    data=f.read()
    return data
    f.close()


Complete code:


Program name: Code.py

import web

urls = (
  '/','main',
  '/Details','details')

app = web.application(urls, globals(), True)

class main:
   def GET(self):
    return'''
    <html>
    <head>
    <title>web.py</title>
    </head>

    <body>

    <h1>A simple exercise in web.py</h1>

    <form name="form" method = "POST">

    Name: <input type="text" name="user"/>

    <input type="submit" value="Submit" />

    </form>
    </body>
    </html>'''

    def POST(self):
 
      form =  web.input()
      f=open("file.txt",'a')
      f.write(form.user)
      f.write("\n")
      f.close()

    
      raise web.redirect('/Details')
    
class details:
    
    def GET(self):

      f=open("file.txt",'r')
      data=f.read()
      return data
      f.close()

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

Sunday 10 July 2011

Web.py : Installation and working


Web.py is a simple web frame work that is written in python for the development of python related web applications.The main feature about web .py is that it is very simple and efficient compared to others


Installation:-

  • Download web.py from the below link.Then extract and copy it into to any directory that your application resides or make it accessible to all applications.
  • Type "cd" in Terminal to "change the directory "where you copied web.py, If you list the contents you  can see a setup.py file inside it. To install the file type the below command.
                            python setup.py install.
  • when you found any permission denied messages when installing in unix like systems,switch to root user and then try the below command.
                            sudo python setup.py install


Working:-


    when you installed it properly you can try it by creating some simple webpages.Open any of your favorite  editor and  creating a file named "hello.py" as shown below.



import web

urls = (

  '/', 'hello')

app = web.application(urls, globals())

class hello:

    def GET(self):

        return 'Hello, web!'

if __name__ == "__main__":

    app.run()



Here  first you need to import the module web.py to use the tools provided by web.py i.e the first line actually refers.


In the second line we are actually mapping the web address(URL) i.e "http://webpy.org/" to a python class    named "hello".


Inside the class you can see a function named  "GET()".This  function "GET()" is actually displays the content  in your browser when your browser opens a web page.Here it will display the string "Hello,web" .


In the third line we are creating an instance .It will handle the all duties like handling the browser request and   serving the desired pages.


The last line will start the web application to handle your requests.


Save the above file and run by using the command python hello.py.


when you run the file,the output will be the address of your website ,by default it is (http://localhost:8080/).    when you copy it and paste it in your browser search bar you will get the resultant web page.

Tuesday 28 June 2011

Python : Interesting String & List

Here i would like to share some interesting behavior of String & List when you use python interpreter.


String:-


We all know that the fundamental thing about Python Strings is that they are "Immutable" ,once you created a string you couldn't change it. See some examples....


>>> s = 'fun with string'
>>> s
'fun with string'
>>> 

you can just add another string by using  '+'  as shown below...

>>> s + '!!!!'
'fun with string!!!!'
>>> 

Another important feature is String Slices. Just see how "slice" syntax behaves in python.

>>> s = 'fun with string'
>>> s[0]                                                 
'f'
>>> s[1:4]
'un '
>>> s[1:]
'un with string'
>>> s[:]
'fun with string'
>>> s[-1]
'g'
>>> s[-4]
'r'
>>> s[:-3]
'fun with str'
>>> s[-3:]
'ing'
>>> 

So now we have a string 's' and we can apply all the methods (i.e functions) that are related to string to 's' as shown below...

>>> s.upper()
'FUN WITH STRING'
>>> s.lower()
'fun with string'
>>> s.startswith('fun')
True
>>> s.endswith('string')
True
>>> s.replace('string','python')
'fun with python'
>>> 



But my favorite is the method called ' s.split() '. Just see what happens if i assigned s.split() function in to a variable 's' itself. If we print it you can see a list of elements.It just transformed into a list.

>>> s = s.split()
>>> s
['fun', 'with', 'string']
>>> 

List:-

So now the variable 's' will behave like  a list.Now you can apply all the methods related to list here with 's'.

>>> s.append('& list')
>>> s
['fun', 'with', 'string', '& list'] 
>>> s.insert(0,'some')
>>> s
['some', 'fun', 'with', 'string', '& list']
>>> s.index('some')
0
>>> s.index('string')
3
>>> s.sort()
>>> s
['& list', 'fun', 'some', 'string', 'with']
>>> s.pop(0)
'& list'
>>> 

See what happens if i call the function " join() ",and assigned it to same variable 's' .When you print 's' you could see the first string.Is it interesting?


>>> s = ['fun', 'with', 'string', '& list']
>>> s = ' '.join(s)
>>> s

'fun with string & list'
>>> 


Thank You....