Monday, November 30, 2015

Language: Java (code snippets)......

Compile
javac file.java
javac Hello.java 
Execute
java filename  
java Hello
--------------------------------------------------------------------------------------
The content of the script Hello.java
public class Hello{

     public static void main(String []args){
        System.out.println("Hello");
     }
}
#################################
//Creation of objects from a Class (java file name is Kitty.java)
//package practice;
public class Kitty{

   public Kitty(String name){
      // Constructor having one parameter i.e. name.
      System.out.println("Given Pet Name is :" + name );
   }
 
   public static void main(String []args){
      // Following statement creates objects myKitty1, myKitty2
      Kitty myKitty1 = new Kitty( "Toy" );
      Kitty myKitty2 = new Kitty( "Beast" );
   }
   }
-----------------------------------------------
Given Pet Name is :Toy
Given Pet Name is :Beast
#################################
//File name is Employee.java
package practice;
import java.io.*;

public class Employee{

   String name;
   int age;
   String designation;
   String city;
   double salary;

   // This is the constructor of the class Employee
   public Employee(String name){
      this.name = name;
   }
   // Assign the age of the Employee  to the variable age.
   public void empAge(int empAge){
      age =  empAge;
   }
   /* Assign the designation to the variable designation.*/
   public void empDesignation(String empDesig){
      designation = empDesig;
   }
      /* Assign city to the variable designation.*/
   public void empCity(String empCity){
         city = empCity;
   }
   /* Assign the salary to the variable salary.*/
   public void empSalary(double empSalary){
      salary = empSalary;
   }
   /* Print the Employee details */
   public void printEmployee(){
      System.out.println("Name:"+ name );
      System.out.println("Age:" + age );
      System.out.println("Designation:" + designation );
      System.out.println("City:" + city );
      System.out.println("Salary:" + salary);
   }
}

//File name is EmployeeTest.java
package practice;
import java.io.*;

public class EmployeeTest{

   public static void main(String args[]){
      /* Create two objects using constructor */
      Employee empOne = new Employee("Carl");
      Employee empTwo = new Employee("Rhea");
      Employee empThree = new Employee("Jonas");

      // Invoking methods for each object created
   
      System.out.println("##################");
      empOne.empAge(26);
      empOne.empDesignation("Travel agent");
      empOne.empCity("Paris");
      empOne.empSalary(700);
      empOne.printEmployee();
   
      System.out.println("##################");
      empTwo.empAge(35);
      empTwo.empDesignation("Doctor");
      empTwo.empCity("Phoenix");
      empTwo.empSalary(500);
      empTwo.printEmployee();
   
      System.out.println("##################");
      empThree.empAge(48);
      empThree.empDesignation("Artist");
      empThree.empCity("Chicago");
      empThree.empSalary(200);
      empThree.printEmployee();
   }
}
-----------------------------------------------
##################
Name:Carl
Age:26
Designation:Travel agent
City:Paris
Salary:700.0
##################
Name:Rhea
Age:35
Designation:Doctor
City:Phoenix
Salary:500.0
##################
Name:Jonas
Age:48
Designation:Artist
City:Chicago
Salary:200.0

#################################
//Reduce variable number using keyword enum
//Script fle name is PizzaTest.java (the class name, not the super class name)
package practice;
class Pizza {

   enum PizzaPortion{ SMALL, MEDIUM, LARGE , VERY_LARGE}
   PizzaPortion portion;
}
public class PizzaTest {

   public static void main(String args[]){
      Pizza slice = new Pizza();
      slice.portion = Pizza.PizzaPortion.VERY_LARGE ;
      System.out.println("Portion: " + slice.portion);
   }
}
-----------------------------------------------
Portion: VERY_LARGE
#################################
//Accessing instance variables and methods
//File name is Toy.java
package practice;
public class Toy{
   int toyAge;
   public Toy(String name){
      // Constructor with one parameter, name.
      System.out.println("My toy dinosaur's name is:" + name );
   }
   public void setAge( int age ){
       toyAge = age;
   }
   public int getAge( ){
       System.out.println("It's age is " + toyAge );
       return toyAge;
   }
   public static void main(String []args){
      /* Object creation */
      Toy myToy = new Toy( "Rex" );                  
      /* Call class method to set age */
      myToy.setAge( 12 );
      /* Call another class method to get age */
      myToy.getAge( );
      /* Accessing instance variable*/
      System.out.println("I bought it " + myToy.toyAge + " years back" );
      System.out.println("Its cost was $10." );
   }
}
-----------------------------------------------
My toy dinosaur's name is:Rex
It's age is 12
I bought it 12 years back
Its cost was $10.
#################################

Language: Java (My understanding)....

#Install Java on Linux Systems
sudo apt-get install openjdk-8-jre
yum install java-1.8.0-openjdk

#Installing a java file
java -jar scala-2.9.0.1-installer.jar
java -jar VarScan.jar  pileup2snp file.pileup
java -jar file.jar

#Run a java file (.jar file)
java -jar fsh.jar

IDE
Eclipse, NetBeans (folder has src, it has package, it has the java file)
####################
Java: object-oriented, portable, cross-platform, interpreted, high performance
Java is based  key concepts: polymorphism, inheritance, encapsulation, abstraction, classes, objects, instance, method, message parsing

Object can be made from a Class by declaration, instantiation and initialization
Objects have states and behavior e.g Water is (ice,gas) and has (fluidity,solidity)
Class describes the above attributes of the object. Object is an instance of class.
Behaviors are the methods.
Class can have many methods

Methods are followed by() e.g. public void size()
State are the values assigned to instance variables
Class is concrete while interface is abstract
Java variables can be local, class, instance
An object's state is created by the values assigned to the instant variables.
The public class name must be the java file name to be executed.


