Install Javascript shell

If you are familiar with Python, you will be liking its interactive command prompt. Because we can experiment its features on the fly in terminal. Similarly if you wish to play with javascript in terminal we have some standalone javascript shells. You can find a list of useful links from here.

Recently I have installed javascript shell from spider monkey  source distribution. I feel  it will be a handy tool for you.

Pre-requisites:

1) Mercurial version control. (Hg)

2) autoconf2.13 ( I installed it from synaptic package manager. It is the easier way)

Here is the step for the installation:

1) Get the spidermonkey source code.

Just copy this in your terminal:

  hg clone http://hg.mozilla.org/mozilla-central/

the source code will be downloaded to the folder ‘mozilla-central’.

2)

 cd mozilla-central/

3)

cd js/src

4)

autoconf2.13

5)

./configure

6)

make

A simple decorator in Python

Decorators are very useful functionality in Python. Here am going in a straight forward way to get a quick basic idea about what a decorator means. You can find what is a decorator and more details from here.

Excerpt from python wiki about decorator: A decorator is the name used for a software design pattern. Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.

Lets go through an example.

@login_required
def account_settings(request):
    #some code

Here login_required is a decorator. Decorator is nothing but another function. But it’s functionality is different. While running this code, when the python interpreter see some decorator ( here it is login_required) it calls the decorator with the below function as argument (that means ‘account_settings’ as argument). Then we can do some preprocessing  with the function inside decorator. Such as, using the details from function arguments we can check whether user is logined or not, if not logined redirect to login page etc.

In short using a decorator we can do some action before a particular function is called.( can do more than this!).

So how a decorator look like. Am giving a simple outline of a decorator:

def login_required(func_name):
    def decorator(request, *args, **kwargs):
       #if not logined:
           # redirect to log in page
       #else:
           #allow to access settings
     return decorator

Some points:

1) The inner function name ‘decorator’ is optional. You can choose a different name also. But you should return that name in the end. That means if you use the name ‘myfunc’ as function name, then you should return ‘myfunc’.

2) If you are sure about the number of parameter and its type you can use it directly as inner function (here ‘decorator’) parameter. If you know there should be two parameters(say ‘a’ and ‘b’ ) for account_settings function, then you can define inner function as ‘decorator(a,b)’ .

if you want to know more about decorators, this is a good tutorial.

how to add a script tag inside a jquery template.

You cannot directly add a script tag inside a jquery template.

suppose you want to add a script tag inside a jquery template in the following way:

<script id="filaVideoTemplate" type="text/x-jQuery-tmpl">
<!-- Some HTML here -->
<script type="text/javascript">
<!-- Some javascript here -->
</script>
</script>

This will not work.Because browsers don’t understand nesting of tags, so whenever it parses a , it closes the outermost script tag.

You should write  ” </scr{{= “”}}ipt>  “instead of closing the inside script directly as  ” </script> “.

so that the code look like:

<script id="filaVideoTemplate" type="text/x-jQuery-tmpl">
<!-- Some HTML here -->
<script type="text/javascript">
<!-- Some javascript here -->
{{html "</sc"+"ript>"}}
</script>

so this is the solution.

Further for the django developers, this is not the solution.
because ‘{‘ and ‘}’ are reserved characters in django templates. so instead of writing
{{html “</sc”+”ript>”}}
we have to write:
{% templatetag openbrace %}{% templatetag openbrace %}html “</sc”+”ript>”}{% templatetag closebrace %}{% templatetag closebrace %}

This will work for django templates.

socket programming using python

Networking is an essential task in software applications nowadays.Python is a powerful language for network programming. Python support both low level and high level access to network services. At a low level, we can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols. Python has a socket module to support socket programming. Python also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.

The following are some of the key concepts in network programming.

Sockets
Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents.Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on.
Then what is a port in a socket? A socket directs to a particular computer in a network. Once connection reaches on a computer it want to identify the application it can connect. Port’s are made for this purpose. In a computer there will be thousands of ports in it. first 1234 ports are reserved for system and rest of ports can be applied to user applications. Each port is assigned with an application and it waits for an application to connect.

TCP and UDP:
In order to transmit data between client and server in the internet we depend on TCP and UDP protocols. So what are them? and what is the difference between them?

TCP (Transmission Control Protocol) is a set of rules (protocol) used along with the Internet Protocol (IP) to send data in the form of message units between computers over the Internet. UDP is an alternative to TCP. But there is major difference between them in the case of data transmission.

More specifically TCP is connection oriented protocol. TCP provides reliable, ordered delivery of a stream of bytes from a program on one computer to another program on another computer. We use this protocol where we each byte of data is important. In the delivery of a email we would not like to miss any byte of data, situations like these where each byte of data is important, needs reliable transmission. TCP/IP are used in situation like these and it has proper error checking mechanism in the destination to ensure that all bytes of data is reached at the destination in order. Here the correctness is more important than delivery time.

