Friday 31 January 2014

Lenovo P770 Smartphone

Lenovo P770 is one of the best smartphones at an affordable price. I have been using this phone for nearly 6 months and it's performance is simply superb. The Lenovo P770 mobile phone's dual core processor delivers a smooth Android experience. The 3500 mAH battery charge lasts around 2 days even after using internet. Android Jelly Bean 4.1 gives you seamless access to all your favorite apps and games.4.5" IPS Display is awesome.It comes with dual-sim stand-by and primary,secondary cameras.


Buy Lenovo P770 from Flipkart.com
 


Specs:

SIM Type                
        Dual SIM, GSM + GSM, (Dual Standby)
Touch Screen
        Yes, Capacitive
OS
        Android OS v4.1 (Jelly Bean)
Processor
       1.2 Cortex A9, Dual Core
Graphics
       PowerVR SGX531
Display
       IPS LCD Capacitive Touchscreen
Size
       4.5 Inches
Resolution
       qHD, 540 x 960 Pixels
Primary Camera
       Yes, 5 Megapixel
Secondary Camera
       Yes, 0.3 Megapixel
HD Recording
       HD
Other Camera Features
       Auto Focus, Geo-tagging,Video Conference
Weight
       162 g
Battery
       Li-Ion, 3500 mAh
Talk Time
       30 hrs (2G), 16 hrs (3G)
Standby Time
       300 hrs (2G)
Memory & Storage   
       1 GB RAM, 4 GB ROM
       Expandable Memory ,microSD, upto 32 GB
Preinstalled Browser
       Android
3G
       Yes, 7.2 Mbps HSDPA; 5.76 Mbps HSUPA
Wifi
       Yes, 802.11 a/b/g/n
USB Connectivity
       Yes, micro USB, v2
Tethering
       Wi-fi Hotspot
Navigation Technology
       A-GPS, with Google Maps
Bluetooth
       Yes, v3
HDMI Port
       No
Audio Jack
       3.5 mm
Music Player
       Yes, Supports MP3
Video Player
       Yes, HD
FM
       Yes
Sensors
       Proximity, Accelerometer
Additional Features
       Polycarbonate Material, USB On-the-go, Multi-tasking, Games

Flipkart link

Thursday 16 January 2014

Java program to find CPU load using 'mpstat'

The following java program uses the linux command 'mpstat' to determine the CPU load .

To see the client-server version of the program with multiple clients, see here .


public class CpuLoad {
    public static void main(String args[]) {
      int i=1;
      float finalres;
      try{
        // execute the linux command
        Process p=Runtime.getRuntime().exec("mpstat");
        BufferedReader in=new BufferedReader(new   InputStreamReader(p.getInputStream()));
        String line=null;
        //read the row corresponding to cpu idle
        while((line=in.readLine())!=null && i<4){        
          i++;
        }      
        String res=line.substring(line.length()-5);
        finalres=Float.parseFloat(res);
        //convert the idle to cpuload
        System.out.println("CPU load:"+(100-finalres)+"%");
      }
      catch(Exception e){
        System.out.println(e);
      }
  }
}

Tuesday 14 January 2014

Shell scripting basics

Display the text “Cyber Security” in the shell prompt. Redirect the displayed line to a file.
Append the outputs of the commands to show the users logged into your system, your
login account and the current date in the ddmmyyyy format to the file.

touch file echo "Cyber Security" >>file 
echo "Users logged in:" >>file w >>file 
echo "my account:" >>file 
who am i >>file 
echo "Today it is:" >>file 
date +%d-%m-%Y >>file 

The ls command with the –R option lists the files in the specified directory and also
subdirectories, if any. Use this with a suitable pipe and filter arrangement to determine
whether a file exists in the account logged in.

echo "Listing all directories and files" 
ls -R 
echo "Enter file name to search" 
read fname echo "Searching for $fname :" 
echo "Search results are below :" 
ls -R|grep -x "$fname" 

Assuming you have a directory containing the following files:
men, orange, book, ant, lotus, apple
Use the ls command to list only those files that
a) consist of five letters
b) begin with the letter l
c) end with the letter t
d) have the second letter o

