Saturday, 23 November 2013

HTML and CSS


Create Tab based webpages  using HTML and CSS

+ One of  a good tut which I came across is :

http://blixt.org/articles/tabbed-navigation-using-css#section=introduction

Tuesday, 12 November 2013

Understanding IP Addressing

Understanding IP Addressing
Every device connected to the Internet needs to have an identifier. Internet Protocol (IP) addresses are the numerical addresses used to identify a particular piece of hardware connected to the Internet.

The two most common versions of IP in use today are Internet Protocol version 4 (IPv4) and Internet Protocol version 6 (IPv6). Both IPv4 and IPv6 addresses come from finite pools of numbers.

For IPv4, this pool is 32-bits (232) in size and contains 4,294,967,296 IPv4 addresses. The IPv6 address space is 128-bits (2128) in size, containing 340,282,366,920,938,463,463,374,607,431,768,211,456 IPv6 addresses.

A bit is a digit in the binary numeral system, the basic unit for storing information.

Not every IP address in the IPv4 (or IPv6) pool can be assigned to the machines and devices used to access the Internet. Some IP addresses have been reserved for other uses, such as for use in private networks. This means that the total number of IP addresses available for allocation is less than the total number in the pool.


Network prefixes

IP addresses can be taken from the IPv4 or the IPv6 pool and are divided into two parts, a network section and a host section. The network section identifies the particular network and the host section identifies the particular node (for example, a certain computer) on the Local Area Network (LAN).


Allocation

IP addresses are assigned to networks in different sized ‘blocks’. The size of the ‘block’ assigned is written after an oblique (/), which shows the number of IP addresses contained in that block. For example, if an Internet Service Provider (ISP) is assigned a “/16”, they receive around 64,000 IPv4 addresses. A “/26” network provides 64 IPv4 addresses. The lower the number after the oblique, the more addresses contained in that “block”.
For e.g in IPv4

The size of the prefix, in bits, is written after the oblique. This is called “slash notation”. There is a total of 32 bits in IPv4 address space. 

IPv4 For example, 

If a network has the address “192.0.2.0/24”, the number “24” refers to how many bits are contained in the network. From this, the number of bits left for address space can be calculated. As all IPv4 networks have 32 bits, and each “section” of the address denoted by the decimal points contains eight bits, “192.0.2.0/24” leaves eight bits to contain host addresses. This is enough space for 256 host addresses. These host addresses are the IP addresses that are necessary to connect your machine to the Internet.

A network numbered “10.0.0.0/8” (which is one of those reserved for private use) is a network with eight bits of network prefix, denoted by “/8” after the oblique. The “8” denotes that there are 24 bits left over in the network to contain IPv4 host addresses:16,777,216 addresses to be exact.


Classless Inter-Domain Routing (CIDR) Chart


The Classless Inter-Domain Routing (CIDR) is commonly known as the CIDR chart and is used by those running networks and managing IP addresses. It enables them to see the number of IP addresses contained within each “slash notation” and the size of each “slash notation” in bits.

UNIX Bash/ Shell scripting examples and excercises


OUTPUT Redirection  in bash shell


  • 1> can be shortened to just >
  • 1>foo 2>&1 to >&foo or &>foo
  • 2>&1 | program to |& program


Unix Bash/ Shell scripting  examples  and   exercises

++Note : The answers below are correct to the best of my understanding .They may vary according to what is expected by the instructor.


1) 

What will be the output of the following ?


grep '^mo.*ing$' /usr/share/dict/words
Ans : all lines starting with 'mo' and ending with 'ing'
(if we count it is 153)

grep '[[:digit:]bc][^x-y]*$' /usr/share/dict/words

Ans :
grep '[[:digit:]bc]'--- will return all lines containing 0-9 OR b OR c



2)
Find all5 char words from /usr/share/dict/words that begin with 'I' and end in 'a'.
Ans: grep '^I.*a$' /usr/share/dict/words

3)
Match lines containing the years 1992-2009 from a file named file.txt.

Ans : egrep '199[2-9]|200[0-9]' file

