Thursday 29 December 2011

QuickBits-12: Bash Shortcuts for Geeks

 

These are some of the shortcuts that i use ...

Command Editing Shortcuts

  • Ctrl + a – go to the start of the command line
  • Ctrl + e – go to the end of the command line
  • Ctrl + k – delete from cursor to the end of the command line
  • Ctrl + u – delete from cursor to the start of the command line
  • Alt + d – delete to end of word starting at cursor (whole word if cursor is at the beginning of word)
  •  Ctrl + w – delete from cursor to start of word (i.e. delete backwards one word)

 

Command Recall Shortcuts

  • Ctrl + r – search the history backwards
  • Ctrl + g – escape from history searching mode
  • Ctrl + p – previous command in history (i.e. walk back through the command history)
  • Ctrl + n – next command in history (i.e. walk forward through the command history)
  • Alt + . – use the last word of the previous command
  • Ctrl + o -  This command is my favourite. If you hit CTRL+o after picking a command from your history, the command is executed, and the next command from history is prepared on the prompt.
  •  

Command Control Shortcuts [Not a Bash Feature]

  • Ctrl + l – clear the screen
  • Ctrl + s – stops the output to the screen (for long running verbose command)
  • Ctrl + q – allow output to the screen (if previously stopped using command above)
  • Ctrl + c – terminate the command
  • Ctrl + z – suspend/stop the command
  •  

Bash Bang (!) Commands

  • !! - run last command
  • !blah – run the most recent command that starts with ‘blah’ (e.g. !ls)
  • !$ – the last word of the previous command (same as Alt + .)
  • !* – all of the previous command except for the first word (e.g. if you type ‘ls foo foo/bar foo/bar/foo‘, then !* would give you ‘foo foo/bar foo/bar/foo‘)
  • ^^ - If you type a command and run it, you can re-run the same command but substitute a piece of text for another piece of text using ^^ (e.g.: if you run 'ls this/is/cool/stuff' and if you do '^cool^geek' then it will run 'ls this/is/geek/stuff'. It replaces only the first occurance)
  • !!:gs/search/replace/ - It is same as previous except it replaces all occurance

 Tricks with ~/.inputrc

  • Put this in your ~/.inputrc
"\e[A": history-search-backward
"\e[B": history-search-forward
"\C-p": history-search-backward
"\C-n": history-search-forward

Type something, then pressing Ctrl-p(or Ctrl-n) will initiate the search in the history with the already typed text as prefix
  •  

Monday 21 November 2011

QuickBits-11: Giving User Input to cmd through file

Lots of user developed commands requires user input for "if you want to continue ... [y/n]" . If you want to automate this

For example: If mycommand requires user input saying 'y' then add 'y' to the arguments.txt file.


cat arguments.txt - | mycommand


Now your mycommand will not ask for user input. It takes it from the file arguments.txt

Saturday 19 November 2011

QuickBits-10: Highlight a word in Emacs buffer

If you have used Source Insight for code browsing, you would have used its word hightlight feature.You can highlight the word under cursor, in your file you are browsing using shift+f8.