mkdir myfolder 
cd myfolder 
touch men orange book ant lotus apple 
echo All files in the directory: 
ls 
echo Files with name starting with 'l' : 
ls l* 
echo Files with name ending with 't': 
ls *t 
echo Files having the second letter 'o': 
ls [a-z][o]* 
echo Files with name having 5 letters: 
ls ????? 


 

Sunday 12 January 2014

Simple echo server and client using TCP/IP


Implement a simple echo server and client which uses TCP/IP for the communication. The client after 
establishing the connection, sends server a message which the latter echoes (i.e., the server prints out the 
message).The server should be capable of handling multiple clients. The clients need to know the address 
of server(IP address and port) it wants to communicate to beforehand.

Your client-server should not be a standalone pair of program. Server should be able to accept connections
from other clients and echo their message. You should be able to contact other servers and send a message 
to be echoed.

This project implements a simple echo server and client which uses TCP/IP for communication.

Programming language used: JAVA

How to compile : javac echoserver.java

To run : java echoserver

Do the same for echoclient.java file

To test :

1. Compile and run echoserver.java
2. Compile and run echoclient.java
3. Input the hostname and port number

You can access the project here
github repository
EXPLANATION

echoserver.java :
........................
As the Server should support multiple clients, we extend our java class to use thread concept.

public class echoserver extends Thread

Get port number to use as user input. The server socket waits forrequests to come in over the network. 
To establish the socket connection between the client and the server, we use

new echoserver (sSocket.accept());

Accept() is a blocking call. If the connection is accepted by the server, it reads a line from client's 
input stream. Server echoes the message and write to client's outputstream using PrintWriter

PrintWriter out = new PrintWriter(cSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader
(cSocket.getInputStream()));

Continuously read message from client

while ((clientmsg = in.readLine()) != null)
{
System.out.println ("Message from client: " + clientmsg);
out.println(clientmsg);
}

The socket and streams are closed after the use.

out.close();
in.close();
cSocket.close();

echoclient.java :
........................
Read the hostname and port number to connect.

Scanner sc= new Scanner(System.in);
BufferedReader s=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the IP address");
String ip=s.readLine();
System.out.println("Enter Port No. to connect");
int port =sc.nextInt();

Create a socket to connect to server

Socket clientsoc =null;

Write to the PrintWriter to send the message to server

out = new PrintWriter(clientsoc.getOutputStream(), true);

The second parameter of PrintWriter() is boolean (autoflush). Read server response from socket's
inputstream.

in = new BufferedReader(new InputStreamReader(clientsoc.getInputStream()));

On completion, close the open socket.

clientsoc.close();

Implementation of Stack data structure in Java using array


This program implements the stack data structure using array.
Read this post to study the implementation of queue data structure using array.


program : Stack.java

