Sunday, August 21, 2011

Using arrays we can store a group of values under a single name. We have C-style arrays in a C++ program. But C-style arrays are inflexible and in some ways awkward to use, so we will use the C++ implementation of the structure, which is a vector.
To use vectors in your code, you need the appropriate library -
#include

Vectors are declared with the following syntax:

vector variable_name (number_of_elements);

The number of elements is optional. You could declare it like this:

vector variable_name;

And that would declare an empty vector — a vector that contains zero elements.

Examples:

vector values (5); // Declares a vector of 5 integers

vector grades (20); // Declares a vector of 20 doubles

vector names; // Declares a vector of strings,
// initially empty (contains 0 strings)

After a vector has been declared specifying a certain number of elements, we can refer to individual elements in the vector using square brackets to provide a subscript or index, as shown below:

grades[5]

v.size()
Returns the number of elements in v.

The = operator

You can use the = (assignment) operator to assign one vector to another, for example v1 = v2, so long as they are vectors of the same type (eg both vector or vector). In this case the contents of v1 are overwritten with the contents of v2 and v1 is truncated or extended to be the same length as v2.


The
push_back() member function
This function allows you to add elements to the end of a vector.


The pop_back() member function

This function removes the last element from the vector.Unfortunately pop_back() doesn't return the value of the popped element.


C++ strings behave (to some extent) like vectors of char

string s = "eyrie";
s[1] = s[0]; // s is now "eerie"
string t = "cat";
char ch = t[0]; // ch is the letter 'c'; note that ch is of type char, not type string
t[0] = t[1];
t[1] = ch; // t is now "act"


Vectors are good at:
  • Accessing individual elements by their position index (constant time).
  • Iterating over the elements in any order (linear time).
  • Add and remove elements from its end (constant time).



Sunday, August 7, 2011

How to change the appearance of the Bash Prompt

First of all - backup your .bashrc file
cp .bashrc .bashrc-backup

now edit .bashrc with your editor:
gedit .bashrc

in the end of the file add:

PROMPT_HOSTNAME='SET_HERE'

PROMPT_COLOR='1;37m'
PROMPT_COLOR2='1;32m'

PS1='\e[${PROMPT_COLOR}[\e[${PROMPT_COLOR2}\u@${PROMPT_HOSTNAME}\e[${PROMPT_COLOR}] $ '

the first color is for the normal font and barckets, and the second one is for the user name and host
.
30: Black/Dark grey
31: Red 32: Green
33: Yellow
34: Blue
35: Magenta

36: Fuscia

37: White/light grey

38: "Default"

foreground color
in the exmaple "1;37m" you will have to change the 37 to another number.
The 1 before it can be set into zero, it is for light \ dark colors
rename the PROMPT_HOSTNAME to your hostname (or anything you want) and save the file.