You can do the same in Emacs, by adding this to your .emacs file


 
(defun is-word-highlighted ()
  (interactive)
  (let ((face (or (get-char-property (point) 'read-face-name)
                  (get-char-property (point) 'face))))
   (if (facep face) (if (face-equal face "hi-yellow") t nil) nil)))

(defun toggle-highlight-word ()
(interactive)
(setq sym (current-word))
(if (is-word-highlighted) (unhighlight-regexp sym) (highlight-regexp sym)) 
)

(global-set-key [S-f8] 'toggle-highlight-word)

Sunday 11 September 2011

QuickBits-9: Search String in files

1. To search for a string/regular expression in all files in a folder
grep -H "string" * 
This will print the matching line.
-H is for printing the matching filename.

2. To search for a string/regular expression in all files in a folder + subfolders
grep -H "string" * -r

3. To search for a string in all files of certain type
find . -name "pattern" -exec grep -H "string" {} \;


grep -H "string" $(find . -name "pattern")
Example: To find string "main" in all .c file
find . -name "*.c" -exec grep -H "main" {} \;


grep -H "main" $(find . -name "*.c")






Sunday 4 September 2011

QuickBits-8: Remove Duplicate Lines in a File

To Remove duplicate lines in a file and print it
 cat filename | sort | uniq  

sort will sort the lines and
uniq will remove adjacent duplicate lines.

To count the number of repetition of each line
 cat filename | sort | uniq -c

Sunday 28 August 2011

QuickBits-7: Convert .a file to .so file

.a files are just archive of .o object files. You need to just extract the files from the archive and package them as a shared object (.so).

ar -x myarchive.a


gcc -shared -Wl,-soname,mysharedlib.so *.o -o mysharedlib.so

Sunday 21 August 2011

QuickBits-6: Search and Kill Process

Many a times we need to find a process and kill it. The best way to Find a process is

Search
 pgrep -l [pattern] 

-l will list the name of the process or else only pid will be displayed. pgrep searches for the match in any part of the name including the arguments to the command.

Example:
 pgrep -l work


output
217 kworker/u:3
218 kworker/u:4
219 kworker/u:5
863 NetworkManager
900 ./a.out work

Search & Destroy
 pkill [pattern]

It will find and kill all the process that matches the Pattern.


Sunday 14 August 2011

QuickBits-5: Searching for previous commands

How to search and run the same command in bash ?

1. Up / down arrow keys [ good for previous few commands ]

2. Type ctrl+r and type any part of the command including its arguments. Bash will find and run it for you. Keep pressing ctrl+r until u find the right command.

Say you have run the following command sometime back

cd /myfolder/personal/secret/

you can search by typing ctrl+r and typing secret. Bash will find this command for you.

Thursday 7 July 2011

QuickBits-4: sshfs

If you have ssh access to another PC and you want to access the folder of that PC the best way is to ssh mount that.
 sshfs username@hostname:/folder /mountfolder 


With this command the the /folder on the ssh host is mounted locally to /mountfolder. And you can access it as local folder.

To unmount the mounted folder

 fusermount -u /mountfolder 

Friday 1 July 2011

QuickBits-3: Vim diff

Most often when you are working in shell you want to find diff between two files and merge them. vimdiff is very good utility.

 vim -d file1 file2 




Keyboard Shortcuts:



ctrl+w ctrl+w - switch windows
do - diff obtain
dp - diff put
[c - previous difference
]c - next difference
:diffupdate - diff update ;)
:syntax off - syntax off
zo - open folded text
zc - close folded text



Tuesday 7 June 2011

A Boolean Array Puzzle

Input: A array arr[] of two elements having value 0 and 1

Output: Make both elements 0.

Specifications: Following are the specifications to follow.
1) It is guaranteed that one element is 0 but we do not know its position.
2) We can’t say about another element it can be 0 or 1.
3) We can only complement array elements, no other operation like and, or, multi, division, …. etc.
4) We can’t use if, else and loop constructs.
5) Obviously, we can’t directly assign 0 to array elements.




void changeToZero(int a[2])
{
a[ a[1] ] = a[ !a[1] ];
}

int main()
{
int a[] = {1, 0};
changeToZero(a);

printf("arr[0] = %d \n", a[0]);
printf("arr[1] = %d ", a[1]);
getchar();
return 0;
}


Monday 23 May 2011

QuickBits-2: Convert flv to mp4

I had lot of flv video files and wanted to convert it to mp4 for my itouch. Here is the quick way. -f is to force the format to mp4.

$ ffmpeg -i file.flv -f mp4 file.mp4

If you have to convert all files in a folder. Here is the small script. It will convert all flv files to mp4 with the same name with extenstion to mp4.

for file in *.flv
do
ffmpeg -i "$file" -f mp4 "${file%.flv}.mp4
done



QuickBits-1: !$

some times u want to take argument from the previous command you gave

say for example

$ ls /user/ramz/dir1/dir2/dir3/

Now you want to cd to the directory you used in ls command. The quick way is

$ cd !$

- This is equivalent to cd /user/ramz/dir1/dir2/dir3
- !$ - Takes the last argument of previous command.


Wednesday 18 May 2011