But there are some other situations where we need data to be reached in the destination within some time constraint, here the correctness of data may be tolerated to some extend. For example in real time video streaming we need bytes of data with in its streaming time. In such application’s it is not important whether the data comes in order or data comes from the same server. we just need all data in time. Even if data reached the destination out of order it should have proper mechanism to rearrange the byte order, it also adjust the data lose to some extend. In such situation’s we depend on connection-less protocol such as UDP. Applications, which do not need reliable data stream service, may use the User Datagram Protocol (UDP), which provides a datagram service that emphasizes reduced latency over reliability.

I will come back with some examples in my next post…

How to host a django project in google appspot

Do you have a project developed in Django and want to host it somewhere.? You are in right place!.  Google app engine support hosting Django projects. But you have to make some changes in your project including your Django’s ORM.

The prerequisite to do this conversion:
* installed Google Appengine SDK.
* installed django.

Google App Engine supports running any WSGI compliant application. Since Django supports this standard it is possible to build (or port existing) Django applications to run on Google App Engine.

your django project may contain the following files:
__init__.py     —   tells Python this is a package
urls.py               —   global URL config (“URLconf”) file
settings.py       —   project-specific configuration
manage.py       — command-line interface for apps

‘your app directory’ contains the following files:
__init__.py    — same as above
models.py        — data models
views.py           — request handlers
tests.py             — unit tests (optional but strongly-encouraged)

Inorder to convert your project to GAE do the following steps:

1) Create a directory for the appengine version of your project. Lets call it ‘my_gae_project’.

2) Inside the directory create a ‘app.yaml‘ file which may look like this.
3) copy this main.py and settings.py files to your application folder. You dont need to change the content of these files.
4) copy views.py and urls.py files from your django project to ‘my_gae_project’.

5) inside urls.py ,if there is ‘admin.autodiscover()’, remove that line.
ensure that you have given correct path for url mapping.

6) Google App Engine does not provide an SQL database so you cannot use Django’s standard Model class. So you have to convert your database models that suit to App Engine models (from google.appengine.ext import db). get help from : http://code.google.com/p/google-app-engine-django

This is not a big deal. you can do this with little effort, and put these new database models inside view.py.

also change the queries used inside the views.py file to GQL.

7)Google App Engine restricts certain module imports and actions that Django tries to perform (such as creating and removing the test database). Appengine have a helper that prevents you from needing to worry about most of these differences.

ex: ‘ from django.shortcuts import get_object_or_404’. we have to remove all such import from our views.py.

8 ) create a ‘template’ directory inside current directory and place all your template files( html files) inside a template directory .

9) create a ‘static’ directory and place all your static files inside that directory.

now your directory structure look like this:

my_gae_project
-‘static'(directory)
-‘templates'(directory)
-app.yaml
-main.py
-settings.py
-urls.py
-views.py

now you can deploy your django site to appengine as you are deploying your appengine project.

(The above methode worked for my url shortening project. Here is the link . Hope this will work for you too. Best wishes…)

SCALA

    Just few days ago , I started to learn SCALA. Scala is pretty new language to the programming arena. Not many people using this language right now. But I found it very interesting to work with it. It has the power of functional programming and object orient programming. Technically, Scala is a blend of object-oriented and functional programming concepts in a statically typed language. Though it has the disadvantage of statically typing language , it provide a powerful and concise way to write applications. You can apply Scala to a wide range of programming tasks, from writing small scripts to building large systems. Scala is easy to get into. It runs on the standard Java platform and interoperates seamlessly with all Java libraries.

     If you want to install scala from linux it is enough to type ‘sudo apt-get install scala’ from terminal. Also you have to install java if it is not there.

A simple example with scala interpreter:

I would like to show a simple example that shows you how scala program really interpret its input. In order to work small example use scala interpreter by typing ‘scala’ from terminal.

 jinesh@jinesh-Compaq-Presario-CQ40-Notebook-PC:~$ scala
Welcome to Scala version 2.7.7final (OpenJDK Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.
scala> 1+2
res0: Int = 3

really here ‘+’ is not an operator. In scala every operation is function call. when you type 1+2 what actually happens is (1).+(2)

‘1‘ calls function + with arguement 2, and the + function is predefined to calculate the sum of its input.Thus, when you typed 1 + 2 into the Scala interpreter in Step 1, you were actually invoking a method  named + on the Int object 1, passing in 2 as a parameter.

 Let’s look another example.

The following function returns the largest of two numbers.

scala> def max(x: Int, y: Int): Int = {
if (x > y) x
else y
}
max: (x: Int,y: Int)Int

When contrast to other languages scala defines type of variables after the variable name.  Also the return type is specified just after parameter list braces.

 FUNCTIONAL WAY OF PROGRAMMING.

If you want to write a script just make a file with ‘scala’ as extension (eg: ‘filename.scala’). Inorder to run type ‘scala filename.scala’.

The following script read an input string from terminal and print it on the console.

// save this script as echoargs.scala
var i = 0
while (i < args.length) {
if (i != 0)
print(" ")
print(args(i))
i += 1
}
println()

if you run this script it will produce the following output.

‘scala echoargs.scala scala is more fun’

output: scala is more fun

But this is not the way of functional programming. Infact this is our old way of approaching in statical way. You can implement the same problem in a different and concise way using ‘foreach’.

args.foreach(arg => println(arg))