import java.awt.DisplayMode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Stack {
/**************************************************************************
Here size refers to the total size of stack,top points to the top element
of stack
**************************************************************************/
int size,top;
int[] stackArray;
public static int set=0;
/**************************************************************************
createStack() method is used to create a stack with user specified
number of elements .This function will return true if number of elements
are successfully read & stack Array is successfully created
*************************************************************************/
private boolean createStack() throws IOException{
try{
set=1;
System.out.println("Enter the number of elemetns of stack");
size=readNo();
stackArray=new int[size];
return true;
}
catch(Exception e)
{
return false;
}
}
/**************************************************************************
this readNo() function will read an integer from keyboard and returns the number

************************************************************************/
private int readNo(){
int no=-1;
try {
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
String entered;
entered = br.readLine();
no=Integer.parseInt(entered);
} catch (IOException e)
{
e.printStackTrace();
}
return no;
}
/**************************************************************************
Push() function is used to add new elements to the stack at its
top position.It will first increment the top to indicate new element
is added to the stack & the entered element is added to stack
************************************************************************/
private void Push(){
System.out.println("Enter the element to be inserted");
++top;
System.out.println(top);
int k=readNo();
stackArray[top]=k;
set=1;
}
/*************************************************************************
Pop() function is used to remove /pop elements from the top of stack.Here
top is decremented to indicate next element
*************************************************************************/
private void Pop() {
int topElement=stackArray[top];
--top;
System.out.println("The deleted number from stack is "+topElement);
}
/*************************************************************************
Display function is used to display all elements starting from top element

*************************************************************************/
private void display(){
int k=top;
System.out.println("Elements in Stack are::");
for(;k>=0;k--){
System.out.println(stackArray[k]+" ");
}
}

public static void main(String[] args) throws Exception{
/*******************************************************************
It creates an object of Stack class named 's'
***************************************************************/
int option=0;
Stack s=new Stack();
s.top=-1;
/***************************************************************************
It is a menu driven program.It runs until user enters exit option
**************************************************************************/
do{
System.out.println("Menu: \n 1- Create\n 2- Push\n 3- Pop\n 4- Display\n 5- Exit");
option=s.readNo();
if(option==1){
if(s.createStack()){
System.out.println("Stack created successfully");
}
else{
System.out.println("Stack not created");
}
}
else if(option==2){
if(set==1)
{
s.Push();
System.out.println("One item successfully added to Stack");
}
else
{
System.out.println("Create stack first");
}
}
else if(option==3){
if(s.top!=-1)
s.Pop();
else
{
System.out.println("Stack is empty ! or not build");
}
}
else if(option==4)
{
s.display();
}
}while(option!=5);
}
}

Implementation of Queue data structure in Java using array


This program implements the Queue data structure using array. Read the implementation of Stack data structure here.


Program: Queue.java

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Queue {

/*******************************************************************
front is where elements are deleted& rear is where elements are inserted
*******************************************************************/
int queueArray[],maxQueueSize,front,rear,currentQueueSize;
String enteredElement;

/********************************************************************
The function createQueue() creates a queue array with number of elements
as User's input
******************************************************************/
private void createQueue() throws Exception{

System.out.println("Enter the number of elements of Queue");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String s=br.readLine();
maxQueueSize=Integer.parseInt(s);
/*************************************************************************
This will create a queueArray with the size entered by user
**************************************************************************/
queueArray=new int [maxQueueSize];
/*************************************************************************
Initially the front is set as -1 & rear is set as 0 in order to indicate there
is no element in the queue.These values will be updated when elements are
added to the list
**************************************************************************/
front=-1;
rear=0;

}

/*******************************************************************
function readNo() reads an integer from keyboard & returns it
*******************************************************************/
private int readNo() throws Exception{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
enteredElement=br.readLine();
int no=Integer.parseInt(enteredElement);
return no;
}
/*************************************************************************
The function enQueue will add elements to the rear end of queue
************************************************************************/
private void enQueueRear() throws Exception{
if(front==-1)
++front;

/************************************************************************
If front=0&rear=0 which means there are no elements in the queue and we
are adding first element to the queue .Then we need to increment currentQueueSize
by one in order to indicate that we have added one element to the queue.Also
the value of rear needs to be updated

************************************************************************/
if(front==0&&rear==0){
System.out.println("Enter the element to be added to the rear end");
int no=readNo();
//We need to increment front in order to insert new element to queue
queueArray[rear]=no;
System.out.println("One element is added successfully to the queue"+rear);
++rear;
currentQueueSize++;

}
/************************************************************************
Also we can add elements to the queue if the value of rear is less than 
maxQueueSize
that is there are empty places in the queue, Then we can add elements to queue
************************************************************************/
else if(rear<maxQueueSize){
System.out.println("Enter the element to be added to the rear end");
int no=readNo();
//We need to increment front in order to insert new element to queue
queueArray[rear]=no;
System.out.println("One element is added successfully to the queue"+rear);
++rear;
currentQueueSize++;

}/************************************************************************
If rear==maxQueueSize then we can add elements to queue only if there are
empty slots in the front of array (i.e if currentQueueSize<maxQueueSize)
************************************************************************/
else if(rear==maxQueueSize&&currentQueueSize<maxQueueSize){
System.out.println("Enter the element to be added to the rear end");
int no=readNo();
rear=0;

queueArray[rear]=no;
System.out.println("One element is added successfully to the queue"+rear);
++rear;
currentQueueSize++;

}
/************************************************************************
If any of the above cases are not true that means there are no place in
the queue
************************************************************************/
else{
System.out.println("overflow");
}

}

/*****************************************************************************
The function deQueueFront() is used to delete elements from queueArray.it will
remove elements from Front
****************************************************************************/
private void deQueueFront(){

/**********************************************************************
If elements are present in queue i.e value of front less than rear
then we can delete element
**********************************************************************/
if(currentQueueSize==0){
System.out.println("Underflow");
}
else if(front0){
queueArray[front]=0;
++front;
--currentQueueSize;
System.out.println("One element has deleted");

}
else if(front==maxQueueSize&&currentQueueSize>0){

front=0;
queueArray[front]=0;
++front;
--currentQueueSize;
System.out.println("One element has deleted");

}

}

/****************************************************************************
The displayElement() function will display all elements of queue

***************************************************************************/
private void displayElement(){
/***********************************************************************
There wont be any elements when currentQueueSize==0
*********************************************************************/
if(currentQueueSize==0)
System.out.println("No elements in the Queue to display:");
/*************************************************************************
If currentQueueSize!=0 which means there are elements in the queue& we can
print them using below code
*************************************************************************/
else{
System.out.println("Elements in queue are ");
int i=front,j=0;

while(j<currentQueueSize){
if(i==maxQueueSize)
i=0;
System.out.println(queueArray[i]);

j++;i++;
}

}
}
public static void main(String[] args) throws Exception{
/************************************************************************
The Queue q=new Queue() will create a new object of Queue() class

**********************************************************************/
Queue q=new Queue();
q.createQueue();
int choice;
System.out.println("Menu Driven Queue Implementation using array::");
do{
System.out.println("Menu\n1 Enqueue\n2 Dequeue \n3 Display \n4 Exit");
System.out.println("Enter your choice");
choice=q.readNo();
if(choice==1)
q.enQueueRear();
else if(choice==2)
q.deQueueFront();
else if(choice==3)
q.displayElement();
}while(choice!=4);

}

}