Segregate even and odd nodes in a Linked List

Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers same.

Examples:
Input: 17->15->8->12->10->5->4->1->7->6->NULL
Output: 8->12->10->4->6->17->15->5->1->7->NULL

Input: 8->12->10->5->4->1->6->NULL
Output: 8->12->10->4->6->5->1->NULL

// If all numbers are even then do not change the list
Input: 8->12->10->NULL
Output: 8->12->10->NULL

// If all numbers are odd then do not change the list
Input: 1->3->5->7->NULL
Output: 1->3->5->7->NULL





#include "linkedlist.h"
#include

NODE* createLL(int maxNode)
{
int index;
NODE* headNode=NULL;

for (index = 0; index <= maxNode; index++)
{
headNode = addAtHead(headNode, rand()%100);
}
return headNode;
}

NODE* segregateEvenOdd(NODE* headNode)
{
NODE* currentNode = headNode;
NODE* lastNode = headNode;
NODE* previousNode = NULL;
int length = 0;

/* Find lastNode and length */
while(currentNode != NULL)
{
lastNode = currentNode;
currentNode = currentNode->next;
length++;
}

currentNode = headNode;
while(length)
{
/* push OddNumber node to last */
if (currentNode->data % 2 == 1)
{
if (headNode != currentNode)
{
previousNode->next = currentNode->next;
lastNode->next = currentNode;
lastNode = currentNode;
currentNode->next = NULL;
currentNode = previousNode->next;
}
else
{
lastNode->next = headNode;
lastNode = headNode;
headNode = headNode->next;
currentNode->next = NULL;
currentNode = headNode;
}
}
else
{
previousNode = currentNode;
currentNode = currentNode->next;
}
length--;
}

return headNode;
}

/* Driver program */
int main()
{
NODE* headNode=createLL(10);

printList(headNode);

headNode = segregateEvenOdd(headNode);

printList(headNode);
}



Tuesday 17 May 2011

Write a C program to remove duplicates from a sorted linked list.


#include
#include "linkedlist.h"

#define LL_LIMIT 6
#define LL_DUP1 4

NODE* createLL()
{
int index=LL_LIMIT;
NODE* headNode = NULL;
while(index > 0)
{
headNode = addAtHead(headNode, index);
if (index == LL_DUP1)
{
headNode = addAtHead(headNode, index);
}
index--;
}
return headNode;
}

int removeDupNode(NODE* headNode)
{
NODE* dupNode;
if (headNode == NULL)
{
printf("List is Empty\n");
return 1;
}

while(headNode->next != NULL)
{
if(headNode->data == headNode->next->data)
{
printf("Duplicate data is %d\n", headNode->next->data);
dupNode = headNode->next;
headNode->next = dupNode->next;
free(dupNode);
}
headNode = headNode->next;
}
return 0;
}

int main()
{
NODE* headNode = NULL;

headNode = createLL();

displayAll(headNode);

if(!removeDupNode(headNode))
{
displayAll(headNode);
}
}

Find Middle of Linked List


#include
#include "linkedlist.h"

#define LL_LIMIT 6
int main()
{
int midData;
int index=LL_LIMIT;
NODE* headNode=NULL;
NODE* oneStepPtr=NULL;
NODE* twoStepPtr=NULL;

/* Create LL*/
while(index > 0)
{
headNode = addAtHead(headNode, index);
index--;
}

/* Display LL*/
displayAll(headNode);

oneStepPtr = headNode;
twoStepPtr = headNode;

/* Increment step pointers till the end */
while(twoStepPtr != NULL &&
twoStepPtr->next != NULL &&
twoStepPtr->next->next != NULL)
{
oneStepPtr = oneStepPtr->next;
twoStepPtr = twoStepPtr->next->next;
}
midData = oneStepPtr->data;

printf("Middle of LL contains %d\n", midData);
return 0;
}

Monday 16 May 2011

Find the Loop in the linked list and remove the loop from it