4)
Search for a 7 digit phone number , possibley with a spcace or a hyphen in the middle
like 123 4567 or 123-4567 ?
grep '[0-9][0-9][0-9][ -][0-9][0-9][0-9]' file
grep '[0-9][0-9][0-9][ -]*[0-9][0-9][0-9]' file --if you want to make the space and - optional






Wednesday, 6 November 2013

WEB2PY Using Python



Steps to create a Simple Form in Web2Py


++Start the Web2PyServer

++
Enter in the Administration Interface.On the left hand side give a name of a new application say RegForm

++
The application we just created in Web2Py has one major file for now  that we need to be concerned about  in order to experiment with the web form and that is default.py in the Controller section.
This default.py is a Python controller that constructs the back-end operations for our form application and manages the data provided by it.

++
Next comes formation of a database in Web2Py

db = DAL('sqlite://storage.sqlite')
db.define_table('registrationform',
    Field('firstname', requires=IS_NOT_EMPTY()),
    Field('lastname', requires=IS_NOT_EMPTY()),
    Field('gender', requires=IS_IN_SET(['Male', 'Female'])),
    Field('username', requires=IS_NOT_EMPTY()),
    Field('password', 'password')
   
Once this default.py is saved, Web2Py controller reads this database schema, and constructs a table named ‘registrationform’ having the following fields:
firstname
lastname
gender
username
password

The code  (db = DAL(‘sqlite://storage.sqlite’) defines the database abstraction layer (DAL()) for the Web2Py controller, and based on the input parameters provided, it establishes the connection with the defined database.
Because, SQLite comes by default with Web2Py, so we can utilize it (although this can be replaced by any type of DBMS like MySQL, etc.).
On the other hand, the function right below it (db.define_table()) defines the structure of the newly created database table.


++
Now we can create our FORM fields.
In the same default.py, enter this new function at the end of the file  right below the above code:
def reg_form():
    form = SQLFORM(db.registration)
    return dict(form=form).
SQLFORM() function in Web2Py ,simply extracts all the input fields defined in the ‘registration’ table .


++
 All we need to do now is to call it  in an html template/page.
In the Views section of the forms application page, create a new html file named default/reg_form.html (it is recommended that we keep the html file name as default/[name of the function] that we specified in Controller default.py).
Open this newly created html file and enter the following HTML code :

<h1>Registration Form </h1>
<br  />
{{=form}}
<br  />

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


A good tutorial to create a Simple app :http://blog.fruiapps.com/2012/05/Web2py-tutorial-to-create-a-Notes-Application

Another  good tutorial video is : http://vimeo.com/3703345

Friday, 1 November 2013

B O O K S



Operating Systems

+  Operating Systems Concepts by Galvin and Swartz (9th edition)
         The book can be read online @ http://os-book.com/


Data Structures

+  Data Structures Made easy


C

+Understanding Pointers in C --Y Kanetkar

Computer Network Systems:

+Notes Lecture Notes from Prof. Dheeraj Sanghi, IIT Kanpur


Python


Python RESOURCES

WEB2PY


+For  project, the official Web2py docx @ http://www.web2py.com/init/default/documentation
+For another good tut for beginners: http://killer-web-development.com/section/1/1



EXCERCISES


Q1. Get a string from user. Reverse the order of words in it.
        Input:
                "hello world !"
          Output:
                  "! world hello"

A1:Code in Python 

mesg=raw_input("Input:\n")
mlist=str(mesg)
invstr=""
for i in range (1 , len(mlist)+1):
           invstr=invstr+mlist[-i]
print invstr

+++++++++++++++++++++++++++++++++++++++++++++++++++

Q2  Take upto a three digit number as input, print the equivalent of the number in words.
           Input:
                    123
            Output:
                 "one hundred and twenty three".
A2: Code in Python 

num=raw_input("Input the number:\n")
list=str(num)
o=list[-1]
t=list[-2]
h=list[-3]
sp=t+o

one={'0':'','1':'one','2':'two','3':'three','4':'four','5':'five','6':'six','7':'seven','8':'eight','9':'nine'}
tens={'0':'and','1':'ten','2':'twenty','3':'thirty','4':'forty','5':'fifty','6':'sixty','7':'seventy','8':'eighty','9':'ninety'}
hun={'1':'one hundred','2':'two hundred','3':'three hundred','4':'four hundred','5':'five hundred','6':'six hundred','7':'seven hundred','8':'eight hundred','9':'nine hundred'}
spl={'11':'eleven','12':'twelve','13':'thirteen','14':'fourteen','15':'fifteen','16':'sixteen','17':'seventeen','18':'eighteen','19':'nineteen'}

if (t=='1'):
 print hun[h],spl[sp]
print hun[h],tens[t],one[o]

+++++++++++++++++++++++++++++++++++++++++++++++++

Q3:
Write a python program to get abbreviation of name.
Input:
Aakash Kumar Gupta
Output:

A. K. Gupta

A3:

name=raw_input("Enter the name\n")
list=name.split()
abr=''
for i in range(0,len(list)-1):
 x=str(list[i])
 y=str(x)
 abr+=y[0]


print abr+" "+list[len(list)-1]


+++++++++++++++++++++++++++++++++++++++++++++++

Q4:
Write a function to create a list containing first n prime numbers. The user should enter n as

a command line argument.

A4:
def isprime(startnumber):
    startnumber*=1.0
    for divisor in range(2,int(startnumber**0.5)+1):
        if startnumber/divisor==int(startnumber/divisor):
            return False
    return True

ran=raw_input("Input the range number\n")
for a in range(2,int(ran)):
 if isprime(a):
   print a


++++++++++++++++++++++++++++++++++++++++++++

Q5:
Write a recursive function to calculate the sum of first n numbers. Note that you are not
supposed to use the formula directly.
Input:
9
Output:

45

A5:


def sum(n):
    if (n==0):
     return 0
    s=n+sum(n-1)
    return s


ran=input("Enter the range  \n")
total=sum(ran)

print  "The sum   =   "    ,total

+++++++++++++++++++++++++++++++++++++++++++++

Q6


Develop a game which allows user to guess 5 times a number randomly generated between 1 and 20 (This you can vary)

A6:

import random

name=raw_input( "Enter you name\n")

print "Hello ! " , name , "Lets play a game of guessing "

hit=random.ranrange(1,20)
guess=input("Input a number between 1    and   20  \n")


for i in range (1,5):
  if (guess<hit):
   print "Your guess is too low  ! "

  if (guess >hit):
   print "Your guess is too high  !  "

  if (guess==hit)
   print  "B i n g o  !  you guessed the correct number in " , i , "chances"
   break



+++++++++++++++++++++++++++++++++++++++++++++++++
Q7
To reverse the order of digits while taking input from command line

A7

#!/usr/bin/env python 
# This can also be used to print the sum of digits of a given integer from a command line 


import sys 

num=int(sys.argv[1]) # convert to int 

while num:
rem=num % 10 # holds remainder 

quot=num / 10 # holds the quotient 

num=quot
sys.stdout.write(str(rem))

print '\n'

+++++++++++++++++++++++++++++++++++++++++++++++++++++++

Q8  Code for printing the below given pattern

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5


A8

for row in range(1,11):
for col in range(1,row+1): 
print col,     # The comma important  for changing the line.try without comma


print   # \n
+++++++++++++++++++++++++++++++++++++++++++++++++++++

Q9

To check if the input string is a palindrome or not .using Recursion .

A9
#!/usr/bin/python

# tests if a string is palindrome of not recursively


import sys

s=str(sys.argv[1] )


def pal(s):

try:

if len(s) == 0 or len(s)==1:
return 'Palindrome'

if s[0] != s[-1]:
return "Not Palindrome"

else:

return pal(s[1:-1]) # stripping  off the first and last chars


except: IndexError
print pal(s)

+++++++++++++++++++++++++++++++++++++++++++++++++++++

Q10
Reverses a string recursively

A:10

import sys
def  RecRev(s):

if len(s)==1: # base case

return s

else: # recursive case

return RecRev(s[1:]) + s[0] # strip off the first char and append to the end






s=sys.argv[1] # hold the input

print RecRev(s)   # call the function

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Q11
Find Commom items in 2 given lists

A11:

import sys
def common(s1, s2):
List=[] # start with empty list

for i in s1: # traverse s1
if i in s2:
L.append(i) # found, so add to L
return List

print common([1,2,3,4,5], [2,4,6,8,10])  # both lists


#print common(('Guanine', 'Cytocin', 'Adenine'), ['Adenine', 'Thyamine']) # tuple and list
#print common("This is string 1", "hide and seek")

# version 2 - Using List comprhension
#[i for i in s1 if i in s2]

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Q12 Program to simulate COPY command .

A12:

#!/usr/bin/python

import sys
source=sys.argv[1]    #source file
dest=sys.argv[2]       #destination file

def copy(source,dest):
f1=open(source,'r') # open file for reading
f2=open(dest,'w')         # open dest file  for writing

        for line in f1:

f2.write(line)

f1.close()
f2.close()

# call  the function

copy(source,dest)

++++++++++++++++++++++++++++++++++++++++++++


Q13.

Write a program that categorizes each mail message by which day of the week the commit was done. To do this look for lines that start with "From" in a sample log file 
Sample Line:
    From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008
Build a histogram using a dictionary to count how many messages have come from each email address, and print the dictionary. Add code to the above program to figure out who has the most messages in the file.After all the data has been read and the dictionary has been created, look through the dictionary using a maximum loop (see Section [maximumloop]) to find who has the most messages and print how many messages the person has.


A13.


name = raw_input("Enter file:")
fhand=open(name)
words=list()
lst=list()
counts=dict()
for line in fhand:
  line=line.rstrip()
  if not line.startswith('From '):continue
  words=line.split()
  lst.append(words[1])    
for x in lst:
  counts[x]=counts.get(x,0)+1
bigcount=None
bigword=None
for word,count in counts.items():
    if bigcount is None or count>bigcount:
        bigcount=count
        bigword=word
print bigword,bigcount

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


Q14.
Finding Numbers in a Haystack
In this assignment you will read through and parse a file with text and numbers. You will extract all the numbers in the file and compute the sum of the numbers.
Sample text:
What should you to write programs? 7746
12 1929 8827
Writing prams (or programming) is a creative 
7 and rewaing activity.  You can wrie programs for 
many reasons, rang from making your living to so
8837 a diff data problem to having fun to helping 128
someone else solve a problem.  assumes that 
needs to know how to program ...


A14.

import re
hand=open('luck.txt')
numlist=list()
num=list()
for line in hand:
    line=line.rstrip()
    num=re.findall('[0-9]+',line)
    if len(num)==0:continue
    for x in num:
numlist.append(x)
sum=0
for x in numlist:
    sum=sum+int(x)
print sum








Random Notes :



Fork System Calls
Useful Link :
http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html


Quiz Questions :

OS PG quiz :3 

1 Briefly describe the network sensors and the related characteristics offered in TinyOS. 
2 Briefly discuss how the memory allocation , command exec and mutual exclusion is achieved in TinyOs . 
3 Discuss about motivation to adopt OS abstraction to  take GPU as computing units
4 How the Ptask scheduling is integrated with CPU scheduling . 
5..Discuss the basic idea of the Cell Architecture.

6..Discuss the power management strategies adopted in Cell .

A very good guidance tut for GATE.Thanks to the author.
http://www.cse.iitk.ac.in/users/dvjrao/study.html


Notes in C:


>>If a break is used in the for loop , it exits the loop immediately, and does not update the counter value to next.
for (i=0;i<9;i++)
 { if (i%2==1)  { break;}

  }
printf("%d",i);

in this case ./a.out gives 1 and not 2 . as the normal case if break is not used .



>>int a;
   while (scanf("%d",&a)==1) //means this will read till the values of   a   are numeric
{}

scanf has a return value which depicts the number of inputs successfully made.(means scanf return 1 after every successful entry)


>>>C operators and expressions - associativity


>>Precedence Of Operators in C





>>Initialising Arrays String Arrays


+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


RESOURCES for asking Questions on HTML and CSS3 and JS


-Stack overflow website
-Share code using   
       >>CodePen
       >>jfiddle.com