Insertion sort using Java


import java.io.*;
import java.lang.Math;
public class insertion
{
public static void main(String args[])
{
 int []arr=new int[10];
 int i,j,t;
 System.out.println("Array before sorting:");
   for(i=0;i<arr.length;i++) {
   arr[i]=(int)(Math.random()*100);
   System.out.println(arr[i]);
   }
 for(j=1;j<arr.length;j++) { 
   t=arr[j]; 
   for(i=j-1;(i>=0) && (arr[i]>t);i--) {
       arr[i+1]=arr[i];
   }
 arr[i+1]=t;
 }
 System.out.println("Array after sorting:");
 for(j=0;j<arr.length;j++) {

 System.out.println(arr[j]);
 }
}

}

Bubble Sort using Java


import java.io.*;
import java.lang.Math;
public class bubble
{
public static void main(String args[])
{
int []arr=new int[10];
int i,j,t,flag=1;
System.out.println("Array before sorting:");
for(i=0;i<arr.length;i++) {
arr[i]=(int)(Math.random()*100);
System.out.print(arr[i]);
System.out.print(" ");
}
System.out.println("");
-------------------------------------------------------------------------
Compare each element adjacent to the current element and swap if required
-------------------------------------------------------------------------

for(i=0;i<arr.length && flag==1;i++) {
flag=0;
for(j=0;(j<arr.length-1);j++) {
if(arr[j+1]<arr[j]) {
t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
flag=1;
}
}
}
-------------------------------------------------------------------------
Display sorted array
-------------------------------------------------------------------------

System.out.println("Array after sorting:");
for(j=0;j<arr.length;j++) {

System.out.print(arr[j]);
System.out.print(" ");

}
System.out.println("");
}

}

Shell Sort Implementation using Java