int detectLoop(NODE* headNode)
{
NODE* oneStepPtr = headNode;
NODE* twoStepPtr = headNode;
int isLoop = 0;

while(twoStepPtr != NULL
&& twoStepPtr->next != NULL
)
{
oneStepPtr = oneStepPtr->next;
twoStepPtr = twoStepPtr->next->next;

if (twoStepPtr == oneStepPtr)
{
isLoop = 1;
break;
}
}
return isLoop;
}

/* Call only when loop exists */
void removeLoop(NODE* headNode)
{
/* find Loop Node */
NODE* oneStepPtr = headNode;
NODE* twoStepPtr = headNode;
NODE* loopNode = headNode;

while(twoStepPtr != NULL
&& twoStepPtr->next != NULL
)
{
oneStepPtr = oneStepPtr->next;
twoStepPtr = twoStepPtr->next->next;

if (twoStepPtr == oneStepPtr)
{
loopNode = oneStepPtr;
break;
}
}


/* Find loopLength */
NODE* currentNode = loopNode;
int loopLength = 0;
while (currentNode != loopNode
|| loopLength == 0)
{
loopLength++;
currentNode = currentNode->next;
}


/* Offset headNode by loopLength */
currentNode = headNode;
NODE* offSetNode = NULL;
NODE* tailNode = NULL;
int offSetLength = 0;

while(offSetLength < loopLength) { tailNode = currentNode; currentNode = currentNode->next;
offSetLength++;
}
offSetNode = currentNode;


/* find tailNode, when currentNode and offSetNode meets, but one */
currentNode = headNode;
while(offSetNode != currentNode)
{
tailNode = offSetNode;
offSetNode = offSetNode->next;
currentNode = currentNode->next;
}

tailNode->next = NULL;
}

Write a recursive approach to reverse a link list.


void recursiveReverse(NODE** headNode)
{
NODE* firstNode;
NODE* restOfNodes;

if(headNode == NULL)
{
printf("List is Empty\n");
return;
}

firstNode = *headNode;
restOfNodes = firstNode->next;

if (restOfNodes == NULL)
{
return;
}

recursiveReverse(&restOfNodes);

firstNode->next->next = firstNode;
firstNode->next = NULL;

*headNode = restOfNodes;
}

Saturday 14 May 2011

Write a program to return the nth node from the end of a linked list.


#include "linkedlist.h"
#include

#define LL_LIMIT 10

/* Create LL */
NODE* createLL()
{
int index=0;
NODE* headNode = NULL;
while(index <= LL_LIMIT)
{
headNode = addAtHead(headNode, ++index);
}
return headNode;
}

/* get Nth Node from Last */
int getNthNodeLast(NODE* headNode, int nodeNum)
{
NODE* currentNode1 = headNode;
NODE* currentNode2 = headNode;
int count = 0;

while(currentNode1 != NULL)
{
count++;
currentNode1 = currentNode1->next;
if(count > nodeNum)
{
currentNode2 = currentNode2->next;
}
}

return currentNode2->data;
}

/* Driver program to test above functions */
int main()
{
NODE* headNode = NULL;
headNode = createLL();

displayAll(headNode);
printf("3rd Node is %d\n", getNthNodeLast(headNode, 3));
}

Thursday 12 May 2011

Write a C program to remove duplicates from a sorted linked list.


#include
#include "linkedlist.h"

#define LL_LIMIT 6
#define LL_DUP1 4

NODE* createLL()
{
int index=LL_LIMIT;
NODE* headNode = NULL;
while(index > 0)
{
headNode = addAtHead(headNode, index);
if (index == LL_DUP1)
{
headNode = addAtHead(headNode, index);
}
index--;
}
return headNode;
}

int removeDupNode(NODE* headNode)
{
NODE* dupNode;
if (headNode == NULL)
{
printf("List is Empty\n");
return 1;
}

while(headNode->next != NULL)
{
if(headNode->data == headNode->next->data)
{
printf("Duplicate data is %d\n", headNode->next->data);
dupNode = headNode->next;
headNode->next = dupNode->next;
free(dupNode);
}
headNode = headNode->next;
}
return 0;
}

int main()
{
NODE* headNode = NULL;

headNode = createLL();

displayAll(headNode);

if(!removeDupNode(headNode))
{
displayAll(headNode);
}
}