Class has methods
string: str compareTo (string) , compareToIgnoreCase(String), compareTo(object string),strOrig.lastIndexOf(Stringname), removeCharAt(string,position), StringBuffer(String string), toString(),  split(string),  toUpperCase() 
####################
compilation of  .java file
javac Script.java
Execution of .jar file
javac Script
java jar path_to_.jar_file
To print the statement
System.out.println("xyz"); return null; 
####################
public static void size()
Access modifiers: default, public, private, protected
Non-access modifiers e.g. static, final, abstract, synchronized
Modifiers: void, boolean, int, Object
public void clear() {
public int size()
public boolean indexExists ) {
private int binarySearch() {
####################
extends (inherits): for extending a class (interface extends)   e.g. extends Object
implements: for implementing an interface (data structure implements) e.g. implements  Comparable<Calendar>
####################
class
Object class is super-parent
java.util.Object (This class provides methods to classes below)
java.util.Arrays---------------sort (), binarySearch ()
java.util.Collections---------- reverse(), 
####################
Methods
constructor, accessor
getter (accessor) returns value
setter (mutator) resets the value
add (E), clear(), comparator(), contains (Object o), iterator(), peek(), poll(), size(), toArray()

Standard methods: sort (), binarySearch (), reverse(),  
User-defined methods: printArray(), insertElement (), Collections.reverse(ArrayList)

####################
IteratorHelper is a field
Polymorphism: Required method is used during runtime
####################
Data structure (container)
array, list,vector
Stack, queue, hash table
LinkedList
#To loop through things in  a container
for(int i=0; i<n; ++i) doSomething;
for(int& i: someDataStructure) { doSomething();}
for(int i: someDataStructure) doSomething();

Abstract data types (ADT)
Priority queue: Common operations are add (x), isEmpty (), remove(), peek()
####################
if (keys==null) return -1;
####################
Search methods
Linear search: easy but not good for long array. 
Binary search; good for long ordered list. Based on binary search tree (BST) algorith, that ignores one half.
Both search methods can be iterative or recursive
####################
Common errors
ArrayStoreException: When wrong type of object is stored into an array of objects
IllegalArgumentException:
NullPointerException: When null is used in place of required object
####################
Compilation, execution
To keep compiled java classes
mkdir dir
#Compile
java -jar ~/path
javac -classpath .jar_file -d dir .java_file
#Execute
jar -cvf units.jar -C dir/ .
#Creating directory in target
mkdir dir
put file
ls dir
job -status < job_ID
job -history < dir_name
job -kill < job_ID
####################
echo %CLASSPATH

java -version
//When compilation error occurs, use -Xlint
javac -Xlint Example.java 
Errors..........
NullPointerException : If class objects are null

Sunday, November 29, 2015

IT (7): What's Hadoop??......

Cloud computing offers some great opportunities for science, but most cloud computing platforms are both I/O and memory limited, and hence are poor matches for data-intensive computing. 
-------------
The other day, I was applying for a software job and one of the criteria was knowledge of Hadoop. Now, I had vaguely heard of the term with respect to big data management, but that's that. For solidifying my position in job market I must know, how it works. So I started accumulating information. Here, I am presenting some from understanding.

Colossal amount of data (generated from diverse fields, namely search engine, grid, transport, industry, agriculture, health, genomics, stock exchange, security, defense), which is called 'Big Data' posed many problems such as storage, handling, transfer, manipulation etc. Further the data types are diverse, classified a structured (relational data), semi-structured (XML) and unstructured (text, pdf, word).

MongoDB and NoSQL (cloud technology) offered the big data solution at operational level, while Massively Parallel Processing (MPP) and MapReduce worked at analytical level. Database owners like Oracle, IBM help to address the issues, but it has limitations. 

In order to solve the above issues, many infrastructures are developed, Hadoop being one of them. Invested by Google, this Apache open source project had solved many challenges inherent to big data. Written in Java and running on MapReduce algorithm, Hadoop operates on single to a cluster of machine.

(Anyway, if you are curious, how the name Hadoop came, it was after a stuffed yellow elephant, the toy of the inventor's kid).


Storage system of Hadoop, Hadoop Distributed File System (HDFS) is based on Google File System (GFS).  Further, Hadoop Common (Java libraries ) and Hadoop YARN (Yet Another Resource Negotiator) (job scheduling and cluster  management) are other important components. Other Apache frameworks are also installed along with Hadoop such as Pig, Hive, HBase, Spark etc. Working mechanism of Hadoop is based on 'division of labor' i.e. data is divided into comparable size file blocks and assigned to cluster nodes.

#Hadoop daemon: hdfs, yarn, MapReduce
#Hadoop operation modes:Local/Standalone Mode, Pseudo Distributed Mode, Fully Distributed Mode
HDFS follows the master-slave architecture. Its task is  fault detection and recovery
MapReduce is a  program model for distributed computing based on java. The reduce task is always performed after the map job.
-------------------------------------------------
#Download, extraction Hadoop 2.4.1 from Apache software foundation, installation
su 
password: 
cd /usr/local 
wget http://apache.claz.org/hadoop/common/hadoop-2.4.1/ 
hadoop-2.4.1.tar.gz 
tar xzf hadoop-2.4.1.tar.gz 
mv hadoop-2.4.1/* to hadoop/ 

exit

Friday, November 27, 2015

Language: Perl (One-liners).....

Perl on-liners can perform a cariety od useful tasks,. Some interesting ones..
Codes tested on bash shell..
-e :For execution; -p: For printing; -i: Edited in place
-------------------------------------------------------------------------
#print lines. pattern, reverse lines, reverse alphabets, shuffle lines, alphabet case change, space manipulation, pattern substitution, column manipulation, blank line manipulation, line numbering, calculations, time printing, word manipulation.........

# Print the first line of a file (head -1)
perl -ne 'print; exit'

# Print the first 10 lines of a file (head -10)
perl -ne 'print if $. <= 10'
perl -ne '$. <= 10 && print'
perl -ne 'print if 1..10'

# Print the last line of a file (tail -1)
perl -ne '$last = $_; END { print $last }'
perl -ne 'print if eof'

# Print the last 10 lines of a file (tail -10)
perl -ne 'push @a, $_; @a = @a[@a-10..$#a]; END { print @a }'

# Print only lines that match a regular expression
perl -ne '/regex/ && print'

# Print only lines that do not match a regular expression
perl -ne '!/regex/ && print'

# Print the line before a line that matches a regular expression

perl -ne '/regex/ && $last && print $last; $last = $_'

#Print  the next line following this pattern
perl -ne 'if ($p) { print; $p = 0 } $p++ if /pattern/' file
# Print lines that match regex AAA and regex BBB in any order
perl -ne '/AAA/ && /BBB/ && print'
# Print lines that don't match match regexes AAA and BBB
perl -ne '!/AAA/ && !/BBB/ && print'
# Print lines that match regex AAA followed by regex BBB followed by CCC
perl -ne '/AAA.*BBB.*CCC/ && print'
# Print lines that are 80 chars or longer
perl -ne 'print if length >= 80'
# Print lines that are less than 80 chars in length
perl -ne 'print if length < 80'
# Print only line 16
perl -ne '$. == 16 && print && exit'
# Print all lines except line 24
perl -ne '$. != 24 && print'
perl -ne 'print if $. != 24'
# Print only lines 13, 19 and 67
perl -ne 'print if $. == 13 || $. == 19 || $. == 67'
perl -ne 'print if int($.) ~~ (13, 19, 67)' 
# Print all lines between two regexes (including lines that match regex)
perl -ne 'print if /regex1/../regex2/'
# Print all lines from line 17 to line 30
perl -ne 'print if $. >= 17 && $. <= 30'
perl -ne 'print if int($.) ~~ (17..30)'
perl -ne 'print if grep { $_ == $. } 17..30'
# Print the longest line
perl -ne '$l = $_ if length($_) > length($l); END { print $l }'
# Print the shortest line
perl -ne '$s = $_ if $. == 1; $s = $_ if length($_) < length($s); END { print $s }'
# Print all lines that contain a number
perl -ne 'print if /\d/'
# Find all lines that contain only a number
perl -ne 'print if /^\d+$/'
# Print all lines that contain only characters
perl -ne 'print if /^[[:alpha:]]+$/
# Print every second line
perl -ne 'print if $. % 2'
# Print every second line, starting the second line
perl -ne 'print if $. % 2 == 0'
# Print all lines that repeat (find duplicate lines)
perl -ne 'print if ++$a{$_} == 2'
# Print all unique lines (find unique lines)
perl -ne 'print unless $a{$_}++'
# Print the first field (word) of every line (like cut -f 1 -d ' ')
perl -alne 'print $F[0]'
#Print paragraphs in reverse order (there must be space between lines).
 perl -00 -e 'print reverse <>' file

#Print all lines in reverse order (what appears is gibberish, may be good for secret signals)
perl -lne 'print scalar reverse $_'  file
perl -lne 'print scalar reverse'  file

#Shuffle rows in a data file
cat file | perl -MList::Util=shuffle -e 'print shuffle(<STDIN>);\n'
#!/usr/bin/perl
use List::Util 'shuffle';
@list = <STDIN>;
print shuffle(@list);

#Convert first letter of each line into uppercase 
perl -nle 'print ucfirst lc' file
perl -ple 's/(\w+)/\u$1/g' file

#Change the alphabet case
perl -ple 'y/A-Za-z/a-zA-Z/' file

# Convert all text to uppercase
perl -nle 'print uc'
perl -ple '$_=uc'
perl -nle 'print "\U$_"'

# Convert all text to lowercase
perl -nle 'print lc'
perl -ple '$_=lc'
perl -nle 'print "\L$_"'

# Uppercase only the first word of each line
perl -nle 'print ucfirst lc'

perl -nle 'print "\u\L$_"'

#Remove leading white spaces 
perl -ple 's/^[ \t]+//' file
perl -ple 's/^\s+//' file

#Remove trailing white spaces (its not much visible though, so skipping result)
perl -ple 's/[ \t]+$//' file
perl -ple 's/\s+$//' file

#Remove whitespace (spaces, tabs) from the beginning an end  
perl -ple 's/^[ \t]+|[ \t]+$//g' file
perl -ple 's/^\s+|\s+$//g' file

# Double space a file, except the blank lines
perl -pe '$_ .= "\n" unless /^$/' file

#Double space a file
perl -pe '$\="\n"' file
perl -pe 'BEGIN { $\="\n" }' file
perl -pe '$_ .= "\n"' file
perl -pe 's/$/\n/' file
perl -nE 'say' file
perl -pe '$_ .= "\n" if /\S/' file

# Triple space a file
perl -pe '$\="\n\n"' file
perl -pe '$_.="\n\n"' file

# N-space a file
perl -pe '$_.="\n"x7' file

#Substitute pattern1 (xyz here) with pattern2 (abc here) on  each line
perl -pe 's/xyz/abc/' file

#Substitute pattern1 with pattern2 on  lines matching pattern3 (lmn here)
perl -pe '/lmn/ && s/xyz/abc/' file
perl -pe 's/xyz/abc/ if /lmn/' file

#Shuffle all fields on a line
perl -MList::Util=shuffle -alne 'print "@{[shuffle @F]}"' file
perl -MList::Util=shuffle -alne 'print join " ", shuffle @F' file

#Take a multi column file and convert into uni column . Suppose
1   9
2   3
5   6
8   4
xargs -n1 < multicolumn
1                                                                                                   
9                                                                                                   
2                                                                                                   
3                                                                                                   
5                                                                                                   
6                                                                                                   
8                                                                                                   
4

#Add a blank line before every line
perl -pe 's//\n/' file

#Remove all blank lines
perl -ne 'print unless /^$/' file
perl -lne 'print if length' file
perl -ne 'print if /\S/' file

# Remove all consecutive blank lines, leaving just one
perl -00 -pe '' file
perl -00pe0 file

#Number all lines in a file
perl -pe '$_ = "$. $_"' file

#Number only non-empty lines in a file
perl -pe '$_ = ++$a." $_" if /./' file

#Number and print only non-empty lines in a file (drop empty lines)
perl -ne 'print ++$a." $_" if /./' file

#Number all lines but print line numbers only non-empty lines
perl -pe '$_ = "$. $_" if /./' file

#Number only lines that match a pattern, print others unmodified
perl -pe '$_ = ++$a." $_" if /regex/' file

#Number and print only lines that match a pattern
perl -ne 'print ++$a." $_" if /regex/'

#Number all lines, but print line numbers only for lines that match a pattern
perl -pe '$_ = "$. $_" if /regex/'

#Number all lines in a file using a custom format
perl -ne 'printf "%-5d %s", $., $_' file

#Print the total number of lines in a file (like wc -l)
perl -lne 'END { print $. }' file
perl -le 'print $n=()=<>' file
perl -le 'print scalar(()=<>)' file
perl -le 'print scalar(@foo=<>)' file
perl -ne '}{print $.' file
perl -nE '}{say $.' file

# Print the number of non-empty lines in a file
perl -le 'print scalar(grep{/./}<>)' file
perl -le 'print ~~grep{/./}<>' file
perl -le 'print~~grep/./,<>' file
perl -E 'say~~grep/./,<>' file

# Print the number of empty lines in a file
perl -lne '$a++ if /^$/; END {print $a+0}' file
perl -le 'print scalar(grep{/^$/}<>)' file
perl -le 'print ~~grep{/^$/}<>' file
perl -E 'say~~grep{/^$/}<>' file

# Print the number of lines in a file that match a pattern (grep -c)
perl -lne '$a++ if /regex/; END {print $a+0}' file
perl -nE '$a++ if /regex/; END {say $a+0}' file

# Check if a number is a prime
perl -lne '(1x$_) !~ /^1?$|^(11+?)\1+$/ && print "$_ is prime"'

# Print the sum of all the fields on a line
perl -MList::Util=sum -alne 'print sum @F'

# Print the sum of all the fields on all lines
perl -MList::Util=sum -alne 'push @S,@F; END { print sum @S }'
perl -MList::Util=sum -alne '$s += sum @F; END { print $s }'
# Find the minimum element on a line
perl -MList::Util=min -alne 'print min @F'

# Find the minimum element over all the lines
perl -MList::Util=min -alne '@M = (@M, @F); END { print min @M }'
perl -MList::Util=min -alne '$min = min @F; $rmin = $min unless defined $rmin && $min > $rmin; END { print $rmin }'

# Find the maximum element on a line
perl -MList::Util=max -alne 'print max @F'

# Find the maximum element over all the lines
perl -MList::Util=max -alne '@M = (@M, @F); END { print max @M }'

# Replace each field with its absolute value
perl -alne 'print "@{[map { abs } @F]}"'

# Find the total number of fields (words) on each line
perl -alne 'print scalar @F'

# Print the total number of fields (words) on each line followed by the line
perl -alne 'print scalar @F, " $_"'

# Find the total number of fields (words) on all lines
perl -alne '$t += @F; END { print $t}'

# Print the total number of fields that match a pattern
perl -alne 'map { /regex/ && $t++ } @F; END { print $t }'
perl -alne '$t += /regex/ for @F; END { print $t }'
perl -alne '$t += grep /regex/, @F; END { print $t }'

# Print the total number of lines that match a pattern
perl -lne '/regex/ && $t++; END { print $t }'

# Print the number PI to n decimal places
perl -Mbignum=bpi -le 'print bpi(n)'

# Print the number PI to 39 decimal places
perl -Mbignum=PI -le 'print PI'

# Print the number E to n decimal places
perl -Mbignum=bexp -le 'print bexp(1,n+1)'

# Print the number E to 39 decimal places
perl -Mbignum=e -le 'print e'

# Calculate factorial of 5
perl -MMath::BigInt -le 'print Math::BigInt->new(5)->bfac()'
perl -le '$f = 1; $f *= $_ for 1..5; print $f'

# Calculate greatest common divisor (GCM)
perl -MMath::BigInt=bgcd -le 'print bgcd(@list_of_numbers)'

# Calculate GCM of numbers 20 and 35 using Euclid's algorithm
perl -le '$n = 20; $m = 35; ($m,$n) = ($n,$m%$n) while $n; print $m'

# Calculate least common multiple (LCM) of numbers 35, 20 and 8
perl -MMath::BigInt=blcm -le 'print blcm(35,20,8)'

# Calculate LCM of 20 and 35 using Euclid's formula: n*m/gcd(n,m)
perl -le '$a = $n = 20; $b = $m = 35; ($m,$n) = ($n,$m%$n) while $n; print $a*$b/$m'

# Generate 10 random numbers between 5 and 15 (excluding 15)
perl -le '$n=10; $min=5; $max=15; $, = " "; print map { int(rand($max-$min))+$min } 1..$n'

# Find and print all permutations of a list
perl -MAlgorithm::Permute -le '$l = [1,2,3,4,5]; $p = Algorithm::Permute->new($l); print @r while @r = $p->next'

# Generate the power set
perl -MList::PowerSet=powerset -le '@l = (1,2,3,4,5); for (@{powerset(@l)}) { print "@$_" }'
# Convert an IP address to unsigned integer
perl -le '$i=3; $u += ($_<<8*$i--) for "127.0.0.1" =~ /(\d+)/g; print $u'
perl -le '$ip="127.0.0.1"; $ip =~ s/(\d+)\.?/sprintf("%02x", $1)/ge; print hex($ip)'
perl -le 'print unpack("N", 127.0.0.1)'
perl -MSocket -le 'print unpack("N", inet_aton("127.0.0.1"))'

# Generate and print the alphabet
perl -le 'print a..z'
perl -le 'print ("a".."z")'
perl -le '$, = ","; print ("a".."z")'
perl -le 'print join ",", ("a".."z")'

# Generate and print all the strings from "a" to "zz"
perl -le 'print ("a".."zz")'
perl -le 'print "aa".."zz"'

# Create a hex lookup table
@hex = (0..9, "a".."f")

# Convert a decimal number to hex using @hex lookup table
perl -le '$num = 255; @hex = (0..9, "a".."f"); while ($num) { $s = $hex[($num%16)&15].$s; $num = int $num/16 } print $s'
perl -le '$hex = sprintf("%x", 255); print $hex'
perl -le '$num = "ff"; print hex $num'

# Generate a random 8 character password
perl -le 'print map { ("a".."z")[rand 26] } 1..8'
perl -le 'print map { ("a".."z", 0..9)[rand 36] } 1..8'

# Create a string of specific length
perl -le 'print "a"x50'

# Create a repeated list of elements
perl -le '@list = (1,2)x20; print "@list"'

# Create an array from a string
@months = split ' ', "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
@months = qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/

# Create a string from an array
@stuff = ("hello", 0..9, "world"); $string = join '-', @stuff

# Find the numeric values for characters in the string
perl -le 'print join ", ", map { ord } split //, "hello world"'

# Convert a list of numeric ASCII values into a string
perl -le '@ascii = (99, 111, 100, 105, 110, 103); print pack("C*", @ascii)'
perl -le '@ascii = (99, 111, 100, 105, 110, 103); print map { chr } @ascii'

# Generate an array with odd numbers from 1 to 100
perl -le '@odd = grep {$_ % 2 == 1} 1..100; print "@odd"'
perl -le '@odd = grep { $_ & 1 } 1..100; print "@odd"'

# Generate an array with even numbers from 1 to 100
perl -le '@even = grep {$_ % 2 == 0} 1..100; print "@even"'

# Find the length of the string
perl -le 'print length "one-liners are great"'

# Find the number of elements in an array
perl -le '@array = ("a".."z"); print scalar @array'
perl -le '@array = ("a".."z"); print $#array + 1'

# Convert an unsigned integer to an IP address
perl -MSocket -le 'print inet_ntoa(pack("N", 2130706433))'
perl -le '$ip = 2130706433; print join ".", map { (($ip>>8*($_))&0xFF) } reverse 0..3'
perl -le '$ip = 2130706433; $, = "."; print map { (($ip>>8*($_))&0xFF) } reverse 0..3'
# Print UNIX time (seconds since Jan 1, 1970, 00:00:00 UTC)
perl -le 'print time'

# Print GMT (Greenwich Mean Time) and local computer time
perl -le 'print scalar gmtime'
perl -le 'print scalar localtime'

# Print local computer time in H:M:S format
perl -le 'print join ":", (localtime)[2,1,0]'

# Print yesterday's date
perl -MPOSIX -le '@now = localtime; $now[3] -= 1; print scalar localtime mktime @now'

# Print date 14 months, 9 days and 7 seconds ago
perl -MPOSIX -le '@now = localtime; $now[0] -= 7; $now[4] -= 14; $now[7] -= 9; print scalar localtime mktime @now'

# Prepend timestamps to stdout (GMT, localtime)
tail -f logfile | perl -ne 'print scalar gmtime," ",$_'
tail -f logfile | perl -ne 'print scalar localtime," ",$_'

Thursday, November 26, 2015

C++: Glossary and code snippets...

Good tools are first requisite of better programming. Here I list some of the tools, links that helped me hone my grasp over programming C++.
C++ originates from C, yet it has many features on top of it, such as classes, objects, templates, namespaces etc. 
-----------------------------------------------------
CodeLite is a good IDE to practice C, C++ and PHP. Linking a compiler is vital for itsproper working.
Create project.....src.......code_file (.cpp extension)
Perspectice----Restore default layout
-----------------------------------------------------
http://cpp.sh/   (Its a nice online compiler, you just need to copy paste your code.)
Some really nice tutorial can be found at:
http://www.cplusplus.com/
-----------------------------------
Function declaration
int main ()
main is the special function
-----------------------------------
class
ostream
-----------------------------------
object 
std::cin            (input)
std::cout          (output)
std::cer            (error)

std::clog           (logging)
-----------------------------------
operator
<< 
-----------------------------------
function
write
The sentence below is direction to preprocessor
#include <iostream>
########################
Should produce Hello World. Brace pair contain statement of the function.
#include <iostream>
int main()
{
 std::cout << "Hello World!";
 std::cout << "C++ is a nice language to learn!";
}
-----------------------------------
Another version of the above program (better than the above)
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
cout << "Its a C++ program";
}
########################
Calculations (declares variables, calculates and prints results before termination)
#include <iostream>
using namespace std;
int main ()
{
int a,b; int result;
a = 5; b = 3;
a = a+1; b = b+2;
result = a * b;
cout << result;
return 0;
}
-----------------------------------
Initializing variables ( here a,b,c,d)
#include <iostream>
using namespace std;
int main ()
{
int a =2; int b(4); int c{6}; int result;
a = a+b; result = a * c;
cout << result;
return 0;
}
########################
String manipulation
Printing one string
#include <iostream>
#include <string>
int main ()
{
string mystring;
mystring= "Programming is fun";
cout << mystring;
return 0;
}
-----------------------------------
Printing multiple strings
#include <iostream>
#include <string>
int main ()
{
string mystring;
mystring= "I like autumn season";
cout << mystring << endl;
mystring= "Because trees are colorful";
cout << mystring << endl;
mystring= "Also, the weather is crisp";
cout << mystring << endl;
return 0;
}
-----------------------------------

INFO (1): Links/Blogs/Journals to assist in bioinformatics and programming....

Popular languages...
---------------------------------------
Awk: Data extraction and reporting
C: General-purpose
C++: General-purpose, object-oriented
Haskell: General-purpose
HTML(HyperText Markup Language): For webpage creation
Java: General-purpose, object-oriented
Javascript (JS): General-purpose, object-based scripting
julia: 
LaTeX: For TeX typesetting
Lisp:General purpose
Lua: For embedded systems and clients
Matlab: For computation and visualization
GNU Octave : For numerical calculations
Perl: For text manipulation, web development, network programming, GUI development
PHP (Hypertext preprocessor): General-purpose, scripting
Python: General Purpose
Scala: 
SQL: For accessing and manipulating databases
R:Statistics
##################################################
Books and links:
'Unix and Perl Primer for Biologists'  by Keith Bradnam & Ian Korf
'Introduction to Linux' by  Machtelt Garrels
'Bash Guide for Beginners' by Machtelt Garrels
'Shell Scripting' by  Steve Parker
'Linux Shell Scripting Cookbook' by Shantanu Tushar & Sarath Lakshman
'The Linux Command Line' by William E. Shotts
'Advanced Bash Scripting Guide' by Mendel Cooper
Handy one-line scripts for awk--------------Eric Pement
Handy one-line scripts for sed--------------Eric Pement
Awk one-liners explained-----------------Peteris Krumins
http://software-carpentry.org
http://www.tutorialspoint.com/
http://www.cyberciti.biz/download/lsst.tar.gz
ftp://ftp.freebsd.org/pub/sys.tar.gz
ftp://ftp.redhat.com/pub/xyz-1rc-i386.rpm
http://xyz.com/abc.iso
http://www.bioinformatics-made-simple.com
gsesoftsolutions.com
--------------------------------------------------------------------------------------------------------------
Unix/Linux
http://www.unix.com/
http://linux.about.com/
http://askubuntu.com/
An A-Z Index of the Bash command line forLinux..http://ss64.com/bash/
Basic Shell Commands------https://www-xray.ast.cam.ac.uk/~jss/lecture/computing/notes/
IBM Knowledge Center-------http://www-01.ibm.com/support/knowledgecenter/
Main Lab Directory-----http://www.cs.sjsu.edu/web_mater/cs46b/cs46blab/mainLabDirectory.html
nixCarft------------http://www.cyberciti.biz/
The Linux Documentation Project-------http://tldp.org/
Unix Introduction---------http://www.ee.surrey.ac.uk/Teaching/Unix/unixintro.html
--------------------------------------------------------------------------------------------------------------

Shell
http://www.tutorialspoint.com/execute_bash_online.php   (a great online console to practice shell)
--------------------------------------------------------------------------------------------------------------
Java
http://picard.sourceforge.net/command-line-overview.shtml
http://www.cs.utexas.edu/~scottm/cs307/codingSamples.htm
--------------------------------------------------------------------------------------------------------------
Perl
http://perldoc.perl.org/index.html
http://www.perlmonks.org/
Book by James Tisdalll
--------------------------------------------------------------------------------------------------------------
Python
http://www.python.org/doc/humor/
--------------------------------------------------------------------------------------------------------------
SQL
http://www.headfirstlabs.com/sql_hands_on/
--------------------------------------------------------------------------------------------------------------
Bioinformatics
http://www.1000genomes.org/
http://genome.ucsc.edu/
http://www.homolog.us/
--------------------------------------------------------------------------------------------------------------
SDSU
http://www-rohan.sdsu.edu/rohansoft.html
##################################################
Forum
https://about.gitlab.com/ (to create, review and deploy code together)
http://unix.stackexchange.com/
http://sourceforge.net/projects/transpose/
http://www.grymoire.com
http://www.thegeekstuff.com/
https://www.biostars.org/
http://quickleft.com/
http://seqanswers.com/
http://stackoverflow.com
##################################################
Blogs:
The tree of life---------------- http://phylogenomics.blogspot.com/
Byte Size Biology-----------http://bytesizebio.net/
OpenHelix ---------------------- http://blog.openhelix.eu/
Living in an Ivory Basement--------- http://ivory.idyll.org/blog/
My Biotech Life---------------------http://my.biotechlife.net/
Next-Gen Sequencing-----------------http://nextgenseq.blogspot.com/
Kevin's GATTACA World----------------http://kevin-gattaca.blogspot.com/
YOKOFAKUN--------------http://plindenbaum.blogspot.com.br/
Blue Collar Bioinformatics----------------https://bcbio.wordpress.com/
Bits and Bugs----------------------http://bitsandbugs.org/
BitesizeBio------------------http://bitesizebio.com/
In between lines of code---------https://flxlexblog.wordpress.com/
eurofins--------http://ngs-expert.com/
Getting Genetics Done-----------http://www.gettinggeneticsdone.com/
The Genome Factory-----------http://thegenomefactory.blogspot.it/
EdgeBio------------https://www.edgebio.com/
Homolog.us--------http://www.homolog.us/
NeXT GEN SEEK-----------http://nextgenseek.com/
ColorBasePair-------http://www.colorbasepair.com/
bioinfoblog.it---------http://bioinfoblog.it/
Bioinformatics Tools-----------http://bioinformatictools.blogspot.com/
http://www.catonmat.net/
##################################################
Journals:
Briefings in Bioinformatics...........http://bib.oxfordjournals.org/

Wednesday, November 25, 2015

Language: MATLAB.........

Matlab (Matrix laboratory)
The source file (function file) has extension .m (e.g.  script.m)
#To save workspace for later use
save script.m
load script.m
The file with suffix .mat has data matrix (e.g data.mat, golubsmall.mat)
# The mat file splits into one with matrix and another with label  in grid format (cell array)  (row * column)
load ('data.mat')
e.g. dimensionality (16 row x 24 columns)
       ndata (70 row x 20 columns)
The source file reads .dat file (containing data)
Comment (%)
###################################################
Data type determination using the functions
x = 5
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
ischar(x)
isreal(x)
isobject(x)
class(x)
ans = 0                                                                                     
ans =  1                                                                                    
ans =  1                                                                                    
ans =  1                                                                                    
ans =  1                                                                                    
ans = 0                                                                                     
ans =  1                                                                                    
ans = 0                                                                                     
ans = double 
###################################################
Arithmetic calculations
2 + 7
6 ^ 2
sin(pi)
8/0
381 * 10.7

x = 4;
y = x + 8
-----------------------
Answers
ans =  9                                                                         
ans =  36                                                                        
ans =    1.2246e-16                                                              
warning: division by zero                                                        
ans = Inf                                                                        
ans =  4076.7 

y =  12
###################################################
% Variable assignment
x = 6
x = sqrt(81)

sqrt(488)
sqrt(48);396/ans

x = 4 * 6;
y = x * 3.2
-----------------------
Answers
x =  6                                                                           
x =  9                                                                           
ans =  22.091                                                                    
ans =  57.158                                                                    
y =  76.800 
###################################################
% Multiple variable assignment 
a = 3; b = 2;
c = a + b
d = a / b
e = a ** b
-----------------------
Answers
c =  5                                                                           
d =  1.5000                                                                      
e =  9
###################################################
%Final velocity calculation
initial_velocity = 0;
acceleration = 9.8;
time = 30;
final_velocity = initial_velocity + acceleration * time
final_velocity =  294  
###################################################
%Format of result display
x = 5 + 8/6 + 2 ^ 2.5
format long
x = 5 + 8/6 + 2 ^ 2.5
x =  11.990                                                                           
x =  11.9901875828257

x = 23.8967452346
format short
x =  23.897
###################################################
%The command format bank will keep only two digits after decimal point
daily_wage = 17.10;
weekly_wage = daily_wage * 5

format bank
daily_wage = 17.10;
weekly_wage = daily_wage * 5

weekly_wage =  85.500                                                                 
weekly_wage =  85.50 
###################################################
%The command format short e will express in exponential notation
5.2 * 1.7
format short e
5.2 * 1.7
ans =  8.8400                                                                         
ans =    8.8400e+00 

x = pi
format long e
x = pi
x =  3.1416                                                                                       
x =    3.14159265358979e+00  
###################################################
Vectors
row vector
r = [3 6 7 9]
r =                                                                                         
                                                                                            
   3   6   7   9 
a = [2 7 8 6];
b = [4 5 3 7];
new = a + b
new =                                                                                       
                                                                                            
    6   12   11   13  

column vector
c = [4;  6;  8;  9]
c =                                                                                        
                                                                                           
   4                                                                                       
   6                                                                                       
   8                                                                                       
   9  

matrix vector
matrix = [1 5 7; 4 7 3; 2 9 6; 7 1 4]
matrix =                                                                                   
                                                                                           
   1   5   7                                                                               
   4   7   3                                                                               
   2   9   6                                                                               
   7   1   4 

Reference to the vector elements and sub-strings
vector = [ 1; 5; 8; 7; 4; 3];
vector(4)
vector(:)
vector = [4 8 5 9 3 2];
parts = vector(2:5)
ans =  7                                                                                    
ans =                                                                                       
                                                                                            
   1                                                                                        
   5                                                                                        
   8                                                                                        
   7                                                                                        
   4                                                                                        
   3                                                                                        
                                                                                            
parts =                                                                                     
                                                                                            
   8   5   9   3   

Matrix manipulation (vector (3,4) here means element at the intersection of row 3 and column 4).
vector = [3 2 8 4 ; 8 3 5 7 ; 4 7 3 6]
vector(3,4)
vector =                                                                                    
                                                                                            
   3   2   8   4                                                                            
   8   3   5   7                                                                            
   4   7   3   6                                                                            
                                                                                            
ans =  6 

vector1 = [3 2 8 4 ; 8 3 5 7 ; 4 7 3 6]
vector1 =                                                                        
                                                                                 
   3   2   8   4                                                                 
   8   3   5   7                                                                 
   4   7   3   6   

vector2 = vector1(3,:)
vector2 =                                                                        
                                                                                 
   4   7   3   6 

vector2 = vector1(:,3)
vector2 =                                                                        
                                                                                 
   8                                                                             
   5                                                                             
   3   

vector2 = vector1(:,:)
vector2 =                                                                        
                                                                                 
   3   2   8   4                                                                 
   8   3   5   7                                                                 
   4   7   3   6   

vector2 = vector1(1:2,1:2)
vector2 =                                                                        
                                                                                 
   3   2                                                                         
   8   3 

vector2 = vector1(2:3,1:2)
vector2 =                                                                        
                                                                                 
   8   3                                                                         
   4   7
###################################################
Array generation
Zero-based array
zeros (3) %matrix of 3 row, 3 column
ans =                                                                                
                                                                                     
   0   0   0                                                                         
   0   0   0                                                                         
   0   0   0
zeros(5,4) %matrix of 5 row, 4 column
ans =                                                                                
                                                                                     
   0   0   0   0                                                                     
   0   0   0   0                                                                     
   0   0   0   0                                                                     
   0   0   0   0                                                                     
   0   0   0   0  

One-based array
ones(2,4) %matrix of 2 row, 4 column
ans =                                                                                
                                                                                     
   1   1   1   1                                                                     
   1   1   1   1 

Identity (diagonal)array
eye(3)    %matrix of 3 row, 3 column
Diagonal Matrix                                                                      
                                                                                     
   1   0   0                                                                         
   0   1   0                                                                         
   0   0   1 

Random array
rand(2, 3)  %It differs in each execution
ans =                                                                                
                                                                                     
   0.029232   0.434291   0.721927                                                    
   0.837602   0.117745   0.356975 

Magic array  %Row, column or diagonal sum is always same
magic(3)
ans =                                                                                
                                                                                     
   8   1   6                                                                         
   3   5   7                                                                         
   4   9   2
###################################################
Calculations
People = 12;
Cattle = 14;
Horse = 2;
Dogs = 3;
Cats = 4;
Total = People + Cattle + Horse + Dogs+...
   + Cats;
disp(Total);
35
###################################################
%Generates nearest rational expression
2.57 * 3.18
format rat
2.57 * 3.18
ans =  8.1726                                                                                     
ans = 40863/5000
###################################################
Common functions
rand():Returns an array of random numbers
size (rand ()): Gives size of a ransom array
zeros(): Creates a matrix of zeros
abs(): Returns absolute value of each element in an array
exp(): Returns exponential of each element in an array
hold off: Resets axis properties to default
hold on: Retains current plot so that subsequent graphs can be added
hold all: Holds the properties
plot (): Creates graph
fplot: To plot a function between specified limits
subplot (): It divides current figure to rectangular panes
format: To control display format for output
round(): Rounds of numbers to next integer
clear: clears
close all: closes
clc; resets
dim: matrix dimensions
delx:
gcf: returns the current figure handle
realsqrt: Returns square root of each element of the array
num2str: Converts numeric array to string
###################################################
% Takes three matrix and generates plot in pdf or eps format
x = [1 2 3 4 5];
y1 = [.23 .45 .78 .35 .65];
y2 = [.45 .56 .23 .34 .28];
%y3 = [.48 .53 .78 .23 .49];

semilogy(x,y1,'-bo;y1;',x,y2,'-kx;y2;');
%semilogy(x,y1,'-bo;y1;',x,y2,'-kx;y2;', x,y3,'-kx;y3;');
title('Plot chart');
xlabel('X Axis');
ylabel('Y Axis');

print -dpdf chart.pdf
--------------------------------------
x = [1 2 3 4 5 ];
y1 = [.34 .78 .89 .56 .34];
y2 = [.23 .56 .78 .54 .36];

semilogy(x,y1,'-bo;y1;',x,y2,'-kx;y2;');
title('Plot title');
xlabel('X Axis');
ylabel('Y Axis');
print -deps graph.eps
###################################################
%To generate vectors U (uniformly-distributed) and N(normally-distributed) of particular length,
% range, mean an SD (Suppose length=100, range is 0,1, mean =0.5, SD = 0.05)
U Vector =rand (length, upper limit)
N Vector =normrand (mean, SD, length, upper limit)

U=rand(100,1);
N=normrnd(0.5,0.05,100,1);
%N=0.5+ 0.05.*randn(100, 1);
###################################################
% To estimate probability density function (pdf ) when window width is given
 %Suppose SD (s=0.005), window width is 0.01
%Using a: increment:b in increments size of 0.001 
% x=[a:i:b], where i is increment and a=0 and b=1
x=0:0.001:1;
%Initializing height of each kernel and total height after summation
% Length of largest array = L = length (x)
height=zeros(1,length(x));
h = zeros(1,length(x));
###################################################
% To estimate of pdf for U vector
l = length(U);
for i=1:l
    %x(i)=a+delx*(i-1)where index of x has to be an integer > 0
    m=round((U(i)-s)*100+1);
    %x(i)=a+delx*(i-1) where index of x has to be an integer < 100
    n=round((U(i)+s)*100+1);
    if m<1
        m=1;
    end
    if n>101
        n=101;
    end
    height(m+1:n)=1;
    %Adding all kernel heights to total height and storing them in 'h'
    h = h + height;
    %Re-initializing height after calculating for each kernel
    height=zeros(1,length(x));
end
%y axis is normalized to the number of data points i.e 1000 here
h=(h/100)*100;
-----------------------------------------------------------------------
%Estimation of pdf for N vector
height=zeros(1,length(x));
%Initializing total height after adding the kernels
j = zeros(1,length(x));
l = length(N);
for i=1:l
    %x(i)=a+delx*(i-1)where index of x has to be an integer > 0
    m=round((N(i)-s)*100+1);
    %x(i)=a+delx*(i-1) where index of x has to be an integer < 100
    n=round((N(i)+s)*100+1);
    if m<1
        m=1;
    end
    if n>100
        n=100;
    end
    %Another precaution
    height(m+1:n)=1;
    %Adding all kernel heights to total height and storing them in 'h'
    j = j + height;
    %Re-initializing height after calculating for each kernel
    height=zeros(1,length(x));
end
%y axis is normalized to the number of data points i.e 100 here
j=(j/100)*100;

figure(1)
%num2str function is useful for labeling plots with numeric values.
%To get unbiased estimate of s
name=['Parzen Density Estimation with Uniform kernels ' num2str(s*2)];
set(gcf,'name',name);
%plot for pdf of U
plot(x,h,'g','linewidth',3);
%hold on retains the current graph and adds another graph to it
hold on
%plot for pdf of N
plot(x,j,'r','linewidth',3)
title(name);
%xlabel(str) labels the x-axis of the current axes with the string, str
%ylabel(str) labels the y-axis of the current axes with the string, str
xlabel('Random numbers (U,N)');
ylabel('Kernel density (x,h/j)');
print(gcf,'-djpeg',[name '.jpg']);

%Estimation of pdf when window width is 0.05
s=0.025;
x=0:0.001:1;
%Initializing height of each kernel and total height after summation
height=zeros(1,length(x));
h = zeros(1,length(x));
%Estimation of pdf for U vector
l = length(U);
for i=1:l
    %x(i)=a+delx*(i-1)where index of x has to be an integer > 0
    m=round((U(i)-s)*1000+1);
    %x(i)=a+delx*(i-1) where index of x has to be an integer < 1000
    n=round((U(i)+s)*1000+1);
    if m<1
        m=1;
    end
    if n>1001
        n=1001;
    end
    %Another precaution
    height(m+1:n)=1;
    %Adding all kernel heights to total height and storing them in 'h'
    h = h + height;
    %Re-initializing height after calculating for each kernel
    height=zeros(1,length(x));
end
%y axis is normalized to the number of data points i.e 1000 here
h=(h/1000)*20;
-------------------------------------------------------------
%Estimation of pdf for N vector
height=zeros(1,length(x));
j = zeros(1,length(x));
l = length(N);
for i=1:l
    %x(i)=a+delx*(i-1)where index of x has to be an integer > 0
    m=round((N(i)-s)*100+1);
    %x(i)=a+delx*(i-1) where index of x has to be an integer < 100
    n=round((N(i)+s)*100+1);
    if m<1
        m=1;
    end
    if n>101
        n=101;
    end
    %Another precaution
    height(m+1:n)=1;
    %Adding all kernel heights to total height and storing them in 'h'
    j = j + height;
    %Re-initializing height after calculating for each kernel
    height=zeros(1,length(x));
end
%y axis is normalized to the number of data points i.e 1000 here
j=(j/1000)*20;

figure(2)
%num2str function is useful for labeling plots with numeric values.
%To get unbiased estimate of s
name =['Parzen Density Estimation with Uniform Kernels ' num2str(s*2)];
set(gcf,'name',name);
%plot for pdf of U
plot(x,h,'g','linewidth',3)
%hold on retains the current graph and adds another graph to it
hold on
%plot for pdf of N
plot(x,j,'r','linewidth',3)
title(name);
%xlabel(str) labels the x-axis of the current axes with the string, str
%ylabel(str) labels the y-axis of the current axes with the string, str
xlabel('Random numbers (U,N)');
ylabel('Kernel density (x,h/j)');
print(gcf,'-djpeg',[name '.jpg']);


%Estimation of pdf when window width is 0.1
%pdf for U vector
s=0.05; x=0:0.001:1; h=zeros(1,length(x)); l = length(U);
for i=1:l
    %x(i)=a+delx*(i-1)where index of x has to be an integer > 0
    m=round((U(i)-s)*1000+1);
    %x(i)=a+delx*(i-1) where index of x has to be an integer < 1000
    n=round((U(i)+s)*1000+1);
    if m<1
        m=1;
    end
    if n>1001
        n=1001;
    end
    %Another precaution
    height(m+1:n)=1;
    %Adding all kernel heights to total height and storing them in 'h'
    h = h + height;
    %Re-initializing height after calculating for each kernel
    height=zeros(1,length(x));
end
%y axis is normalized to the number of data points i.e 1000 here
h=(h/1000)*20;

%pdf for N vector
height=zeros(1,length(x));
j = zeros(1,length(x));
l = length(N);
for i=1:l
    %x(i)=a+delx*(i-1)where index of x has to be an integer > 0
    m=round((N(i)-s)*1000+1);
    %x(i)=a+delx*(i-1) where index of x has to be an integer < 1000
    n=round((N(i)+s)*1000+1);
    if m<1
        m=1;
    end
    if n>1001
        n=1001;
    end
    %Another precaution
    height(m+1:n)=1;
    %Adding all kernel heights to total height and storing them in 'h'
    j = j + height;
    %Re-initializing height after calculating for each kernel
    height=zeros(1,length(x));
end
%y axis is normalized to the number of data points i.e 1000 here
j=(j/1000).*(1/(s*2));

figure(3)
%num2str function is useful for labeling plots with numeric values.
%To get unbiased estimate of s
name=['Parzen Density Estimation with Uniform kernels ' num2str(s*2)];
set(gcf,'name',name);
%plot for pdf of U
plot(x,h,'g','linewidth',3)
%hold on retains the current graph and adds another graph to it
hold on
%plot for pdf of N
plot(x,j,'r','linewidth',3)
title(name);
%xlabel(str) labels the x-axis of the current axes with the string, str
%ylabel(str) labels the y-axis of the current axes with the string, str
xlabel('Random numbers (U,N)');
ylabel('Kernel density (x,h/j)');
print(gcf,'-djpeg',[name '.jpg']);

-------------------------------------------------------------
%Standard deviation vector is v and standard deviation is s
v=[0.01 0.05 0.1];
%This for loop traverses v and calculates the normal distribution for each s
for i=1:length(v)
    x=0:0.0001:1;
    height=zeros(1,length(x));
    j=zeros(1,length(x));
    h=zeros(1,length(x));
    l=length(N);
    u=length(U);
    %For loop traverses N and determines the height of each kernel
    for p=1:l
        %Normal distribution equation
        height=(1/(realsqrt(2*pi)*v(i))).*exp((-(x-N(p)).^2)/(2*v(i)^2));
        %Adding each kernel height to the total height
        j=j+height;
        height=zeros(1,length(x));
    end
    j=j/100;
 
%For loop traverses U and determines the height of each kernel 
    for q=1:u
%Normal distribution equation
        height1=(1/(realsqrt(2*pi)*v(i))).*exp((-(x-U(q)).^2)/(2*v(i)^2));
        %Adding each kernel height to the total height
        h=h+height1;
        %Re-initializing each kernel height
        height1=zeros(1,length(x));
    end
%Normalizing the y-axis to account for the 100 points
h=h/100;
figure(4)
name=['Parzen Density Estimation with Normal Kernels ' num2str(v(i))];
set(gcf,'name',name);
plot(x,h,'g','linewidth',2)
hold on
plot(x,j,'r','linewidth',2)
title(name);
xlabel('Random numbers (U,N)');
ylabel('Kernel density (x,h/j)');
print(gcf,'-djpeg',[name '.jpg']);
end
#####################

Suppose
a = 3
b = 7
who
a  b
Use of whos command will tell the variable attributes as size, bytes and class
whos
Attr Name        Size                     Bytes  Class                        
   ==== ====        ====                     =====  =====                        
        a           1x1                          8  double                       
        b           1x1                          8  double  
#####################