Labels
Ivy vs Maven
Check out the difference between them at Ivy FAQ.
Also check the Ivy creator opinion at Xavier Hanin's Blog: Ant+Ivy vs Maven: my biased opinion.
Shell Script System info
#!/bin/sh
echo "###############################"
echo " Hardware Details "
echo "###############################"
echo "HostName:`uname -n`"
echo "Machine Name:`uname`"
echo "Processor Name:`uname -p`"
echo "##############################"
echo " Software details "
echo "##############################"
echo "Os Name:`uname -o`"
echo "Os Release:`uname -r`"
echo "Od version:`uname -v`"
Shell Script to find out if a rectangle type
echo "Enter Angle A:"
read A
echo "Enter Angle B:"
read B
echo "Enter Angle C:"
read C
if [ $A -eq 90 -o $B -eq 90 -o $C -eq 90 ]
then
echo "This is Right angled Triangle"
elif [ $A -gt 90 -o $B -gt 90 -o $C -gt 90 ]
then
echo "This is Obtuse angled Triangle"
elif [ $A -lt 90 -a $B -lt 90 -a $C -lt 90 ]
then
echo "This is acute angled Triangle"
fi
Shell Script Linux
the first line in the shell script should be the interpreter location to be used
#!/bin/bash ----> this interpreter is taken to execute the file
if this is not there the shell which launched this will be taken.
echo –n no new line
eco –e take special
| Double Quotes | does interpolation , substitutes with var value |
| Single Quotes | no manipulation directly prints |
| Back Quotes | executes a command and gives us output. |
Special variables in shell
program to print
- program name
- number of paramerters
- all arguments
echo "program name is $0"
echo "argument one dollar 1 $1"
echo "argument two dollar two $2"
echo "argument three Dollar three $3"
IFS=":"
echo "all args $@ "
echo "all args with delimiter $* "
If in Shell Script:
if test $x –lt $y
OR
if [$x –lt $y]
Check the file properties
root@v11> if [ -e shell.sh ]; then echo yes ; else echo no; fi
yes
root@v11> if [ -f shell.sh ]; then echo yes ; else echo no; fi
yes
root@v11> if [ -d shell.sh ]; then echo yes ; else echo no; fi
no
root@v11> if [ -L shell.sh ]; then echo yes ; else echo no; fi
no
root@v11> if [ -r shell.sh ]; then echo yes ; else echo no; fi
yes
Case in Shell Script:
case $1 in
a) echo "this is a";;
b) echo "this is b";;
c) echo "this is c";;
*) echo "this is default";;
esac
While in Shell Script:
num=0;
while [ $num -lt $# ]
do
echo $num
num=$[num+1]
done
Until in Shell Script:
For in Shell Script:to print all the command line arguments passed using for
for i in $@
do
echo $i
done
Handling Signals
trap "echo trapped; exit;" SIGINT
while [ 1 ]
do
echo "hi"
done
Linux Set and Tar commands
SET
shows the list of environment variables
[trainee@localhost purna]$ set
BASH=/bin/bash
BASH_ARGC=()
BASH_ARGV=()
BASH_LINENO=()
BASH_SOURCE=()
BASH_VERSINFO=([0]="3" [1]="1" [2]="17" [3]="1" [4]="release" [5]="i686-redhat-linux-gnu")
BASH_VERSION='3.1.17(1)-release'
COLORS=/etc/DIR_COLORS.xterm
COLUMNS=80
tar
to tar
tar –cvf <file.tar> input files list
untar
tar –xvf <file.tar>
tar –zxvf will unzip and untar it.
At,Batch and Cron
crontab:
l list
e edit
r remove
format of the file
| minutes | hour | day | month | days of week | Command |
0 * * * “mon-sat” echo “Hello”
every hour you get a hello message.
the output of the above is sent to mail.
Processes in Linux
Program ?
- process if different from a program.
- Program under execution is a process.
- Program is set of instructions.
INIT: Mother of all the processes.
- Fork: if there is process P1 can fork out into multiple processes which are identical,Independent P1 and P2 with different PID’s.
- Exec:
- Wait:
Rights of Process
- Who am i ? what is its pid
- who is my parent ? what is my parent process id
- what happened to my child ?
Orphan Process :
the process whose parent died,when a parent process is killed the INIT process takes the responsibility that's the reason its called mother of all the processes.
Zombie Process :
A process
PS
processes running on your terminal
[trainee@localhost purna]$ ps
PID TTY TIME CMD
6188 pts/14 00:00:00 bash
6507 pts/14 00:00:00 ps
number of processes running
[trainee@localhost purna]$ ps -e|wc -l
164
processes running on a terminal pts/3
[trainee@localhost purna]$ ps -tpts/3
PID TTY TIME CMD
4300 pts/3 00:00:00 bash
6612 pts/3 00:00:00 cat
DAEMON
Disk And Execution Monitor
JOBS
will print all the jobs which are stopped or paused .
to resume these jobs one can use fg or bg (foreground or background) %JOB_NUMBER
KILL
list all signals
[trainee@localhost purna]$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+338)SIGRTMIN+4}Dummy signals
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
Kill A Process
[trainee@localhost purna]$ kill -s SIGKILL 4524
where 4524 is the process id
Nice
the lesser the Nice value the higher the priority
only the root can make the priority higher or nice value to low.
Regular Expressions in Linux
Regular Expression:
| [.] DOT | dot matches for a single character |
| [abcd] | matches one of the list ,say [abcd] matches one of a,b,c,d |
| [a-d] | matches the range of characters a to d |
| [^a-i] | should not contain the range a to i |
| [a*] ~= {0,} | match zero or more a’s |
| [a+] ~= {1,} | match one or more a’s |
| [a?] ~= {0,1} | zero or one occurance of letter a |
| wh(at|en|ere} | what when where , you can specify group of letters and also a pipe to mark OR operator |
| ^not | start with string not,notify,notice etc…… |
| not$ | end with not like knot |
GREP: search Globally for Regular Expression and Print
| grep | option[s] |
| -n number in the file | |
| -c count the number of occurrences, unlike wc –l it gives the file wise count | |
| -A context selection After -B Context selection Before you can specify number with A or B | |
| -l List the names of files | |
| -r recursively Grep | |
| -s , if there are permission errors it suppresses | |
| -e used to search multiple regular expressions |
Egrep: Extended GREP { More operators +,?,(),|}
Fgrep: Fixed length Grep , does not support operators
VI Editor
VI – Visual Editor.
| Normal | no sign |
| Command Line | : colon |
| Input | INSERT/REPLACE |
Normal –> Insert mode a,i,o,r,s A,I,O,R,S
Esc/Enter –> to normal mode.
: to command line mode.
H
-{minus} k
0<----h * l---->$ ----------------------->M
Enter j
L
GG= go to line number
x delete command
X replacement for back space
u undo char by char
U undo at once
DW delete a word
DD delete a whole line
repeat a command 5x will delete 5 chars meaning number specifies number of times the command has to be executed.
| q | quit, vi wont allow if there are any changes done. |
| q! | quit without saving |
| wq | write and quit |
| wq <filename> | save as file name and quit,if file not exists |
| wq! <filename> | save as file name and quit,if file exists |
| r! <Command> | run the command and put the output at the cursor position |
| sh | takes u to shell from vi ,where you can execute commands and come back. |
Some more linux Commands
file: give the type of the file , which is determined using the extension of the file.
[trainee@localhost purna]$ file *
as: directory
f2: empty
f3: ASCII text
f4: ASCII text
f5: ASCII text
WC: gives the word count in a file or some stream of data.
c=character count
l = line count
L = length of the longest line
w= word count
split: split a file into many parts , the default is 1000 lines but you can use –l option and specify number of lines.
[trainee@localhost purna]$ split -l 5 f5
[trainee@localhost purna]$ ls
as f3 f5 g1 xaa xac xae xag xai
f2 f4 fruits g2 xab xad xaf xah xaj
splits f5 file to many files like
xaa xac xae xag xai
xab xad xaf xah xaj
cmp: check if two files are same
when they are equal there is no output
else it looks like this
[trainee@localhost purna]$ cmp xaa xab
xaa xab differ: byte 1, line 1
[trainee@localhost purna]$ cmp -l xaa xab
1 40 61
2 40 70
4 40 61
5 40 71
Heap Sort
Heap Sort in C++
#include < iostream.h >
#include < conio.h >
int heapSize = 10;
void print(int a[]) {
for (int i = 0; i <= 9; i++) {
cout << a[i] << "-";
}
cout << endl;
}
int parent(int i) {
if(i==1)
return 0;
if(i%2==0)
return ( (i / 2)-1);
else
return ( (i / 2));
}
int left(int i) {
return (2 * i) + 1;
}
int right(int i) {
return (2 * i) + 2;
}
void heapify(int a[], int i) {
int l = left(i), great;
int r = right(i);
if ( (a[l] > a[i]) && (l < heapSize)) {
great = l;
}
else {
great = i;
}
if ( (a[r] > a[great]) && (r < heapSize)) {
great = r;
}
if (great != i) {
int temp = a[i];
a[i] = a[great];
a[great] = temp;
heapify(a, great);
}
}
void BuildMaxHeap(int a[]) {
for (int i = (heapSize - 1) / 2; i >= 0; i--) {
heapify(a, i);
print(a);
}
}
void HeapSort(int a[]) {
BuildMaxHeap(a);
for (int i = heapSize; i > 0; i--) {
int temp = a[0];
a[0] = a[heapSize - 1];
a[heapSize - 1] = temp;
heapSize = heapSize - 1;
heapify(a, 0);
}
}
void main() {
int arr[] = {
2, 9, 3, 6, 1, 4, 5, 7, 0, 8};
HeapSort(arr);
print(arr);
}
Quick Sort
Quick Sort in c++
#include < iostream.h >
#include < stdio.h >
#include < conio.h >
void print(int a[]) {
for (int i = 0; i < 10; i++) {
cout << a[i] << "-";
}
cout << endl;
}
int partition(int a[], int p, int r) {
int x = a[r];
int j = p - 1;
for (int i = p; i < r; i++) {
if (x <= a[i]) {
j = j + 1;
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
a[r] = a[j + 1];
a[j + 1] = x;
return (j + 1);
}
void quickSort(int a[], int p, int r) {
if (p < r) {
int q = partition(a, p, r);
quickSort(a, p, q - 1);
quickSort(a, q + 1, r);
}
}
void main() {
int a[] = {
1, 9, 0, 5, 6, 7, 8, 2, 4, 3};
quickSort(a, 0, 9);
print(a);
getch();
}
Merge Sort
Merge sort in C
#include < iostream.h >
#include < conio.h >
#include < stdio.h >
void print(int * a) {
for (int i = 0; i < 10; i++) {
cout << a[i] << "-";
}
cout << endl;
}
void mergeConquer(int * a, int left, int mid, int right) {
int lno = mid - left + 1;
int rno = right - mid;
int * L = new int[lno];
int * R = new int[rno];
for (int y = 0; y < lno; y++) {
L[y] = a[left + y];
cout << L[y] << "l";
}
cout << endl;
for (int z = 0; z < rno; z++) {
R[z] = a[mid + z + 1];
cout << R[z] << " r "; ;
}
cout << endl;
y = 0;
z = 0;
for (int i = left; i <= right; i++) {
if ( (y < lno) && (z < rno)) {
if (L[y] <= R[z]) {
a[i] = L[y];
y++;
}
else {
a[i] = R[z];
z++;
}
}
else if ( (y < lno) && (z >= rno)) {
a[i] = L[y];
y++;
}
else if ( (y >= lno) && (z < rno)) {
a[i] = R[z];
z++;
}
}
}
void mergeDivide(int * a, int left, int right) {
int mid = (left + right) / 2;
if (left < right) {
cout << "============";
mergeDivide(a, left, mid);
mergeDivide(a, mid + 1, right);
mergeConquer(a, left, mid, right);
}
}
void main() {
clrscr();
int a[] = {
5, 24, 6, 48, 9, 40, 42, 3, 1, 7};
mergeDivide(a, 0, 9);
print(a);
}
Stack
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
#include <stdlib.h>
class element
{
public:
int value;
element* next;
};//class element
class stack
{
public:
int size;
element* current;
stack()
{
size=0;
current=NULL;
}//default constructor
bool push(int,element*);
bool pop();
bool isEmpty();
int getStackSize();
void printStackSize();
void printStackElements(element*);
void printStackMenu();
};
bool stack::push(int ele,element* temp)
{
temp=new element;
if(current==NULL)
{
temp->next=NULL;
}
else
{
temp->next=current;
}
temp->value=ele;
current=temp;
printf("%d inserted\n\n",ele);
size++;
return false;
}
bool stack::pop()
{
if(isEmpty())
{
cout<<"\nStack is Empty\n";
return false;
}
else
{
cout<<"\n Element To POP :"<<current->value;
cout<<"\n Before POP";
printStackElements(current);
current=current->next;
cout<<"\n After POP";
printStackElements(current);
size=size--;
}
return true;
}
bool stack::isEmpty()
{
if(getStackSize()==0)
return true;
return false;
}
int stack::getStackSize()
{
return size;
}//returns size of the stack
void stack::printStackSize()
{
cout<<"\nThe Size of the Stack:"<<size<<"\n";
}//print the stack size
void stack::printStackElements(element* base)
{
element* curr2;
curr2= base;
cout<<"\n-----\n";
cout<<"STACK\n";
cout<<"-----\n";
while(curr2!=NULL)
{
cout<<" |"<<curr2->value<<"|\n";
curr2=curr2->next;
}
}// print the stack
void stack::printStackMenu()
{
cout<<"Welcome to Stack \n";
cout<<"1.Push an element\n";
cout<<"2.Pop an element\n";
cout<<"3.Display Stack\n";
cout<<"4.Size Of Stack\n";
cout<<"5.Exit\n";
}
void main()
{
stack st;
char Option=0;
int val;
while(1)
{
st.printStackMenu();
cin>>Option;
switch(Option)
{
case '1':
cout<<"Enter a Number \n";
cin>>val;
st.push(val,st.current);
break;
case '2':
st.pop();
break;
case '3':
st.printStackElements(st.current);
break;
case '4':
st.printStackSize();
break;
case '5':
exit(0);
break;
}
}
}
Queue
#include <iostream.h>
class element
{
public:
int value;
element* next;
};//class element
class Queue
{
public:
int size;
element* head;
element* tail;
Queue()
{
size=0;
head=NULL;
tail=NULL;
}//default constructor
void Enqueue(int);
void Dequeue();
int isEmpty();
int getQueueSize();
void printQueueSize();
void printQueueElements();
void printQueueMenu();
};
void Queue::Enqueue(int ele)
{
if(head==NULL) // first element
{
head=new element;
tail=head; //head==tail if one element
head->value=ele;
head->next=NULL;
}
else
{
tail->next=new element;
tail->next->value=ele;
tail->next->next=NULL;
cout<<tail->next->value<<endl;
tail=tail->next;
}
size++;
//printQueueElements();
}
void Queue::Dequeue()
{
if(getQueueSize()==0)
return;
else if(head==tail)
{
head=NULL;
}
else
{
element *curr,*prev; //remove the first element inserted and
curr=head; //point the head to next element
head=curr->next;
curr=NULL;
}
size--;
}
int Queue::isEmpty()
{
if(getQueueSize()==0)
return 1;
return 0;
}
int Queue::getQueueSize()
{
return size;
}//returns size of the Queue
void Queue::printQueueSize()
{
cout<<"\nThe Size of the Queue:"<<size<<"\n";
}//print the Queue size
void Queue::printQueueElements()
{
element* curr2;
curr2= head;
cout<<"\n-----\n";
cout<<"Queue\n";
cout<<"-----\n";
cout<<"size:"<<getQueueSize()<<endl;
while(curr2!=NULL)
{
cout<<" |"<<curr2->value<<"|";
curr2=curr2->next;
}
cout<<endl;
}// print the Queue
void Queue::printQueueMenu()
{
cout<<"Welcome to Queue \n";
cout<<"1.Enqueue an element\n";
cout<<"2.Dequeue an element\n";
cout<<"3.Display Queue\n";
cout<<"4.Size Of Queue\n";
cout<<"5.Exit\n";
}
void main()
{
Queue qt;
qt.printQueueMenu();
char Option=0;
int val;
while(1)
{
qt.printQueueMenu();
cin>>Option;
switch(Option)
{
case '1':
cout<<"Enter a Number \n";
cin>>val;
qt.Enqueue(val);
break;
case '2':
qt.Dequeue();
break;
case '3':
qt.printQueueElements();
break;
case '4':
qt.printQueueSize();
break;
case '5':
exit(0);
break;
}
}
}
Double Linked List
#include <iostream.h>
class node
{
public:
int value; //value stored in the node
node *next; //pointer to next node
node *prev; //pointer to previous node
};
class dlist
{
public:
node *front; //pointer to front of list
node *back; //pointer to back of list
dlist()
{
front=NULL;
back=NULL;
}
void insertFront(int value);
void insertBack(int value);
void removeFront();
void removeBack();
void insertBefore(int value,node *nodeB);
void insertAfter(int value,node *nodeA);
void removeBefore(node *nodeB);
void removeAfter(node *nodeA);
void removeNode(node *newNode);
void printDListFront();
void printDListBack();
};
//insert a node before nodeB
void dlist::insertBefore(int value,node *nodeB)
{
node *newNode;
newNode=new node();
newNode->prev=nodeB->prev;
newNode->next =nodeB;
newNode->value =value;
if(nodeB->prev==NULL)
{
this->front=newNode;
}
nodeB->prev=newNode;
}
//insert a node before the front node
void dlist::insertFront (int value)
{
node *newNode;
if(this->front==NULL)
{
newNode=new node();
this->front=newNode;
this->back =newNode;
newNode->prev=NULL;
newNode->next=NULL;
newNode->value=value;
}
else
{
insertBefore(value,this->front );
}
}
//insert a node after nodeB
void dlist::insertAfter(int value,node *nodeB)
{
node *newNode;
newNode=new node();
newNode->next= nodeB->next ;
newNode->prev =nodeB;
newNode->value =value;
if(nodeB->next==NULL)
{
cout<<"\n "<< endl;
this->back =newNode;
}
nodeB->next=newNode;
cout<<"2"<<endl;
}
//insert a node after the last node
void dlist::insertBack (int value)
{
if(this->back==NULL)
{
cout<<"insert at back";
insertFront(value);
}
else
{
cout<<"insert at back";
insertAfter(value,this->back );
}
}
//remove the front node
void dlist::removeFront ()
{
removeNode(this->front);
}
//remove a back node
void dlist::removeBack ()
{
removeNode(this->back);
}
//remove before a node
void dlist::removeBefore(node *nodeB)
{
if(nodeB->prev==this->front)
{
this->front=nodeB;
this->front->prev=NULL;
}
else
{
removeNode(nodeB->prev);
}
}
//remove after a node
void dlist::removeAfter(node *nodeA)
{
if(nodeA->next==this->back)
{
this->back=nodeA;
this->back->next=NULL;
}
else
{
removeNode(nodeA->next);
}
}
//remove a perticular node
void dlist::removeNode(node *nodeToRemove)
{
if(nodeToRemove==this->front)
{
this->front=this->front->next;
this->front->prev=NULL;
}
else if (nodeToRemove==this->back)
{
this->back=this->back->prev;
this->back->next=NULL ;
}
else
{
nodeToRemove->prev->next=nodeToRemove->next;
nodeToRemove->next->prev=nodeToRemove->prev;
}
}
//Print the list from front
void dlist::printDListFront()
{
node* curr2;
curr2= this->front;
cout<<"\n-----\n";
cout<<"Queue\n";
cout<<"-----\n";
//cout<<"size:"<<getQueueSize()<<endl;
while(curr2!=NULL)
{
cout<<" |"<<curr2->value<<"|";
curr2=curr2->next;
}
cout<<endl;
}// print the Double Linked List from front
// print the Double Linked List from backwards
void dlist::printDListBack()
{
node* curr2;
curr2= this->back;
cout<<"\n-----\n";
cout<<"Queue\n";
cout<<"-----\n";
//cout<<"size:"<<getQueueSize()<<endl;
while(curr2!=NULL)
{
cout<<" |"<<curr2->value<<"|";
curr2=curr2->prev;
}
cout<<endl;
}// print the Double Linked List from back
void main()
{
dlist *st ;
st= new dlist();
st->insertBack(8);
st->printDListFront ();
st->insertBack(5);
st->printDListFront ();
st->insertBack(6);
st->printDListFront ();
st->insertFront(1) ;
st->printDListFront ();
st->insertFront(3) ;
st->printDListFront ();
st->insertBack(7);
st->printDListFront ();
st->removeFront();
st->printDListFront ();
st->removeBack();
st->printDListFront ();
}Binary Search Tree
Binary Search Tree
import java.*;
import java.lang.*;
//node of the binary tree
class bnode {
String key;
bnode left;
bnode right;
bnode() {
key = null;
left = null;
right = null;
}
bnode(String key) {
this.key = key;
left = null;
right = null;
}
};
//binary tree
class btree {
bnode root;
btree() {
root = null;
}
//insert a node into the tree
void put(String key) {
bnode current = root;
bnode prev = current;
if (root == null) {
root = new bnode(key);
}
else {
boolean insert = false;
while (insert == false) {
prev = current;
if (key.compareTo(current.key) < 0) {
if (current.left == null) {
current.left = new bnode(key);
insert = true;
}
current = current.left;
}
else {
if (current.right == null) {
current.right = new bnode(key);
insert = true;
}
current = current.right;
}
}
}
}
//delete a node with a key
boolean delete(String key) {
boolean deleted = true;
bnode current = root;
bnode prev = current;
while (current != null) {
if (key.compareTo(current.key) > 0) {
prev = current;
current = current.right;
}
else if (key.compareTo(current.key) < 0) {
prev = current;
current = current.left;
}
else if (key.compareTo(current.key) == 0) {
deleted = false;
break;
}
}
if (check(current) == 0) {
if (current.key.compareTo(prev.key) > 0) {
prev.right = null;
}
else {
prev.left = null;
}
}
else if (check(current) == 1) {
if (current.key.compareTo(prev.key) > 0) {
if (current.left != null) {
prev.right = current.left;
}
else {
prev.right = current.right;
}
}
else {
if (current.left != null) {
prev.left = current.left;
}
else {
prev.left = current.right;
}
}
}
else if (check(current) == 2) {
bnode temp = inord(current);
if (current == root) {
root.key = temp.key;
}
else {
if (current.key.compareTo(prev.key) > 0) {
prev.right.key = temp.key;
}
else {
prev.left.key = temp.key;
}
}
}
return deleted;
}
//in order
bnode inord(bnode a) {
int t = 0;
bnode ret, prev = new bnode();
prev = a;
a = a.right;
while (a.left != null) {
prev = a;
a = a.left;
t = 1;
}
ret = a;
if (t == 0) {
prev.right = null;
}
else {
prev.left = null;
}
a = null;
return ret;
}
//check if a node is there
int check(bnode a) {
int ret;
if ( (a.left != null) && (a.right != null)) {
ret = 2;
}
else if ( (a.left == null) && (a.right == null)) {
ret = 0;
}
else {
ret = 1;
}
return ret;
}
//print the node
void printIn(bnode oot) {
if (oot.left != null) {
printIn(oot.left);
}
System.out.println("--------" + oot.key + "----------");
if (oot.right != null) {
printIn(oot.right);
}
}
public static void main(String[] args) {
btree a = new btree();
a.put("h");
a.put("g");
a.put("e");
a.put("d");
a.put("f");
a.put("c");
a.put("b");
a.put("a");
a.put("i");
a.printIn(a.root);
a.delete("h");
a.delete("e");
a.printIn(a.root);
}
}
Towers OF hanoi program in c++
#include <iostream.h>
// a disk with a value , which is an element of the stack ,tower in this case
class Disk
{
public:
int value;
Disk* next;
};//class Disk
class Tower //a stack data structure representing a tower
{
public:
int size;
Disk* current;
Tower()
{
size=0;
current=NULL;
}//default constructor
int peep();
bool push(int);
bool pop();
bool isEmpty();
int getTowerSize();
void printTowerSize();
void printTowerDisks();
void printTowerMenu();
};
int Tower::peep()
{
return this->current->value;
}
bool Tower::push(int ele)
{
Disk* temp;
temp=new Disk;
if(current==NULL)
{
temp->next=NULL;
}
else
{
temp->next=current;
}
temp->value=ele;
this->current=temp;
size++;
return false;
}
bool Tower::pop()
{
if(isEmpty())
{
cout<<"\nTower is Empty\n";
return false;
}
else
{
current=current->next;
size=size--;
}
return true;
}
bool Tower::isEmpty()
{
if(getTowerSize()==0)
return true;
return false;
}
int Tower::getTowerSize()
{
return size;
}//returns size of the Tower
void Tower::printTowerSize()
{
cout<<"\nThe Size of the Tower:"<<size<<"\n";
}//print the Tower size
void Tower::printTowerDisks()
{
if(this->isEmpty())
{
cout<<"-----\n";
cout<<" "<<endl;
cout<<"-----\n";
return;
}
Disk *curr2;
curr2=this->current ;
cout<<"-----\n";
cout<<"Tower\n";
cout<<"-----\n";
int i=0;
while(curr2 !=NULL)
{
if(i>4)
break;
i++;
cout<<" |"<<curr2->value<<"|\n";
curr2=curr2->next;
}
}// print the Tower
void createSourceTower(Tower *source,int numberOfDisks)
{
for(int i=numberOfDisks;i>0;i--)
{
source->push(i);
}
}
void moveDisk(Tower *source,Tower *dest) // movinng a disk from source to destionation
{
dest->push(source->current->value );
source->pop();
}
void hanoi( int N, Tower *source, Tower *dest,Tower *aux ) // move N disks from source to destination
{
if (N > 0 )
{
hanoi(N - 1, source, aux, dest); //move n-1 disks from source to auxxilary (sub problem)
moveDisk(source,dest); //move nTH disk from source to destination
hanoi(N - 1, aux, dest, source); //move n-1 disks from auxillary to destination (sub problem)
}
}
void main()
{
Tower *source,*destination,*auxillary;
//Towers required for the 3 towers source destination and auxillary
source=new Tower;
destination=new Tower;
auxillary=new Tower;
//take number of disks from user
int numberOfDisks;
cout<<"Enter number of Disks in the source Tower";
cin>>numberOfDisks;
//inserting the disks into the source tower
createSourceTower(source,numberOfDisks);
cout<<"==============================================="<<endl;
cout<<"Initial Scenario of the Towers "<<endl;
cout<<"Source"<<endl;
source->printTowerDisks ();
cout<<"Auxillary"<<endl;
auxillary->printTowerDisks ();
cout<<"Destination"<<endl;
destination->printTowerDisks ();
hanoi( numberOfDisks,source, destination, auxillary );
cout<<"==============================================="<<endl;
cout<<"Final Scenario of the Towers "<<endl;
cout<<"Source"<<endl;
source->printTowerDisks();
cout<<"Auxillary"<<endl;
auxillary->printTowerDisks ();
cout<<"Destination"<<endl;
destination->printTowerDisks ();
cout<<"==============================================="<<endl;
}
Is Prime Number
#include<iostream.h>
#include <math.h>
void main()
{
int number;
cout<<" ---------------------------------------------"<<endl;
cout<<" Enter a number to find if its a prime number "<<endl;
cout<<" ---------------------------------------------"<<endl;
cin>>number;
bool a =true;
for(int i=2;i<sqrt(number);i++) //check untill the square root
{
if(number%i==0) // if it is divisible it is non prime
{
a=false;
break;
}
}
if(a==false)
cout<<number<<" is not a prime number"<<endl;
else
cout<<number<<" is a prime number"<<endl;
}
GCD (Greatest Common Divisor ) Euclids way
GCD (Greatest Common Divisor ) Euclids way
public class GreatestCommonDivisor {
//using euclid's way of calculating GCD
static int greatestCommonDivisor(int a, int b) {
int gdivisor = 1, divider, dividend;
if (a < b) { // the one less is divisor the one greater is dividend
divider = a;
dividend = b;
}
else {
divider = b;
dividend = a;
}
if (dividend % divider == 0) { //its the GCD
return divider;
}
else { //proceed further
greatestCommonDivisor(divider, dividend % divider);
}
return gdivisor; //the GCD of the 2 numbers
}
public static void main(String args[]) {
System.out.println(greatestCommonDivisor(5, 144));
}
}
GCD (Greatest Common Divisor ) Euclids way
Permutations program in java
class permutations {
static void print(int v[], int n) {
for (int i = 0; i < n; i++) {
System.out.print(v[i] + " ");
}
System.out.println("\n");
}
static void permute(int v[], int start, int n) {
if (start == (n - 1)) {
//if its the end of the sequence genereated then print them
print(v, n);
}
else {
for (int i = start; i < n; i++) {
//swap the start element woith the ith element to get n first sequeces
int temp = v[start];
v[start] = v[i];
v[i] = temp;
permute(v, start + 1, n);
//of the n the first is kept constant the same is applied for the rest sequence
v[i] = v[start];
v[start] = temp;
}
}
}
public static void main(String[] args) {
System.out.println("learn 2day permutaions!");
int v[] = {
1, 2, 3};
//this is the array which should contain the items to be permuted
permute(v, 0, v.length);
}
}
Simple Permutations program in java
Selection Sort
#include <iostream.h>
void selectionSort(int *array,int length)//selection sort function
{
int i,j,min,minat;
for(i=0;i<(length-1);i++)
{
minat=i;
min=array[i];
for(j=i+1;j<(length);j++) //select the min of the rest of array
{
if(min>array[j]) //ascending order for descending reverse
{
minat=j; //the position of the min element
min=array[j];
}
}
int temp=array[i] ;
array[i]=array[minat]; //swap
array[minat]=temp;
}
}
void printElements(int *array,int length) //print array elements
{
int i=0;
for(i=0;i<10;i++)
cout<<array[i]<<endl;
}
void main()
{
int a[]={9,6,5,23,2,6,2,7,1,8}; // array to sort
selectionSort(a,10); //call to selection sort
printElements(a,10); // print elements
}
Count Sort
#include < iostream.h >
#include < stdio.h >
#include < conio.h >
void print(int a[]) {
for (int i = 0; i < 10; i++) {
cout < < a[i] < < "-";
}
cout < < endl;
}
int max(int a[]) {
int mac = 0;
for (int i = 0; i < 10; i++) {
if (a[i] > mac) {
mac = a[i];
}
}
cout < < "ths is mac " < < mac < < endl;
return mac;
}
void countTimes(int a[], int b[]) {
int maxi = max(a);
for (int i = 0; i < = maxi; i++) {
b[i] = 0;
}
for (i = 0; i < 10; i++) {
b[a[i]] = b[a[i]] + 1;
}
}
void countRanks(int b[]) {
for (int i = 1; i < = 7; i++) {
b[i] += b[i - 1];
}
}
void countSort(int a[], int b[], int c[]) {
int l = 0;
for (int i = 9; i >= 0; i--) {
cout < < a[i] < < "-" < < b[a[i]] < < "\n";
c[b[a[i]] - 1] = a[i];
b[a[i]] = b[a[i]] - 1;
}
print(c);
}
void main() {
clrscr();
int a[] = {
1, 2, 4, 6, 7, 7, 0, 6, 3, 5};
print(a);
int * b;
int mac = max(a);
int c[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
b = new int[mac];
countTimes(a, b);
countRanks(b);
countSort(a, b, c);
print(c);
}
Insertion Sort
Insertion Sort in c++
#include < iostream.h >
#include < conio.h >
void sort(int * a) {
for (int j = 2; j < 10; j++) {
for (int k = 0; k < j; k++) {
if (a[j] < a[k]) {
int temp = a[k];
a[k] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < 10; i++) {
cout << a[i] << "\n";
}
}
void main() {
clrscr();
int a[] = {
1, 4, 6, 8, 0, 9, 7, 5, 2, 3};
sort(a);
}
Insertion Sort in c++
Bucket Sort
#include <iostream.h>
class element //element
{
public:
int value;
element *next;
element()
{
value=NULL;
next=NULL;
}
};
class bucket //bucket containing a perticular range of values
{
public:
element *firstElement;
bucket()
{
firstElement = NULL;
}
};
void main()
{
int lowend=0; // minimum element
int highend=100; //max element
int interval=10; //number of intervals
const int noBuckets=(highend-lowend)/interval; //number of buckets required
bucket *buckets=new bucket[noBuckets];
bucket *temp;
for(int a=0;a<noBuckets;a++) //creation of required buckets
{
temp=new bucket;
buckets[a]=*temp;
}
cout<<"--------The Elements to be Sorted using Bucket sort are ------------------\n";
int array[]={12,2,22,33,44,55,66,77,85,87,81,83,89,82,88,86,84,88,99};
for(int j=0;j<19;j++) //sending elments into appropriate buckets
{
cout<<array[j]<<endl;
element *temp,*pre;
temp=buckets[array[j]/interval].firstElement;
if(temp==NULL)//if it is the first element of the bucket
{
temp=new element;
buckets[array[j]/interval].firstElement=temp;
temp->value=array[j];
}
else
{
pre=NULL;
while(temp!=NULL) //move till the appropriate position in the bucket
{
if(temp->value>array[j])
break;
pre=temp;
temp=temp->next;
}
if(temp->value>array[j]) //if the new value is in betwen or at the begining
{
if(pre==NULL) //insertion at first if the bucket has elements already
{
element *firstNode;
firstNode=new element();
firstNode->value=array[j];
firstNode->next=temp;
buckets[array[j]/interval].firstElement=firstNode;
}
else //insertion at middle
{
element *firstNode;
firstNode=new element();
firstNode->value=array[j];
firstNode->next=temp;
pre->next=firstNode;
}
}
else// if the new value is to be created at last of bucket
{
temp=new element;
pre->next=temp;
temp->value=array[j];
}
}
}
cout<<"------------------The Sorted Elements Are-----------\n";
for(int jk=0;jk<10;jk++)
{
element *temp;
temp= buckets[jk].firstElement;
while(temp!=NULL)
{
cout<<"*"<<temp->value<<endl;
temp=temp->next;
}
}
cout<<"--------------------------------END------------------\n";
}
Bucket Sort program in C++
Bubble Sort
#include <stdio.h>
#include <iostream.h>
void bubbleSort(int *array,int length)//Bubble sort function
{
int i,j;
for(i=0;i<10;i++)
{
for(j=0;j<i;j++)
{
if(array[i]>array[j])
{
int temp=array[i]; //swap
array[i]=array[j];
array[j]=temp;
}
}
}
}
void printElements(int *array,int length) //print array elements
{
int i=0;
for(i=0;i<10;i++)
cout<<array[i]<<endl;
}
void main()
{
int a[]={9,6,5,23,2,6,2,7,1,8}; // array to sort
bubbleSort(a,10); //call to bubble sort
printElements(a,10); // print elements
}
Inode and Linux file system
DISK TYPES
- IDE
- /dev/hda
- /dev/hdb
- ……
- SCSI
- /dev/sda
- /dev/sdb
Linux Partition
| Boot block | Super Block | I node table | Data Block |
Boot Block : has information to boot
Super Block: has all summary of the parition
- has list of free inode numbers
- has list of blocks
- a copy of super block is put in ram is called super surrogagate block. this is periodically updated this is called sync, this happens during shutdown.
Inode : all properties of files are stored {except this everything else is present in INODE file number,name,data}
Inode table is list of Inodes
Inode looks like this
| Type |
| permissions |
| uid/gid |
| timestamp |
| links Count--->when more than file names which refer to the inode then this is incremented. |
| size |
| Pointer to the disk Block |
Data Block: is the place where actual data is stored.[Data Block Pointers]
| PTR 1 |
| PTR 2 |
| PTR 11 – > pointer to a list of pointers |
| PTR 12 – > double indirection |
Hard Links:
has the same i-node number with different file name
when original file is deleted the link file is still present until the hard link count is 0
ln <target name> <link name>
ln <targets> <dest dir>
hard links are not allowed for directories
Every time a directory is created it has 2 hard links the path and the [.]
and when a sub dir is created the .. becomes another link
Soft Links:
the size of the file is the path length.
when the original file is deleted this symbolic link becomes invalid.
permission of symbolic link is 777 which is of no use.
when user tries to change permission on soft link it might affect the original file.
same as hard link except that you need to give an option –s
soft links are allowed for directories
Check Inode number:
[trainee@localhost purna]$ ls -li
total 1
Inode number---------hardlink count
3702945 drwxrwxr-x 2 trainee trainee 4096 Jun 14 15:03 file1
Linux File Permissions
| Text | Binary | Directory | |
| Read | cat <file> | cp /bin/ls | ls |
| Write | cat > <file> | cc a.c | rm <directory> |
| eXecute | ./<file> | ls | cd <directory> |
Only 2 users can change the permissions of a file
- the Owner
- super user or root
ls -l
Owner-Group-Others HardLinks username groupName bytes date filename
drwxrwxr-x 2 trainee trainee 4096 Jun 14 15:03 as
-rw-rw-r-- 1 trainee trainee 0 Jun 14 14:27 f2
-rw-rw-r-- 1 trainee trainee 148 Jun 14 14:28 f3
-rw-rw-r-- 1 trainee trainee 148 Jun 14 14:28 f4
-rw-rw-r-- 1 trainee trainee 888 Jun 14 14:29 f5
-rw-rw-r-- 1 trainee trainee 0 Jun 14 15:10 fruits
-rw-rw-r-- 1 trainee trainee 0 Jun 14 15:10 g1
-rw-rw-r-- 1 trainee trainee 0 Jun 14 15:10 g2
Change permissions on a file
- Numerical: use chmod 777 filename all permissions to a file.
- Symbolic: use chmod a+x,g-w <filename> [User Group] [+/-] [r/w/x]
UMASK:
- specifies what has to be denied
- its only for newly created files
you can find out umask by typing umask
[trainee@localhost purna]$ umask
0002 the last three specify what permission to deny to the owner group and others
Linux Files and Directories
input----> Command ----> Output
input redirection <
output redirection >
cat f1 > f2
to concatenate
to display file contents
copy files
cat without any arguments ….takes from the terminal and writes to the terminal so reads from keyboard and displays on screen this will be infinite loop .
cat f1 >> f2 [APPEND]
Less:
read from standard input and show page by page on standard output.
Touch:
- is a easy way to create a file which does not exist
- if it exists its access time is updated unlike cat it does not display
ls- lists the files/directories in a directory
- color has a meaning which can be found out using –color option.
- files starting with [.]DOT are hidden files.
/[Slash]- Root directory
dev: all devices
lib: library's for every one.
lost+found: specific to redhat recovered files
Misc: miscellaneous.
proc: mapping to memory.
tmp : temporary files
var : variety of log files
bin: binaries of commands like ls mkdir etc.
boot: boot loader files, kernel etc
sbin: system binaries
mnt: any mountable devices like cdrom pendrive are mounted under this.
./ : current working directory
.. : parent directory
~ : Home directory (available only in few shells)
PWD : print working directory
CD: change directory, cd without any arguments takes to the home directory
to go to home u can use cd $HOME , cd ~ or just cd.
mkdir: <dir name …..>make a directory, on success does not give any message ,, instead u can use –V for verbose.
mkdir –p make parents as necessary.
rmdir <dir name ….> removes the specific dir
ls *: all the files
ls f?: list files which start with f and have one more leter.
ls f[1234]/ls f[1-4]: f followed by one of 1-4
Note for copy and move
- Use option -i to make it interactive along with v so that you have a say whether you have to overwrite or not .
- use -r to move or copy recursively.
- use –v to make it verbose.
- -f to make it silent.
- -b to take a back up before overwrite as we have bvf option is safest.
Copy:
cp <source file> <dest file>
cp <source files…….> <dest file>
Move:
mv <source file> <dest file>
mv <source files…….> <dest file>
Delete:
rm: removes files completely very hard to recover.
rm –rf ~ [ most dangerous command ]
Linux Notes Part 1
root@v11geonode2> cat /etc/passwd
root:x:0:0:Super-User:/root:/sbin/sh
daemon:x:1:1::/:
bin:x:2:2::/usr/bin:
USERNAME : PASSWORD:USERID:GROUPID
the password encrypted is stored at /etc/shadow
vin:$1$3vD2BLH4$ZEFSMbnDYrJ4YGEqzKDR0/:14734:7:91:7:::
user2:$1$19HkQt88$DBFe7VgQpGdd7osh9Oe8m1:14735:7:91:7:::
vin1:$1$0YwoL0i8$/Jg7ZnPs50lxlSax3Nc5C0:14742:7:91:7:::
logout
- logout
- exit
- control D
Shutdown
- halt : shut down and halt.
- Init 0/6 : run level 0 is halt and 6 is reboot.
- shutdown –r/h h=halt r=reboot
- poweroff
- reboot
- restart
Shells
- bourne shell sh
- csh-c shell csh
- ksh-korn shell(is the most powerfull shell) ksh
- bash bourne again. bash
| COMMAND | OPTIONS | ARGUEMENTS |
| internal/external | character or string | optional |
Who Am I [aka who –m] : tells who the logged in user is
root@v11geonode2> who am i
root pts/2 Jun 14 12:18 (10.142.208.146)
user terminal Login Time IP-Address
actually who with any two options will return the same
you can actually type who mom likes / who dad likes tooo
WHO : all the users
root@v11geonode2> who
rtp99 pts/1 Jun 14 11:16 (10.142.216.148)
root pts/3 Jun 14 12:20 (10.142.216.164)
root pts/4 Jun 14 12:27 (10.142.216.158)
root pts/7 Jun 14 10:34 (10.142.216.158)
-U gives idle time
id
[trainee@localhost /]$ id
uid=500(trainee) gid=500(trainee) groups=500(trainee) context=user_u:system_r:unconfined_t
[trainee@localhost /]$ id -u
500
[trainee@localhost /]$ id -g
500
[trainee@localhost /]$ id -G
500
[trainee@localhost /]$ id -nu
trainee
[trainee@localhost /]$ id -ng
trainee
[trainee@localhost /]$ id -nG
trainee
about Us
root@v11geonode2> logname
root
root@v11geonode2> tty
/dev/pts/2
Hardware Information
[trainee@localhost /]$ uname -s
Linux
[trainee@localhost /]$ uname -o
GNU/Linux
[trainee@localhost /]$ uname -p
i686
[trainee@localhost /]$ uname -m
i686
[trainee@localhost /]$ uname -n
localhost.localdomain
[trainee@localhost /]$ uname -r
2.6.18-8.el5
[trainee@localhost /]$ uname -v
#1 SMP Fri Jan 26 14:15:21 EST 2007
[trainee@localhost /]$ uname -a
Linux localhost.localdomain 2.6.18-8.el5 #1 SMP Fri Jan 26 14:15:21 EST 2007 i686 i686 i386 GNU/Linux
Date
Mon Jun 14 13:03:43 IST 2010
Changing password
root@v11geonode2> passwd
passwd: Changing password for root
New Password:
root can set some stupid and simple passwords.
Calculator(powerful but not user friendly)
[trainee@localhost /]$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
2+3
5
x=2
y=3
z=x+y
print z
5
quit
Linux has 10k commands so …learn to use the manual[Manual pages]
man [Command]
- man kill
- man -k kill : lists all the sections where the command is there.[trainee@localhost /]$ man -k kill
kill (1p) - terminate or signal processes
kill (1) - terminate a process
kill (2) - send signal to a process - man 2 kill where 2 is the section ie the one in the bold above
info
more user friendly help
it has hyper links in the form of *[Star]
--help
only few commands support this , brief explanation
whatis kill
lists the sections
XML pretty-printing in Java
When the xmlStr is printed using Java streams, it prints in a single line sans formatting and indentation.
To get it ‘pretty-printed’, javax XML API library can be used.
Source xmlInput = new StreamSource(new StringReader(xml));
StreamResult xmlOutput = new StreamResult(new StringWriter());
Transformer transformer = TransformerFactory.newInstance().newTransformer();
//transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
xml=xmlOutput.getWriter().toString();
System.out.println("THE RESULT XML "+xml);
MD5 Encryption
public static byte[] getEncrypted(String passwd) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] pwd = passwd.getBytes();
md.update(pwd);
byte[] mdpwd = md.digest();
return mdpwd;
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}