Find Middle of Linked List


#include
#include "linkedlist.h"

#define LL_LIMIT 6
int main()
{
int midData;
int index=LL_LIMIT;
NODE* headNode=NULL;
NODE* oneStepPtr=NULL;
NODE* twoStepPtr=NULL;

/* Create LL*/
while(index > 0)
{
headNode = addAtHead(headNode, index);
index--;
}

/* Display LL*/
displayAll(headNode);

oneStepPtr = headNode;
twoStepPtr = headNode;

/* Increment step pointers till the end */
while(twoStepPtr != NULL &&
twoStepPtr->next != NULL &&
twoStepPtr->next->next != NULL)
{
oneStepPtr = oneStepPtr->next;
twoStepPtr = twoStepPtr->next->next;
}
midData = oneStepPtr->data;

printf("Middle of LL contains %d\n", midData);
return 0;
}

Thursday 5 May 2011

Stack using One Queue

Implement a stack using a queue. The operations need not be neccesarily O(1).


#include "queueimplll.h"

typedef struct queue QUEUE;
typedef struct queue_node QUEUE_NODE;

int queuepush( QUEUE *q1, int val)
{

/* In an empty Q, push the val straight*/
if (q1->first == 0 &&
q1->last == 0)
{
enqueue( q1, val);
return 0;
}

/* enQ val*/
if (enqueue(q1, val))
{
printf("ERROR: enqueue q2\n");
}


/* deQ, enQ by 1 short of QLength*/
int first_value;
int qlength = queue_length(q1) - 1;
while(qlength--)
{
dequeue(q1, &first_value);
enqueue(q1, first_value);
}

return 0;
}

/*Driver Program*/
int main()
{
QUEUE queue1;
int index;

init_queue(&queue1);

for (index = 10; index <= 100; index += 10)
{
queuepush( &queue1, index);
}

int value = 0;
index = 0;
while (!queue_empty_p(&queue1))
{
dequeue( &queue1, &value);
printf("%d : %d\n", index++, value);
}
}

Stack using two queues

Implement a stack using two queues. The operations need not be neccesarily O(1).





#include stdio.h
#include "queueimplll.h"

typedef struct queue QUEUE;
typedef struct queue_node QUEUE_NODE;

int queuepush( QUEUE *q1, QUEUE *q2, int val)
{

/* If first queue is empty, enqueue val straight away*/
if (q1->first == 0 &&
q1->last == 0)
{
enqueue( q1, val);
return 0;
}

/* Enqueue val into second queue*/
if (enqueue(q2, val))
{
printf("ERROR: enqueue q2\n");
}

/* Move (deQ, enQ) from q1 to q2 */
int first_value;
while (!queue_empty_p(q1))
{
dequeue(q1, &first_value);
enqueue(q2, first_value);
}

/* Move (deQ, enQ) from q2 to q1*/
while (!queue_empty_p(q2))
{
dequeue(q2, &first_value);
enqueue(q1, first_value);
}
/* q1 is ready to be poped up*/

queue_empty_p(q2);
return 0;
}

/* Driver program */
int main()
{
QUEUE queue1, queue2;
int index;

init_queue(&queue1);
init_queue(&queue2);

/* Push into queue1 */
srand(time(NULL));
for (index = 0; index <= 100; index++)
{
queuepush( &queue1, &queue2, (rand() % 100) + 1);
}

/* Pop from queue1*/
int value = 0;
index = 0;
while (!queue_empty_p(&queue1))
{
dequeue( &queue1, &value);
printf("%d : %d\n", index++, value);
}
}



Tuesday 3 May 2011

Queue with two stacks

Implement a queue using two stacks. The operations need not be neccesarily O(1).





/* Include Stack Implementation (using Array)*/
#include "stackimplarray.h"

void queuepush(STACK* st1, STACK* st2, int val)
{
/* If first stack is empty, push the value straight down */
if (st1->size == 0)
{
st1->items[st1->size++] = val;
return;
}

/* Pop all elements of first stack
and push it into second stack */
while(st1->size != 0)
{
push(st2, pop(st1));
}

/* Push value onto second stack */
push(st2, val);

/* Pop all elements of second stack
and push it into first stack */
while(st2->size != 0)
{
push(st1, pop(st2));
}
}