import java.io.*;
import java.lang.Math;
public class shell
{
public static void main(String args[])
{
int []arr=new int[10];
int i,j,t,flag=1;
System.out.println("Array before sorting:");
  for(i=0;i1)) {
  flag=0;
  l=(l+1)/2;
   for(j=0;(j<arr.length-l);j++) {
     if(arr[j+l]<arr[j]) {
     t=arr[j+l];
     arr[j+l]=arr[j];
     arr[j]=t;
     flag=1;
     }
   }
  }
/*-------------------------------------------------------------------------
Display sorted array
-------------------------------------------------------------------------*/
System.out.println("Array after sorting:");
  for(j=0;j<arr.length;j++) {
  System.out.print(arr[j]);
  System.out.print(" ");
  }
System.out.println("");
}
}

Selection Sort using Java


import java.io.*;
import java.lang.Math;
public class selection
{
public static void main(String args[])
{
int []arr=new int[10];
int i,j,t,first;
System.out.println("Array before sorting:");
for(i=0;i<arr.length;i++) {
arr[i]=(int)(Math.random()*100);
System.out.print(arr[i]);
System.out.print(" ");
}
System.out.println("");
for(i=0;i0;i--) {
first=0;
for(j=1;jarr[first]) {
first=j;
}
}
t=arr[first];
arr[first]=arr[i];
arr[i]=t;
}
/*-------------------------------------------------------------------------
Display sorted array
--------------------------------------------------------------------------*/
System.out.println("Array after sorting:");
for(j=0;j<arr.length;j++) {
System.out.print(arr[j]);
System.out.print(" ");
}
System.out.println("");
}
}

Quick sort Implementation using Java


 
 
import java.io.*;
import java.lang.Math;
public class Quicksort {
public static void main(String args[]) {
int []arr=new int[10];
int i,j,t,first;
System.out.println("Array before sorting:");
  for(i=0;i<arr.length;i++) {
  arr[i]=(int)(Math.random()*100);
  System.out.print(arr[i]);
  System.out.print(" ");
  }
quickSort(arr,0,arr.length-1);  
/*-------------------------------------------------------------------------
Display sorted array
--------------------------------------------------------------------------*/
System.out.println("");
System.out.println("Array after sorting:");
  for(j=0;j=len)
      return;             // array length=0
      int l=low,n=len; 
      int pivot=a[(l+n)/2]; // pivot
      while(l<n)
           {               
                while(l<n && a[l]<pivot)   
                     l++;   
                while(l<n && a[l]>pivot)   
                     n--;   
               if(l<n){  
                 int tem = a[l];  
                 a[l]=a[n];  
                 a[n]=tem; 
               }
               if(n<l) {
               int t = l;l=n;n=t;   
               }  
           quickSort(a,low,l); //left array sorting
           quickSort(a,l==low?l+1:l,len);  //right array sorting
          }
}
}

Merge Sort Implementation using Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
 