You can try the options below and can select the nice colour combinations of your choice.

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\e[${PROMPT_COLOR2}\u@\h\[\033[00m\]:\[\033[1;37m\]\w\[\033[00m\]\$ '

PS1='\n\[\033[1;34m\]\342\226\210\342\226\210 \u @ \w\n\[\033[0;36m\]\342\226\210\342\226\210 \t $ \[\033[0;39m\]'

PS1="$C_BLUE[$C_RED\$?$C_BLUE][$C_RED\u@\h:\w$C_BLUE]\$ $C_RESET"

Try my choice..
if [ $(id -u) -eq 1 ];
then # you are root
PS1='\[\e[1;31m\][\u@\h \W]\$\[\e[0m\] '
else # normal

cal

PS1='\[\033[01;34m\]\u @ \w\[\033[0;36m\]\t $ \[\033[0;39m\]♡'

fi

You can see a calendar at the begining...The command cal run each time when the terminal opened and calendar will be displayed.You can replace cal by other command also..



unix tool awk

The Awk text-processing programming language and is a useful tool for manipulating text.

  • Awk recognizes the concepts of "file", "record", and "field".
  • A file consists of records, which by default are the lines of the file. One line becomes one record.
  • Awk operates on one record at a time.
  • A record consists of fields, which by default are separated by any number of spaces or tabs.
  • Field number 1 is accessed with $1, field 2 with $2, and so forth. $0 refers to the whole record.
  • Examples

    Print every line after erasing the 2nd field

    awk '{$2 = ""; print}' file

    Print hi 48 times
    yes | head -48 | awk '{ print "hi" }'
    print only lines of less than 65 characters
    awk 'length < 64'

    In awk, the $0 variable represents the entire current line, so print and print $0
    do exactly the same thing.

    AWK Variables

    awk variables are initialized to either zero or the empty string the first time they are used.
    Variables
  • Variable declaration is not required
  • May contain any type of data, their data type may change over the life of the program
  • Must begin with a letter and continuing with letters, digits and underscores
  • Are case senstive
  • Some of the commonly used built-in variables are:

    • NR -- The current line's sequential number
    • NF -- The number of fields in the current line
    • FS -- The input field separator; defaults to whitespace and is reset by the -F command line parameter
    Integer variables can be used to refer to fields. If one field contains information about which other field is important, this script will print only the important field:
    $ awk '{imp=$1; print $imp }' calc

    The special variable NF tells you how many fields are in this record.
    This script prints the first and last field from each record, regardless
    of how many fields there are:

    Unix tool sed

    sed (stream editor) is a Unix utility that parses text and implements a programming language which can apply transformations to such text. It reads input line by line, applying the operation which has been specified via the command line, and then outputs the line.

    Sed is a powerful stream editor. Sed copies its input to its output, editing it in passing. Each portion of an input line matching a regular expression can be replaced with a fixed string or another portion of the input. Lines matching a regular expression can be deleted. GNU sed understands Unicode.

    Usage

    The following example shows a typical, and the most common, use of sed,
    where the
    -e option indicates that the sed expression follows:
    sed -e 's/oldstuff/newstuff/g' inputFileName > outputFileName

    Under Unix, sed is often used as a filter in a pipeline:

    generate_data | sed -e 's/x/y/g'
    That is, generate the data, and then make the small change of
    replacing x with y.

    Several substitutions or other commands can be put together in a file.
    sed -f subst.sed inputFileName > outputFileName

    Besides substitution, other forms of simple processing are possible.
    For example, the following uses the d command to delete lines that
    are either blank or only contain spaces:

    sed -e '/^ *$/d' inputFileName

    This example used some of the following regular expression metacharacters:

    • The caret (^) matches the beginning of the line.
    • The dollar sign ($) matches the end of the line.
    • The asterisk (*) matches zero or more occurrences of the previous character.

    Samples

    To delete a line containing a specific word from the file use:
    sed '/yourword/d' yourfile
    To delete only the word use:
    sed 's/yourword//g' yourfile




    Use of 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. As the number of files in the program increases, compile time and complexity of compilation command also increases.

    With make, the programmer specifies what the files are in the project and how they fit together, and then make takes care of the appropriate compile and link steps. Make can speed up your
    compiles since it is smart enough to know that if you have ten .c files but you have only
    changed one, then only that one file needs to be compiled before the link step. Make has
    some complex features, but using it for simple things is pretty easy.

    Simple Example

    This is an example descriptor file to build an executable file called prog1. It requires the source files 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

    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 and mydefs.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.

    Invoking make

    Make is invoked from a command line with the following format

    make [-f makefile] [-bBdeiknpqrsSt] [macro name=value] [names]

    Frequently used make options
    Command Result
    make use the default descriptor file, build the first target in the file
    make myprog use the default descriptor file, build the target myprog
    make -f mymakefile use the file mymakefile as the descriptor file, build the first target in the file
    make -f mymakefile myprog use the file mymakefile as the descriptor file, build the target myprog



    Wednesday, July 20, 2011

    How to get user input in python?

    In Python we can use the raw_input() and input() to take inputs from user.

    Example for raw_input()..
    >>> lastName = raw_input("What is your Last Name?")
    What is your Last Name?pk
    >>> firstName = raw_input("What is your First Name?")
    What is your First Name?amala
    >>> print("Is your name {0} {1}?".format(firstName, lastName))
    Is your name amala pk?
    >>>

    Example for input()..
    >>> x = input("Enter a number:")
    Enter a number:6
    >>> print x
    6

    Now let's think how these inputs are interpreted....
    Using raw_input, the data is always interpreted as a string...Using input, the data is always interpreted as integer type...

    We can check this...

    >>> a=raw_input()
    5
    >>> print type(a)
    >>> digit=int(a)
    >>> print type(digit)
    >>>

    also

    >>> a=input()
    6
    >>> print type(a)
    >>> string=str(a)
    >>> print type(string)

    Thus we can use int() and str() to convert to integer type and string type respectively.



    Tuesday, July 12, 2011

    Some Programs involving Recursion

    We can find a^b using recursion.The code is..

    def power(a, b):
    if (b == 0):
    return 1
    else:
    a=a*power(a, b-1)
    return a

    print power(3, 9)


    We can optimise the above program and reduce the time complexity.
    Here is the code for that..

    def power(a, b):
    if(b == 0):
    return 1
    else:
    if(b%2 == 0):
    v = power(a, b/2)
    return v**2
    else:
    v = power(a, (b-1)/2)
    return a*v**2

    print power(3, 5)


    Next we can move on to finding the nth element of Fibonacci series.
    For that we have a recursive code..

    def fib(n):
    if n<2 :
    return n
    else:

    return fib(n-1)+fib(n-2)

    print fib(6)


    We can optimise the above code using the technique of memorisation.
    Then the code will be..

    def fib(n):
    if not n in memory:
    memory[n] = fib(n-1) + fib(n-2)
    return memory[n]

    memory={0:0,1:1}
    print fib (250)





    Thursday, July 7, 2011

    Object-Oriented Programming

    One of the way of organising our program is to combine data and functionality and wrap it inside an object. This is called the object oriented programming paradigm. This way is used when we want to write large programs or have a solution that is better suited to it.

    Classes and objects are the two main aspects of object oriented programming. A class creates a new type where objects are instances of the class. Even integers are treated as objects (of the int class)

    Objects can store data using ordinary variables that belong to the object. Variables that belong to an object or class are called as fields. Objects can also have functionality by using functions that belong to a class. Such functions are called methods of the class. This terminology is important because it helps us to differentiate between functions and variables which are separate by itself and those which belong to a class or object. Collectively, the fields and methods can be referred to as the attributes of that class.

    Fields are of two types - they can belong to each instance/object of the class or they can belong to the class itself. They are called instance variables and class variables respectively.

    A class is created using the class keyword. The fields and methods of the class are listed in an indented block.

    Class methods have only one specific difference from ordinary functions - they must have an extra first name that has to be added to the beginning of the parameter list, but you do do not give a value for this parameter when you call the method, Python will provide it. This particular variable refers to the object itself, and by convention, it is given the name self.

    Although, you can give any name for this parameter, it is strongly recommended that you use the name self - any other name is definitely frowned upon.

    >>> class person:
    ... pass
    ...
    >>> p=person()
    >>> print p
    <__main__.person instance at 0xb776586c>

    We have already discussed that classes/objects can have methods just like
    functions except that we have an extra
    self variable. We will now see
    an example.


    >>> class person:

    ... def sayHi(self):
    ... print "Hai,friend"
    ...
    >>> p=person()
    >>> p.sayHi()
    Hai,friend
    >>>


    The __init__ method
    There are many method names which have special significance in Python classes.

    The __init__ method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. Notice the double underscore both in the beginning and at the end in the name.

    >>> class person:
    ... def __init__(self,name):
    ... self.name=name
    ... def sayHi(self):
    ... print "Hai, my name is",self.name
    ...
    >>> p=person('amala')
    >>> p.sayHi()
    Hai, my name is amala

    Here, we define the __init__ method as taking a parameter name (along with the usual self). Here, we just create a new field also called name. Notice these are two different variables even though they have the same name. The dotted notation allows us to differentiate between them.

    Most importantly, notice that we do not explicitly call the __init__ method but pass the arguments in the parentheses following the class name when creating a new instance of the class. This is the special significance of this method.

    
    

    Sunday, July 3, 2011

    Exception Handling

    Error reporting and processing through exceptions is one of Python’s key features. In Python a programmer can raise an exception at any point in a program. When the exception is raised, program execution is interrupted as the interpreter searches back up the stack to find a context with an exception handler.

    Lets start with a simple program.

    >>> a=6
    >>> b=0
    >>> c=a/b

    Python "crashes" on divide by zero.

    Traceback (most recent call last):
    File "", line 1, in
    ZeroDivisionError: integer division or modulo by zero

    Now let's try that with exception handling:

    >>> a=6
    >>> b=0
    >>> try:
    ... print " a = ",a
    ... print " b = ",b
    ... c=a/b
    ... print " c = ",c
    ... except:
    ... print " division failed !!!"
    ... c=0
    ... print " c default to ",c
    ... else:
    ... print "division went very well"
    ...
    This time the program will not crash, we will get an error message printed instead. Our program will continue to execute.

    Our output looks like this:

    a = 6
    b = 0
    division failed !!!
    c default to 0

    The statements in the try: block are attempted.The first failure jumps to the except: block If nothing in the try block fails, the program jumps to the else: block. The 1st two print statements execute, but then the try block fails, so - print 'c=',c - does not. The except block executes.The else block does not execute.

    Monday, June 27, 2011

    Python Generators

    When we write a program it mat contain a series of named blocks. Each of those performs a single logical action. Named blocks are usually performed one after another as a sequence of statements from within another block.

    In this example, the pow2 function is performed completely before the for loop is run.

    The list called "powers" is constructed completely and stored in memory while the for loop is run. That's not a problem in this case with a list of ten values, but it could be a problem if the list was to contain a billion values.

    def pow2(upto):
    powers = []
    sat = 1
    spwr = 1
    while spwr <= upto:
    powers.append(sat)
    sat *= 2
    spwr += 1
    return powers

    def main():
    for w in pow2(10):
    print w
    main()


    Python provides an alternative way.i.e. Generator Functions. A generator function is one that does NOT run to completion when it's first called - instead, it only runs until it has a value available to return.

    A generator function is any function which uses the yield statement.

    When the for loop asks for the next element the generator starts or continues function execution at the place it left off. It runs until it reaches a yield statement. The function call is suspended at the yield statement. The generator stores the function call state and returns the given element.

    Here's the program provided above, modified to use a generator.

    def pow2(upto):
    sat=1
    spwr=1
    while spwr<=upto:
    yield sat
    sat*=2
    spwr+=1

    def main():
    for w in pow2(10):
    print w
    main()

    Operation is exactly the same as the example above ... but there is NOT an intermediate list produced.Generators provide a very neat way of providing data as required on applications that potentially use huge intermediate lists.


    Saturday, June 25, 2011

    List comprehensions

    Python supports a concept called "list comprehensions". It can be used to construct lists in a very easy way.

    In mathematics we can describe lists this way:

    S = {x² : x in {0 ... 9}}
    V = (1, 2, 4, 8, ..., 2¹²)
    M = {x | x in S and x even}

    In Python we can do this as::

    >>> S = [x**2 for x in range(10)]
    >>> V = [2**i for i in range(13)]
    >>> M = [x for x in S if x % 2 == 0]

    Let's see the result:

    >>> print S
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    >>>
    print V
    [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
    >>>
    print M
    [0, 4, 16, 36, 64]

    More examples:
    >>> [(x, x**2) for x in vec]
    [(2, 4), (4, 16), (6, 36)]
    >>> vec1 = [2, 4, 6]
    >>> vec2 = [4, 3, -9]
    >>> [x*y for x in vec1 for y in vec2]
    [8, 6, -18, 16, 12, -36, 24, 18, -54]
    >>> [x+y for x in vec1 for y in vec2]
    [6, 5, -7, 8, 7, -5, 10, 9, -3]
    >>> [vec1[i]*vec2[i] for i in range(len(vec1))]
    [8, 12, -54]
    any type of elements, including strings, nested lists and functions. We can even mix different types within a list.

    list comprehensions work for any type of elements

    >>> words='You can nest list comprehensions inside of each other'.split()
    >>> words
    ['You', 'can', 'nest', 'list', 'comprehensions', 'inside', 'of', 'each', 'other']
    >>> new=[[w.upper(), w.lower(), len(w)] for w in words]
    >>> for i in new:
    ... print i
    ...
    ['YOU', 'you', 3]
    ['CAN', 'can', 3]
    ['NEST', 'nest', 4]
    ['LIST', 'list', 4]
    ['COMPREHENSIONS', 'comprehensions', 14]
    ['INSIDE', 'inside', 6]
    ['OF', 'of', 2]
    ['EACH', 'each', 4]
    ['OTHER', 'other', 5]
    >>>



    Tuesday, June 21, 2011

    Lambda, map, filter and reduce

    lambda

    Python supports functions that are not bound to a name.we can use a construct called "lambda" for this. It can be used with functions like filter(), map() and reduce().

    The general syntax of a lambda function is quite simple:
    lambda argument_list: expression

    For example:

    >>> value=lambda x:x*x
    >>> value(7)
    49

    More than one arguments are supported and these are separated by comma.The expression is an arithmetic expression using these arguments.

    For example:

    >>> value=lambda x,y:x/y
    >>> value(47,5)
    9

    map()

    map() is a function with two arguments:
    r = map(func, seq)
    The first argument func is the name of a function.Second argument is a sequence like list.
    map() applies the function func to all the elements of the sequence seq. It returns a new list with the elements changed by func.

    >>> value=[1,4,7,5,8]
    >>> def sqrt(x):
    ... return x*x
    >>> map(sqrt,value)
    [1, 16, 49, 25, 64]

    The advantage of the lambda operator can be seen when it is used in combination with the map() function.

    >>> a=[5,6,4,8]
    >>> b=[4,3,2,7]
    >>> map(lambda x,y:x*y, a,b)
    [20, 18, 8, 56]


    filter()

    This function is used to filter out all the elements of a list.

    filter(fun, list)

    The first argument, fun needs a function which returns a Boolean value, i.e. either True or False. This function will be applied to every element of the list l. If the fun returns true for a particular element of the list,that will be included in the result list.

    >>> a=[4,5,76,34,7,32,45,89]
    >>> result = filter(lambda x: x % 2, a)
    >>> print result
    [5, 7, 45, 89]

    reduce()

    The function reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value.

    Suppose seq = [ s1, s2, s3, ... , sn ].When we call reduce(func, seq) , first 2 elements of the seq will be applied to func at first.In the next step func will be applied on the previous result and the third element of the list.It will continue like this until just one element is left and return this element as the result of reduce() .

    >>> reduce(lambda x,y:x+y,[34,78,435,23,78])
    648



    Sunday, June 19, 2011

    Strings

    Python has a built-in String class named "str".String literals can be enclosed in single or double quotes.
    Consider for example:
    >>> print "hai friend \n are you fine"
    hai friend
    are you fine

    Suppose we want to get \n, \t etc in our sentence we have to add r before the quotes.
    >>> print r"hai friend \n are you fine"
    hai friend \n are you fine

    There are a number of operations on strings.
    Concatenation is done with the + operator.
    >>> "hi"+" friend"
    'hi friend'

    Suppose we want to concatenate a string with a number, we can convert number to a string with the str casting function, otherwise,
    >>> pi=3.14
    >>> text='The value of pi is '+pi
    Traceback (most recent call last):
    File "", line 1, in
    TypeError: cannot concatenate 'str' and 'float' objects

    So we can concatenate these by,
    >>> pi=3.14
    >>> text='The value of pi is '+str(pi)
    >>> text
    'The value of pi is 3.14'

    The * operator between strings and numbers creates a new string that is a number of repetitions of the input string.
    >>> print 3*"cool !"
    cool !cool !cool !


    Comparing Strings:
    Strings can be compared with the standard operators :
    ==, !=, <, >, <=, and >=.


    String methods

    s.lower,s.upper -returns the lowercase or uppercase version of the string.
    s.startwith('other'),s.endwith('other') - tests if the string start with or end with the given other string
    s.find('other') - searches for the given other string and returns the first index where it begins.Otherwise return -1.
    s.replace('old','new') - returns a string where all occurences of 'old' have been replaced by new.

    Extracting substrings: Strings in Python can be subscripted just like an array: s[4] = 'a'. Two indices separated by a colon, will return a substring containing characters index1 through index2-1. Indices can also be negative, in which case they count from the right, i.e. -1 is the last character. Thus substrings can be extracted like,
    >>> s="beautiful"
    >>> s[1:4]
    'eau'
    >>> s[:5]
    'beaut'
    >>> s[3:]
    'utiful'
    >>> s[-7:-2]
    'autif'

    String % : Python has % operator which takes a printf-type format string on the left (%d,%s),and matching values separated by commas.
    >>> text="%d little girls are dancing with their %s"%(3,"mother")
    >>> text
    '3 little girls are dancing with their mother'

    Variables

    Variables are reserved memory locations to store values. So When we create a variable we reserve space in memory according to the data type of the variable. The interpreter allocates memory .

    Assigning values to variables

    Python variables do not have to be explicitly declared. The declaration happens automatically when we assign a value to a variable. The equal sign (=) is used to assign values to variables.

    The operand to the left of the = operator is the name of the variable, and the operand to the right of the = operator is the value stored in the variable.

    For example:

    >>> c=100
    >>> m=123.34
    >>> name="john"

    Python doesn't have the same types as C/C++, which appears to be your question.

    For example:
    >>> i = 123
    >>> type(i)
    <type 'int'>
    >>> type(i) is int
    True
    >>> i = 123456789L
    >>> type(i)
    <type 'long'>
    >>> type(i) is long
    True
    >>> i = 123.456
    >>> type(i)
    <type 'float'>
    >>> type(i) is float
    True

    Multiple Assignment : You can also assign a single value to several variables simultaneously.

    For example:

    >>> a=d=s=2
    >>> a
    2
    >>> d
    2
    >>> s
    2

    Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables.

    For example:

    >>> a,b,c=2,4,"dfg"
    >>> a
    2
    >>> b
    4
    >>> c
    'dfg'
    >>>

    Python numbers : Number data types store numeric values. They are immutable data types, which means that changing the value of a number data type results in a newly allocated object.

    Number objects are created when you assign a value to them.

    For example:

    >>> a=1
    >>> d=3
    >>> f=7

    You can delete a single object or multiple objects by using the del statement.

    For example:

    >>> del a
    >>> del d,f

    Saturday, June 18, 2011

    Basics of Linux

    Linux is a free Unix-like operating system.
    • Linux is an implementation of UNIX.

    • The Linux operating system is written in the C programming language.
    • Linux uses GNU tools, a set of freely available standard tools for handling the operating system.
    In Linux everything is a file.To organize our files into a system we use folders. The lowest possible folder is root / where you will find the user homes called /home/.
      /   /home/   /home/mom/   /home/dad/
    Every file belongs to a user and a group.
    Linux has one special user called root . Root is the "system administrator" and has access to all files and folders. This special user has the right to do anything.

    To run Linux commands, you need to get to the Linux command line prompt.To get to the Linux command line prompt from a Linux desktop, you open a terminal emulation window.When you open a terminal emulation window, you get a "window" on the desktop.This window shows the Linux command line prompt, at which you can run Linux commands . After running a Linux command, this window also shows the output of the command.

    Linux commands
    • mkdir -make directories
    • cd - change directory
    • mv - move (rename) files
    • pwd - print name of current/working directory
    • ls - list directory contents
    • rm - remove files or directories
    • chmod -change file access permissions
    syntax: chmod [-r] permissions file name

    r Change the permission on files that are in the subdirectories of the directory that you are currently in.permission Specifies the rights that are being granted. Below is the different rights that you can grant in an alpha numeric format.filenames File or directory that you are associating the rights with Permissions

    u - User who owns the file.

    g - Group that owns the file.

    o - Other.

    a - All.

    r - Read the file.

    w - Write or edit the file.

    x - Execute or run the file as a program.

    • mount - mount a file system
    • cp - copy files and directories
    • vim - Vi IMproved, a programmers text editor

    Introduction to python

    Python is an easy to learn and powerful programming language.In python code is automatically compiled to byte code and executed.So python can be used as a scripting language.

    Features of python
    • Simple and Easy to Learn
    • Free and Open Source
    • High-level Language
    • Built-in high level data types: strings, lists, dictionaries.
    • The usual control structures: if, if-else, if-elif-else, while.
    • Multiple levels of organizational structure: functions, classes, modules, and packages.

    Python programs are executed by interpreters. There are two modes to use the interpreter.
    • Interactive mode
    On a Linux platform you should be able to do this by typing python at a command prompt. On windows you should double click on the Python icon.This will launch the interactive interpreter.

    Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
    [GCC 4.4.5] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 34+45
    79
    >>> a="haiii"
    >>> a
    'haiii'
    >>> len(a)
    5
    >>>
    • Script mode In script mode code is stored in a file.Interpreter is used to execute the contents of the file.Python scripts saved with extension .py.

    Creating and running programs

    Python programs are just text files that contain instructions for the Python interpreter. You can create them with any text editor .In Linux we can run the program by typing something like ./program.py.

    Comment :
    Any line which starts with a hash (#) is a comment. It will be skipped by the interpreter. There is no multi line comment in Python, you should start every line with a hash instead.

    Indentation: In python white space indentation effect the meaning.A logical block will have the same indentation.If one of the line of a logical block has a different indentation it will result in syntax error.

    Code is checked at runtime: Python does very little checking at compile time.Python only checks a line when it runs that line.

    Tuesday, May 17, 2011

    Locating the path of files using the shell

    Here is a text file containing human genetics data:

    http://svn.software-carpentry.org/swc/data/1000gp.vcf


    If you had forgotten where you downloaded the file, how would you locate the path of all files with that name on the computer (using the shell)?

    Answer

    The find command used to find the files.To locate the path of given file we can use the command ,

    $ find / -name "1000gp.vcf"

    Here the system would search for any file named 1000gp.vcf on the root and all sub-directories from the root.

    If we are giving the command, $ find -name "1000gp.vcf" the system would search for any file named 1000gp.vcf in the current directory and any sub-directory only.

    Monday, May 9, 2011

    A Digital circuit simulation tool

    My first project is simulating logic circuits in Python. Real logic circuits built with electronic components are the basis for computer hardware. The simplest gates (AND, OR, NOT) are made with only a few transistors and resisters.

    Digital Simulator has a toolbar of digital circuit elements, including logic gates, flip-flops, switches, and indicators. Drawing a circuit with Digital Simulator is like using a paint program. You click the element's icon on the toolbar, then click where you want the element to go. You use a similar procedure to draw wires and indicate connections.

    The AND gate has two inputs (generally labeled A and B) and and output C. The inputs and output may have the value 0 or 1. The output C is 1 if and only if both A and B are 1. Otherwise it is 0.


    The OR gate is very similar with the same inputs A and B, and output C. The output C is 1 if either A or B is 1, Otherwise it is 0.

    The NOT gate has a single input A and output B.The output is the opposite of the input. If the input is 0, the output is 1. If the input is 1, the output is 0.

    By using existing gates and connecting outputs to inputs in certain ways we can build several circuits. For example to make a NAND gate where the output is 0 if and only if both inputs are 1, we can use and AND gate followed by a NOT gate. The inputs of the AND gate are the inputs to the NAND. The AND output is connected to the NOT input. The NOT output is the output for the NAND.

    Here you can use DCD to simulate digital circuits using basic gates like AND, OR, NOT, NAND, Flip Flops (JK, SR, T) and many pre-built integrated circuits. This program comes with many pre-built demonstration circuits like seven segment displays, RAM chip simulations, digital clock circuits etc.