/* Driver code to test above functions*/
int main()
{
STACK stack1, stack2;
int i;
for(i=1; i<=10; i++)
{
queuepush(&stack1, &stack2, i * 100);
}

while(stack1.size != 0)
{
printf("%d\n", pop(&stack1));
}
}



Saturday 30 April 2011

Controlling Rhythmbox/banshee from shell

In Linux all the music player like Banshee / Rhythmbox music player has a dbus interface which provides us a means to control them from commandline like pause, play, next, previous, increase/decrease volume.

I wrote few alias to do so ...

Rhythmbox

alias pauseplay='dbus-send --dest=org.gnome.Rhythmbox /org/gnome/Rhythmbox/Player org.gnome.Rhythmbox.Player.playPause boolean:true'

alias next='dbus-send --dest=org.gnome.Rhythmbox /org/gnome/Rhythmbox/Player org.gnome.Rhythmbox.Player.next'

alias prev='dbus-send --dest=org.gnome.Rhythmbox /org/gnome/Rhythmbox/Player org.gnome.Rhythmbox.Player.previous'

alias incvolume='dbus-send --dest=org.gnome.Rhythmbox /org/gnome/Rhythmbox/Player org.gnome.Rhythmbox.Player.setVolumeRelative double:.1'

alias decvolume='dbus-send --dest=org.gnome.Rhythmbox /org/gnome/Rhythmbox/Player org.gnome.Rhythmbox.Player.setVolumeRelative double:-.1'

Banshee
alias pauseplay='dbus-send --type=method_call --dest=org.bansheeproject.Banshee /org/bansheeproject/Banshee/PlayerEngine org.bansheeproject.Banshee.PlayerEngine.TogglePlaying'

alias next='dbus-send --type=method_call --dest=org.bansheeproject.Banshee /org/bansheeproject/Banshee/PlaybackController org.bansheeproject.Banshee.PlaybackController.Next boolean:false'

alias prev='dbus-send --type=method_call --dest=org.bansheeproject.Banshee /org/bansheeproject/Banshee/PlaybackController org.bansheeproject.Banshee.PlaybackController.Previous boolean:false'



Place these alias in your .bashrc or .bash_aliases file. Now you can control rhythmbox from shell like
pauseplay - play or pause rhythmbox Music player
next - next track
prev - previous track
incvolume - increase volume
decvolume - decrease volume

Change the alias for your convenience ...

Thursday 28 April 2011

Odd or Even number

Given a positive number n print whether the number is Even or Odd without using any conditional and comparison operators.




int main()
{
int number;
char* names[2] = {"Even","Odd"};
printf("Enter a positive number:");
scanf("%d", &number);
printf("\n%d is %s number\n", number, names[number % 2]);
}



Tuesday 26 April 2011

Puzzle 1 : Survivor Problem

Problem Statement : There are 100 people forming a circle and they are numbered from 1 to 100. They decide to kill each other using a sword, in following manner. At any point, person numbered n having a sword kills person numbered n+1 and passes the sword to n+2. This process doesnot stop until at the end only 1 person remains alive. Initially, person numbered 1 has the sword in hand. Calculate the survivor number. What about any general N ?

Solution


For various N, survivor number obtained is given below,





1 -> 12 -> 14 -> 18 -> 1

3 -> 35 -> 3


6 -> 5


7 -> 7



It is apparent from above pattern that when N is power of 2, Survivor is 1. Otherwise we have to add 2 to every number away from power of 2.



Method 1(Using Recursion):

  1. Let Survivor number be 1

  2. Until N is power of 2


    1. Subtract N by 1

    2. Add 2 to Survivor number





int checkPowerOfTwo(int num)
{
return (num && !(num & (num - 1)));
}

int findSurvivor(int totPerson)
{
int result = 1;
while(!checkPowerOfTwo(totPerson)
&& totPerson > 0)
{
findSurvivor(--totPerson);
result += 2;
}
return result;
}

