Sunday 16 December 2012

Scala Certificate

Paint


Thick

Monday 10 December 2012

Python Webapp2 framework and Users Services




Webapp2 is a simple web application framework included in the App Engine.
A webapp2 application has two parts: 

* RequestHandler classes that process requests and build responses.
* WSGIApplication instance that routes incoming requests to handlers based 
   on the URL.

This is a code which defines a simple request handler.
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)
Here MainPage is mapped to the root URL (). The get method sets properties on self.response to prepare the response, then exits. webapp2 sends a response based on the final state of the MainPage instance.


User Services

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)
If the user is already signed in to your application, get_current_user() returns the User object for the user. Otherwise, it returns None. If the user has signed in, display a personalized message using the user.nickname(). If the user has not signed in, tell webapp2 to redirect the user's browser to the Google account sign-in screen.






[Expecting Your Valuable Comments]
Thank You

Iterator, Generator and List Compression





Iterator

An iterator is an object representing a stream of data and this object returns the data one element at a time. A Python iterator needs to support a method called __next()__ .This next () method takes no arguments and always returns the next element of the stream. If there are no more elements in the stream,  __next()__ must raise StopIteration exception. 

Here is the example:
 
 
num= []
i = 0
for item in range(10):
        i = i + 4
        num.append(i)
print num

a = iter(num)
print a.next()
print a.next()  

Output