public class MergeSort {
/*********************************************************************************
 The arrayUnsorted[] is where user inputs the unsorted elements
 arraySorted[]-array which will contain the elements of in sorted order
 temp[]-array which is used for temporary use
 length-indicates the number of elements in the array
 *********************************************************************************/
    int length,i;
    int arrayUnsorted[],arraySorted[],temp[];
    public static void main(String[] args) throws Exception{
       
        MergeSort ms=new MergeSort();
        ms.readArray();
        System.out.println("The Unsorted array is ");
        ms.displayArray(ms.arrayUnsorted);
        /*************************************************************************
         The array arrayUnsorted[] is copied to arraySorted[]
         mergeSort
         *************************************************************************/
        ms.copyArray(ms.arrayUnsorted, ms.arraySorted, 0, ms.length-1);
        ms.mergeSort(0, ms.length-1);
        System.out.println("The Sorted array is ");
        ms.displayArray(ms.arraySorted);

    }
    /*******************************************************************
     function readArray() reads the length of array & then reads all 
     elements to arrayUnsorted[]
     *******************************************************************/
    private void readArray() throws Exception{
        System.out.println("Enter the number of elements  in the array");
        length=readNo();
        arrayUnsorted=new int[length];
        arraySorted=new int[length];
        temp=new int[length];
        System.out.println("Enter the elements of array");
        for(i=0;i            arrayUnsorted[i]=readNo();   
        }
    }
    /*******************************************************************
     function readNo() reads an integer from keyboard & returns it
     *******************************************************************/
    private int readNo() throws Exception{
        String enteredElement;
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
        enteredElement=br.readLine();
        int no=Integer.parseInt(enteredElement);
        return no;
    }
    /**************************************************************************
     function displayArray() is used to display all the elements of the array,
     which  given as its input 
     **************************************************************************/
    private void displayArray(int[] arrayToDisplay ){
        int i;
        for(i=0;i                System.out.print(arrayToDisplay[i]);
                System.out.print(" ");
        }
        System.out.println();   
    }
    /*****************************************************************************
     function mergeSort() is where original divide and conquer approach happens.Here 
     the lower & upper limit of array are taken as input & the whole array is split 
     into two subarrays.Then these two subarrays are again divided until subarray 
     will have 1 element in it.Then sub arrays are merged in a sorted manner
     *****************************************************************************/
    private void mergeSort(int low,int high){
        if(low            int mid=(low+high)/2;
            mergeSort(low, mid);
            mergeSort(mid+1, high);
            merge(low,mid,high);           
        }               
    }
    /*****************************************************************************
     function merge() is used to merge two subarrays in a sorted manner.For temporary 
     storing results of sorted array, temp[] array is used.
     In this function the subarrays are individually sorted.The subarray elements are 
     compared with other & the elements of both array are stored to temporary array 
     in sorted manner.After sorting  the both arrays & then the sorted result is copied 
     from temp[] array to arraySorted[] 
     ******************************************************************************/
    private void merge(int low,int mid,int high){
        int i,j,k;
        i=j=low;
        k=mid+1;
        while(i<=mid&&k<=high){
            if(arraySorted[i]<=arraySorted[k]){
                temp[j]=arraySorted[i];
                i++;
            }
            else{
                temp[j]=arraySorted[k];
                k++;
               
            }
            j++;
        }
        while(i<=mid){
            temp[j]=arraySorted[i];
            j++;i++;
        }
        while(k<=high){
            temp[j]=arraySorted[k];
            k++;
            j++;
        }       
        copyArray(temp, arraySorted, low,high);       
    }   
    /****************************************************************************
      function copyArray() is used to copy existingArray[] to newArray with lower 
      & upper limits as existingArrayLow & existingArrayHigh 
     ***************************************************************************/
    private void copyArray(int existingArray[],int newArray[],int existingArrayLow,int existingArrayHigh){
        for(int i=existingArrayLow;i<=existingArrayHigh;i++){
            newArray[i]=existingArray[i];
        }       
    }
}

Wednesday 8 January 2014

Configuring GitHub account

GitHub is an online project hosting service. It offers both paid plans for private repositories, and free accounts for open source projects.

It is the most popular open source code repository. This post provides a simple step by step procedure to configure a free account on GitHub and explains how to upload your projects in to the repository.

1. Create an account at GitHub
Sign up for a free account and verify your email ID.

Here is my GitHub repository : MyProjects

2. Create a repository

A repository is the directory where you keep your projects. See the right corner of your homepage after log in.

Click on the 'Create new repo' icon and a box will appear

Give an appropriate name and description for your repository .

Create it..

Create your directories in an organized manner.

Read this for setting up Git in your system

Uploading Files to the repository

1. First you need to sync your local directory with the Git online directory

Make a directory in your system

mkdir mygitdirectory

cd to mygitdirectory

Now initialise Git by

git init

To sync the online content

git clone https://github.com/yourusername/yourdirectory_path.git

You will see that the entire files inside your local folder.

You can edit the files, add new or delete.

Now you need to commit the changes

Suppose you created a file 'hello' and to upload it to the repository,use the following commands in terminal

git add hello                            //file is added

git commit -m 'first commit'   //commit message

git remote add origin https://github.com/yourusername/MyProject.git           

git push origin master           //pushing file into GitHub

Congratulations !! You have made your first commit