int main (int argc,
char *argv[])
{

int noOfPerson;

// Check number of arguments passed
if (argc != 2)
{
printf( "usage: %s N\n", argv[0] );
printf( "\t where N is number of persons\n", argv[0] );
return 1;
}

noOfPerson = atoi(argv[1]);

if (noOfPerson == 0)
{
printf("Zero is not a valid input\n");
return 2;
}
printf("Survivor is %d\n", findSurvivor(noOfPerson));
return 0;
}




Method 2:

  1. If N is power of 2, return 1

  2. Find next lower power of 2 wrt to N

  3. Find difference between N and result from step 2. Double and add 1





    1. int checkPowerOfTwo(int number)
      {
      return (number && !(number & (number - 1)));
      }

      int findIndexOfMsb(int number)
      {
      int result = 0;
      while (number >>= 1)
      {
      result++;
      }
      return result;
      }
      int findSurvivor(int totPerson)
      {
      if (checkPowerOfTwo(totPerson))
      {
      return 1;
      }
      return (1 + (totPerson - (1 << findIndexOfMsb(totPerson))) * 2);
      }

      int main (int argc,
      char *argv[])
      {

      int noOfPerson;

      // Check number of arguments passed
      if (argc != 2)
      {
      printf( "usage: %s N\n", argv[0] );
      printf( "\t where N is number of persons\n", argv[0] );
      return 1;
      }

      noOfPerson = atoi(argv[1]);

      if (noOfPerson == 0)
      {
      printf("Zero is not a valid input\n");
      return 2;
      }
      printf("Survivor is %d\n", findSurvivor(noOfPerson));
      return 0;
      }



Thursday 21 April 2011

Convert: The Image Conversion Tool

Many times command line tools are so cool and able than a GUI. I got to know about such a command line image conversion tool. It helped me complete my work so fast and efficient than many GUIs.

This tool does not come by default in ubuntu 10.10. You need to install imagemagick.

sudo apt-get install imagemagick

Giving you glimpse of what this amazing tool can do ... This is just a tip of the iceberg. You can do much much more using this ...

  1. Convert an Image from one Format to another (You can give any image format you know)

      $ convert a.jpg b.png

      $ convert a.bmp c.jpg

  2. To convert all files in folder

      $ convert *.jpg -set filename:name '%t' '%[filename:name].png'

  3. To convert all files in a folder and rename it as per your prefix

      $ convert *.jpg mynameprefix.png'

  4. To create a gif animation from the image files you have

      $ convert *.jpg mygif.gif

  5. To add a pause between transition in a gif image

      $ convert *.jpg -delay 100 mygif.gif

  6. To resize an image

      $ convert myimg.jpg -resize 50% myimgsmall.jpg

      $ convert myimg.jpg -resize 120x120 mythumbnail.jpg

        - To resize the image to pixel of 120 x 120 (width x height) image

  7. To add images to a pdf

      $ convert *.jpg photos.pdf

  8. Sometimes the image size will be too big but you can reduce it by reducing the quality(You may not be able to perceive it in computer screen)

      $ convert img.jpg -quality 75 new_img.jpg

      $ convert *.jpg -quality 75 mynameprefix.jpg

        - To convert all the jpg files and rename it to required prefix followed by sequential number

      $ convert *.jpg -quality 75 -set filename:name '%t' '%[filename:name].jpg'
      - To lower the quality without changing their name.

  9. To Add string to your file at a given location (0,0 denotes top left)

      $ convert myimg.jpg -draw 'text 100,200 “MY STRING”' mynewimg.jpg

      $ convert myimg.jpg -pointsize 20 -draw 'scale 1.5,1.5 text 100,200 “MY STRING”' mynewimg.jpg

          - This makes font size 20

      $ convert *.JPG -set filename:name '%t' -pointsize 36 -draw 'text 500,200 "COOL STUFF"' '%[filename:name].JPG'

  10. To make an image black and white

      $ convert myimg.jpg -colorspace gray myblack.jpg

      $ convert myimg.jpg -charcoal 5 myfun.jpg

        - It converts an image to pencil sketch the number indicates the thickness of line


For Further hacks refer to

http://www.imagemagick.org/Usage/