[4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
4
8
>>> a.next()
12
>>> a.next()
16
>>> a.next()
20

Generators
 
Generator is a function which controls the iterations, stop at a point, save the context and resume from where it stopped last. A generator can generate a sequence of numbers and yields the result one at a time. Since generators return one value at a time they take up less memory and behave similar to an iterator. Generators are usually evoked in a loop.

Here is the simple example:-

def fibonacci():
        a = 0
        b = 1
        yield a 
        yield b
        while 1:
                c = a + b
                a, b = b, c
                yield c
d = fibonacci()




List Compression

List comprehension is a concise way of creating lists. We  use list compression when we need to define operations that are to be applied to each element in the list. It simplifies the code, where we have to use multiple statements to get desired output to a more shorter form.

for a in range(10):

          square.append(a*a)

 Here, this can be also done with single line code as given below:

 square = [a*a for a in range(10)]





[Expecting Your Valuable Comments]
Thank You

Saturday 8 December 2012

Functional Programming





Functional programming is a programming paradigm that treats calculations and computations as the evaluation of functions rather than state. 

Functional languages, I/O, assignments, etc., are completely avoided in this FP. In Python, however, we do not avoid them completely. Instead, a functional like interface is provided . For example, local variables are used inside the function, but global variables outside the function will not be modified. 


Functional programming can be regarded as the opposite of object-oriented programming. Objects are entities that provide functions to modify internal variables. Functional programming aims at the complete elimination of state, and works with the data flow between functions.

In Python, it is possible to combine object-oriented and functional programming. For example, functions could receive and return instances of objects.


Theoretical and practical advantages to the functional style:

1. Formal provability.
2. Modularity.
3. Composability.
4. Ease of debugging and testing.




[Expecting Your Valuable Comments]
Thank You


Friday 7 December 2012

Google App Engine





Google App Engine lets us to run web applications on Google's infrastructure.
We can serve our app from our own domain name using Google Apps. Or, we can serve our app using a free name on the appspot.com domain. Through this Google Apps, we can share our application with our friends, organizations and with the whole world.

App Engine Features:

1. Dynamic web serving, with full support for web technologies
2. Persistent storage with queries, sorting and transactions
3. Automatic scaling and load balancing.
4. APIs for authenticating users and sending email using Google Accounts.
5. A fully featured local development environment that simulates Google App 
    Engine on your computer.
6. Task queues for performing work outside of the scope of a web request.
7. Scheduled tasks for triggering events at specified times and regular intervals.

Google Apps can run in one of three runtime environments: the Go environment, the Java environment, and the Python environment.

Python Runtime Environment

With Google App Engine's Python runtime environment, we can implement our app using the Python programming language. App Engine includes rich APIs and tools for Python web application development. We can also take advantage of a wide variety of mature libraries and frameworks for Python web application development.

Create your first Google App engine project

Before we do anything else, you’ll need to install the Google App Engine SDK. You’ll need Python 2.5 too. You won’t be writing any Python code but the App Engine SDK will need it to run on your computer.

You’ll need to choose a unique ‘application id’ nothing more than a name for your project. Make sure it consists only of lowercase letters and numbers. 

On your computer, create a folder named after your application id.

Create a file app.yaml in that folder. It tells App Engine what to do with your files.And we need to add these lines.

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

- url: /.*
  script: main.py 
Here main.py is the python file where we access our web application file, for example "hunter.html".

For this, we need to add these lines to main.py 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 main1(webapp.RequestHandler):
 def get(self):
           self.response.out.write(template.render("hunter.html",{})) 
  
def main():
    app = webapp.WSGIApplication([
        (r'.*',main1)], debug=True)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()
Where the hunter.html file can be replaced with your application file and place that file in the application id folder.

Registering the Application

Sign in to App Engine using your Google account here.

To create a new application, click the "Create an Application" button. Follow the instructions to register an application ID, a name unique to this application. If you elect to use the free appspot.com domain name, the full URL for the application will be http://your_app_id.appspot.com/. Edit the app.yaml file, then change the value of the application: setting to your registered application ID.

Testing the added appllication

Start the web server with the following command:
google_appengine/dev_appserver.py "path to applicationid folder"
 Now you can test the application by visiting the following URL :
http://localhost:8080/
Uploading the Application
appcfg.py update "path to applicationid folder"
Enter your Google username and password at the prompts.
You can now see your application running on App Engine with the url http://your_app_id.appspot.com.

Click here to see an example:


[Expecting Your Valuable Comments]
Thank You

Wednesday 5 December 2012

CountDown Timer



A countdown is a sequence of counting backward to indicate the seconds, days, or other time units remaining before an event occurs or a deadline expires.

Here is the countdown Timer:
Enter the minute and second in the text box and click set to Set it as the initial value and click Start.


Timer Min Sec



If its not working in your browser properly, Try this timer.

Click here to get the code.



[Expecting Your Valuable Comments]
Thank You

Thursday 29 November 2012

Conway's Game of Life



Game of Life is not as our typical computer games. It is a 'cellular automaton'. This consists of a collection of cells which, based on a few mathematical rules, can live, die or multiply.


The Rules: 

1. Any live cell with fewer than two live neighbours dies, as if caused by    
    underpopulation.

2. Any live cell with two or three live neighbours lives on to the next generation.

3. Any live cell with more than three live neighbours dies, as if by overcrowding.

4. Any dead cell with exactly three live neighbours becomes a live cell, as if by 
    reproduction.


Patterns

Different types of patterns occur in the Game of Life, including still lifes, oscillators, and spaceships, which are the patterns that translate themselves across the board.


           Still lifes

Block Game of life block with border.svg
Beehive Game of life beehive.svg
Loaf Game of life loaf.svg
Boat Game of life boat.svg
                Oscillators




Blinker [period2] Game of life blinker.gif



Toad [period2] Game of life toad.gif



Beacon  [period2] Game of life beacon.gif



Pulsar [period3] Game of life pulsar.gif
                Spaceships

Glider Game of life animated glider.gif
Lightweight spaceship [LWSS] Game of life animated LWSS.gif
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 neighbours 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.



Play the game:





Click here to download 'Game of Life' code.




[Expecting Your Valuable Comments]
Thank You

Sunday 25 November 2012

Generate SSH Key






To use SSH keys to establish a secure connection between your computer and GitHub. Here is the steps to generate SSH keys and adding the public key to your Github account.

Step 1: Check for SSH keys

 Check for existing ssh keys on your computer by running the command given below:
$ cd ~/.ssh 
# Checks to see if there is a directory named ".ssh" in you user        directory                                                
If it shows "No such file or directory", skip to step 3. Else go to step 2.

Step 2: Backup and remove the existing key

Back the old SSH directory up and remove it:
$ ls
# Lists all the subdirectories in the current directory
config  id_rsa  id_rsa.pub  known_hosts

$ mkdir key_backup
# Makes a subdirectory called "key_backup" in the current directory

$ cp id_rsa* key_backup
# Copies the id_rsa keypair into key_backup

$ rm id_rsa*
# Deletes the id_rsa keypair
Step 3: Generate a new key

To generate a new SSH key, enter the code given below. To make default settings, when asked to enter a file in which to save the key, just press enter.
$ ssh-keygen -t rsa -C "your_email@youremail.com"
# Creates a new ssh key using the provided email
Generating public/private rsa key pair.
Enter file in which to save the key (/home/you/.ssh/id_rsa):
You need to enter passphrase.
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]
When you enter the passphrase, it shows something like this:
Your identification has been saved in /home/you/.ssh/id_rsa.
Your public key has been saved in /home/you/.ssh/id_rsa.pub.
The key fingerprint is:01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db                       your_email@youremail.com
Step 3: Add SSH key to Github

Run the following code to copy the key to your clipboard.
$ sudo apt-get install xclip
# Downloads and installs xclip
$ xclip -sel clip < ~/.ssh/id_rsa.pub
# Copies the contents of the id_rsa.pub file to your clipboard
Now,

1. Go to Github Account settings.
2. Click on SSH keys in the left sidebar.
3. Click on Add SSH key.
4. Paste your key into the Key field.
5. Click Add key
6. Confirm the action by entering your Github password.


[Expecting Your Valuable Comments]
Thank You

GIT REPOSITORY





A Git project using two main approaches. The first takes an existing project or directory and imports it into Git. The second clones an existing Git repository from another server.

Initialize a git repository in a directory


Go to the project’s directory and type
$ git init 
This creates a new subdirectory named .git that contains all of your necessary repository files. If you want to begin version-controlling existing files, then you need to start tracking files and do a initial commit. git add commands specify the files you want to track.git commit commands used to commit.
$ git add *.c
$ git add README
$ git commit -m 'initial project version'
Cloning a repository

If you want to get a copy of an existing Git repository, use git clone command.
git clone [url]if you want to clone the Ruby Git library called Grit
$ git clone git://github.com/schacon/grit.git 
if you want to clone the Ruby Git library called Grit in a new directory new
$ git clone git://github.com/schacon/grit.git new
Checking the status

To get the status of the git, type the command git status.Then you should see something like this.

$ git status
# On branch master
nothing to commit (working directory clean)
Add a new file README to your project. If the file didn’t exist   before, and you run git status, you see your untracked file like this:
$ vim README
$ git status
# On branch master
# Untracked files:
#   (use "git add ..." to include in what will be committed)
#
#   README
nothing added to commit but untracked files present (use "git add" to track)
Tracking a file

To begin tracking, use git add. Now on running the command git status, you will get  something like so:
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
#   new file:   README
#
Staging a modified file

Modify a file which is already tracked and then try the command. You will get something like this:
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
#   new file:   README
#
# Changed but not updated:
#   (use "git add ..." to update what will be committed)
#
#   modified:   hunter.rb
#

Now this shows the file 'hunter.rb' is modified but not yet staged. To stage it, run the command git add (Multipurpose command- Used for tracking, staging and to do more) and then git status.
$ git add benchmarks.rb
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
#   new file:   README
#   modified:   hunter.rb
#

If you modified the file 'hunter.rb'. To see the difference between the modified and unmodified file, type the command git diff before staging the modified file.
$ git diff
diff --git a/hunter.rb b/hunter.rb
index 3cb747f..da65585 100644
--- a/hunter.rb
+++ b/hunter.rb
@@ -36,6 +36,10 @@ def main
           @commit.parents[0].parents[0].parents[0]
         end

+        run_code(x, 'commits 1') do
+          git.commits.size
+        end
+
         run_code(x, 'commits 2') do
           log = git.commits('master', 15)
           log.size
Committing a file


The simplest way to commit is to type the commit message inline with the command git commit after -m flag.
$ git commit -m "Story 182: First commit"
[master]: created 463dc4f: "First commit"
 2 files changed, 3 insertions(+), 0 deletions(-)
 create mode 100644 README
Removing files

To remove a file from Git, you have to remove it from your tracked files and then commit. The git rm command does that and also removes the file from your working directory.
$ git rm pythonhunter.rb
rm 'pythonhunter.rb'
$ git status
# On branch master
#
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
#       deleted:    pythonhunter.rb
#
Renaming files

To rename a file, run a command git mv and run command git status to get something like this:
$ git mv pythonhunter.txt hunter
$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
#       renamed:    pythonhunter.txt -> hunter
#
Adding remote repository

To add a remote repository, run the below command.
$ git remote add origin git@github.com:rasheedh/Photo-Editor.git
Where 'git@github.com:rasheedh/Photo-Editor.git' is the SSH url(Generating SSH key).

Pushing to remote

If you want to push your master branch to your origin server, then you can run this to push your work back up to the server:
$ git push origin master

[Expecting Your Valuable Comments]
Thank You