Sunday, March 18, 2012

12 day to day useful Ubuntu commands*

Hi,

These are day to day useful Ubuntu commands. Hope they are of any use in you day to day lives..:).

These commands should be working fine on Ubuntu 10.04, 11.04.

1. To search for a previously typed command:-

Form: history | grep command_name

E.g:- history | grep redis-server

Sample Output:-


 1632  redis-server
 1636  redis-server
 1638  sudo apt-get remove redis-server
 1658  redis-server
 1661  redis-server
 1662  redis-server &
 1872  redis-server
 1873  ps aux|grep redis-server
 1874  redis-server &
 1891  ps aux|grep redis-server
 1913  redis-server &
 1991  redis-server
 1992  redis-server &
 2038  history redis-server | grep
 2039  history | grep redis-server

2. To view particular file permissions of file(s) in a particular directory

Form: ls -l

Sample Output:-


-rwxr-xr-x 1 mohnish mohnish  84461758 2010-12-19 13:22 jdk-6u23-linux-i586.bin
-rwxr-xr-x 1 mohnish mohnish  21388070 2010-12-19 11:17 jre-6u23-linux-i586.bin
-rw-r--r-- 1 mohnish mohnish     86242 2011-02-19 16:19 nautilus-dropbox_0.6.7_i386.deb
-rwxr-xr-x 1 mohnish mohnish 278520832 2010-12-19 09:12 netbeans-6.9.1-ml-linux.sh
-rwxr-xr-x 1 mohnish mohnish  91764736 2011-03-02 23:34 netbeans-6.9.1-ml-ruby-linux.sh
-rw-r--r-- 1 mohnish mohnish  91581668 2011-03-03 06:24 netbeans-6.9.1-ml-ruby-linux.sh.tar.gz
-rw-r--r-- 1 mohnish mohnish   4873383 2011-01-06 21:17 ruby-1.8.7-p330.tar.gz
-rw-r--r-- 1 mohnish mohnish    292302 2011-02-24 07:05 rubygems-1.5.0.tgz

3. To view a running process wrt a particular name

Form: ps aux | grep process_name

A running process could be a running server etc.

E.g. ps aux | grep redis

Sample Output:-


mohnish@mohnish-laptop:~latest$ ps aux | grep redis
mohnish   2897  0.0  0.0  26976  1552 ?        Sl   13:22   0:02 redis-server
mohnish  18342  0.0  0.0   3332   876 pts/4    S+   14:39   0:00 grep --color=auto redis

4. To Kill a process

Form: kill -9 process_id

E.g. : kill -9 2897


5. Present Working Directory(pwd)

Form: pwd

E.g.:- mohnish@mohnish-laptop:~$ pwd
/home/mohnish

6. Use of Ctrl + R to search

Form:- [Keyboard Press] Ctrl + R (Followed by) [ Type the keyword you want to search]

E.g. : Ctrl + R (followed by sc) , returns:- (reverse-i-search)`sc': ./script/server

7. Power Off and Reboot via Terminal

Poweroff:- sudo poweroff

Reboot:- sudo reboot

8. Cache(Searching for a package wrt  Repositories), Install and Remove packages from your terminal

a. Cache


Form:- sudo apt-cache search package_name

E.g. sudo apt-cache search pidgin

Sample Output:-


b. Install

Form:- sudo apt-get install package_name

E.g. sudo apt-get install pidgin-sipe

c. Remove

Form:- sudo apt-get remove package_name

E.g. sudo apt-get remove pidgin-sipe

d. Update

Form/Command: sudo apt-get update

9. Clear Terminal screen shortcut

Scenario: When you terminal is overly crowded with stuff

Command:- Ctrl + L
(This even clears your mysql screen :))

10. Exiting your terminal

Command:- exit

11. Changing your pwd and listing contents in new directory

a. To change directory(cd)

Form:- cd directory_name

b. To list contents of pwd

Form:- ls

Eg. for a. and b.


mohnish@mohnish-laptop:~$ cd sample_pics/
mohnish@mohnish-laptop:~/sample_pics$ ls
16-4-2008-a.jpg  28-10-08-a.jpg  Blue hills.jpg     Desert.jpg      Jellyfish.jpg  kwp-full.jpg    Penguins.jpg  Tulips.jpg       Water lilies.jpg
17-5-2008-a.jpg  8-5-2008-a.jpg  Chrysanthemum.jpg  Hydrangeas.jpg  Koala.jpg      Lighthouse.jpg  Sunset.jpg    Wallpaper-1.jpg  Winter.jpg
mohnish@mohnish-laptop:~/sample_pics$

12. Locking Your Ubuntu Desktop( a functionality similar to Windows + l)

When you are at leisure :), feel free to leave you desktop soon after the below

Command: Alt + Ctrl + l

[A special note: Using tabs to navigate with ease] :-

The use of tab in cd and in other terminal related commands like ls etc., is vital , as it saves you time from typing the entire directory_name/file_name etc., Please find below a sample use of tab while navigating your way inside the contents of a directory you would like to use:-


mohnish@mohnish-laptop:~$ cd m
me/               myforum/          myforum_unzipped/

The above shows up as soon as you press a tab, after you type "m" matching all directories starting with the letter "m".




*CREDITS:

I have learnt few of the above from my seniors at office, apart from other learning experiences. I am grateful to them for the same..

Wednesday, February 15, 2012

Accessing a non model attribute through Rails Active Record Query Interface


Hi,

Imagine this is your scenario:-
You have a model called User. This users table in the back end has more

than 100 records.
I am trying to extract the TOP 30 records , grouping people by the total

number of residents in each area, ordering them in a descending manner. 

The sql query for the same is:- 


    select area, count(area) as total from users group by area order by

total desc limit 30; 


When doing this in Rails, the query looks something like this:- 


    User.select('area, count(area) as total').group('area').order('total

DESC').limit(30)
Rails Active Record Query Interface?
This gives me the areas in descending order, but it doesn't share the

count in terms of number of residents per area. Atleast not a direct outcome of the equivalent Rails command.
Now here come a few road blocks, something that I faced atleast..:)
1. How can we access the count attribute "total" through
2. How can we do 1. along with getting the TOP 30 records ?
3. How can we do 1., 2. and also get the records in the descending order ?
To get the count for each area the below query works, but it doesn't directly support our requirements as of 2 and/or 3.
User.select('area, count(location) as total').group('area').count
The reason behind this is,
a. Profile.select('location, count(location) as total').group('location').order('total DESC').count
b. Profile.select('location, count(location) as total').group('location').order('total DESC').limit(30).count
a. and b. throw errors via Rails console.
I got to know about use of "**to_sql**" from the [active record rails
casts][1] by Ryan Bates. 


  [1]:

http://railscasts.com/episodes/202-active-record-queries-in-rails-3 


When I used the to_sql command in my Rails query, I got:- 


    User.select('area, count(area) as total').group('area').order('total

DESC').limit(30).to_sql 


    SELECT  area, count(area) as total FROM `users` GROUP BY area ORDER

BY total DESC LIMIT 30 


I got the same sql query as above. But somehow since the **count(area)**

is not a direct attribute of the Users model, I was unable to print it

using the above Rails query. 


I'm able to get the count of residents belonging to each area using `User.select('area, count(area) as total').group('area').count`, 
but this is not giving me the areas in descending order. What it returns
is a hash having the area with the count of number of residents in it. I couldn'tfind much from the Rails Guides on this .

Now what worked for me like a charm thanks to inputs from Frederick Cheung(via the following thread - http://www.ruby-forum.com/topic/3073356) was:-

users = User.select('area, count(area) as total').group('area').order('total DESC').limit(30)

users[0].total

This is how through a loop we can access the total number of folks residing in other areas as well.

Hope this helps.

Thanks..:)

Saturday, February 11, 2012

The Drawing Competition at Anatha Shishu Sevashrama - Cognizant CSR



In life, one is not always blessed with opportunities where each one can show case their talent. Such opportunities come, not often. These come by even more scarcely for the less fortunate. The Drawing competition at Anatha Shishu Sevashrama, a home for around 65 orphans, was such an initiative where these children could bring out their hidden talent.



The entire event was something that started as a thought in the mind of Kalyani Sekhar, Sr Director - DAG. At first, it was an event that Kalyani wanted to hold for these children during Children's day, around November last year. Due to some unforseen reasons the event got postponed and was finally held on January 7th, 2012.  Kalyani, was very actively involved in entire planning and execution of this event from the very beginning. Being a POC at this ashram, it was a wonderful opportunity for me also to be involved alongside.


Conducting this event for around 65 children, surely had its bit of planning involved, to make sure everything went well. Children in the ashram were of different age groups from LKG upto 11th std. To start with, we had to figure out how it should be conducted for 60+ children simultaneously. Once the list of the children belonging to different classes was obtained from the ashram, we divided them into junior, middle and senior age groups for the competition. Topics had to be finalized on which these children could draw. It was decided that the senior age group children would draw and paint, whereas the junior and the middle age group children would mainly use pencil colors and crayons for the competition. 

When it came to choosing stationery for the competition and prizes for the children, Kalyani wanted to give them the best they could make use of. My father, was mainly into stationery business, so I suggested we could do well with having him as a vendor to procure the necessary items for this competition. Through this, selection of good quality items was made easier with the vast experience my father in the stationery business. It was also a unique opportunity for me to do a bit of management, execution :), something different from the normal role that I have at office..:).  We brainstormed from the word go, upon the variety of items, quantity and suitable sizes of items to meet requirements of various age groups before placing a final order, this way making sure that nothing is missed out on the day of the competition. Items used for the competiton included drawing sheets, boxes of pencils, sufficient quantities of erasers, sharpeners, color pencils, crayons especially for the use of little ones :), paint colors, palettes, plastic cups used for containing water required while painting, etc.


When it came to choosing prizes, as a token of appreciation of one's exceptional effort, it was decided that these children get rewared with something they could really make good use of. It was agreed upon to give away 3 prizes for each of the 3 age groups of children i.e. junior, middle and senior groups. Upon consulting Saraswathy aunty(the General Secretary and the care taker of the ashram, a lady who has lost her sight of vision) for the same, it was decided to give a variety of stationery items, each forming a set, as a prize to each winner. This could be put to good use in their daily schooling. For the lower age groups especially, Kalyani suggested we could give them drawing and coloring books with lesser number of stationery items as they wouldn't really require too much stationery for their age. Most of the children in the ashram, are currently going to Kannada medium schools and are more fluent in the local language of the city. Probably, keeping this in mind Kalyani also suggested that the lower age groups can be gifted moral story books written in Kannada as part of their prizes. We, somehow managed to get the Kannada books of famous personalities like Mother Teresa, Bhagat Singh etc. to be a part of the prizes for the junior category of students. On a general note, a prize set included note books of various sizes, gel and ball pens, refills, box of color pencils, crayons, stick files (to keep important certificates), highlighter pens etc. The number and the variety of these items was accordingly moderated based on I, II and III prize categories. Based on her experience, Saraswathy aunty also suggested it would be good if consolation prizes could be given away to all the participants. A small notebook, a box of pencils and a ball pen, together gift wrapped as a set was
given to each participant of the competition towards the end.


      Saraswathy Aunty

I still can recall the mailer for this event was sent on Jan 5th, 2012 to Cognizant All BLR DL, and from then on, till 6th Jan EOD there were many volunteers who signed up for this event. Being a POC for this event, I started receiving queries wrt the event from Jan 5th itself..:). Associates wanted to know more details about this event, location specific queries and they also wanted us to confirm their participation . It was a little difficult for me to juggle between work and also answering the queries through IM, mails, vnet calls of the interested participants of this event but some how all went really well..:). It was also fun and exciting to see their enthusiasm to be a part of this altogether.. I am thankful to my team for believing in me that I could balance both work as well as this.

Going by the number of registered volunteers, I was pretty sure that there would be around 15 - 20 volunteers who would have registered for this event. Honestly, I was not sure at that point of time how we could really make best use of these many volunteers at the event, in a way they such that they also feel content with what they can contribute to a noble cause. Although, initially we had in the mailer mentioned we would need around 10 volunteers for this event, Rajesh the POC of Outreach Bangalore suggested that let the volunteers register for this event, even if it exceeds the required number. I just realized at that point, their physical presence in itself at the event has its own value, thereby they can witness the live event and do their bit of participation. Also they say right.., don't worry, things by itself will fall in place.. You just need to have faith.. this is just what happened..:) do read on..:)..

On the day of the event, it was really fulfilling to see a total of 26 volunteers! , who actually made it. It was truly amazing and mind boggling..!:).  We had associates from MBP,GVC,BTP and even a member from the newly acquired CoreLogic Team. One of the associates had also come with his family( his little one, wife and mother in law) for this event. Deepak Prabhu Matti, a member of the Bangalore Outreach Council Board, who has been actively involved with Cognizant Outreach Bangalore initiatives in many ways,  suggested that we could have each volunteer mentor a group of children during the competition. This way all volunteers were actively involved in the entire event.




Some volunteers were enjoying themselves with the little ones who as their age suggests, would generally be upto some or the other mischief..:), drawing and scribbling their way through the competition..:), other volunteers were helping by transferring childrens thoughts on what they had in mind to draw to the actual drawing paper... A truly wonderful bonding seemed to build between these children and the volunteers at that time..:).. Joy was all over at the ashram..:)



After the competition the and just before the prize distribution, Deepak Prabhu Matti, Rajesh had addressed all the volunteers gathered together briefing them about Outreach, Cognizant Foundation(CF) and current Outreach initiatives in Bangalore. This was never planned, it just happened I guess seeing the huge response we had for this event. I also got a chance to speak to the volunteers and share what activities have been previously conducted at this ashram as part of Cognizant Outreach initiatives and show them around the library and the dispensary constructed at the ashram that was donated by CF with Deepak Prabhu Matti being the lead volunteer behind this entire project initiative.




All in all it has truly being an enriching experience for me..:) . It is more fullfilling whenever I get to recall the series of events that lead to this event as a whole through this blog. It was a pleasure to work alongside a richly experienced, highly knowledgable person like Kalyani for this event. I still remember Kalyani's words as the event was drawing its end on that day, "it is really heartening to see these many volunteers". A major highlight of this entire event was, to see these many volunteers at the event, 26 Cognizant volunteers!.


It truly has been a wonderful beginning to 2012..:), sharing our joy with these children and many more in the days to come with support from volunteers, guidance from seniors and also with support from our company Cognizant, in initiatives like these. I humbly take this opportunity to thank each and every one who made this event successful..:)



Friday, January 13, 2012

Scalability in Rails - Exploring Caching



Many of us when talk about Rails, are concerned with scalability of Rails applications.

I got a chance to improve scalability of a particular module in my application through Rails Caching.

Here's how it works in Rails 3.x series:

Rails, basically comes with a inbuilt Caching mechanism which is by default enabled in  production mode.
In each of the Modes of deploying a Rails app, i.e. Dev, Test, Prod we need to make sure caching is enabled in the respective app/environments/mode.rb file
i.e.

app/environments/development.rb
app/environments/test.rb
app/environments/production.rb

The command which will set Caching to true in these environments is:

config.action_controller.perform_caching = true


Now , Say if you are implementing Rails -> Action Caching, In your controller You need to enter:-

caches_action :index, :layout => false

def index
# your code goes in here
end

This means, Rails is going to cache the Index action for you. Of course , with Caching, we need to also consider Expiry of Cache.

What I gotta implement is not a Batch Process which regularly checks for Cache Expiry, but a more efficient approach which is within my controller itself. This way I am saving myself and others who use this code in the future from the overhead of managing and monitoring a batch process time and again.

This is how the Cache Expiry action can look:-

def clear_cache
t = Rails.cache.fetch('variable_used_to_check_expiry_time') || Time.now
t = Time.parse(t) if t.is_a?(String)
expire_action :action => :index if Time.now > t
end

Now, how do I call for clear_cache to check when it is actually time to clear the cache..? Well, this can be done efficiently , automatically using a before_filter method.. Like this..
before_filter => :clear_cache

Rails Cache, comes with a <b>Cache log</b> on which we can specify when the a page was first accessed as a result of the particular Rails action being called.

Now for e.g. if I access the index.html.erb at 20:29 pm, this gets stored in my Rails cache log through the following way:-

def index
# your code goes in here
Rails.cache.write('variable_used_to_check_expiry_time', Time.now + 6.hours)
end I'm setting my cache expiry time to current time  + 6 hrs..i.e. at 04:29am,

Now only if the page => index.html.erb if accessed after 04:29am the following day, the new cache expiry time can be set....

You might be wondering what is written into cache log when the controller method of clear cache is actually called for the first time? Thats a good question..:)

Well basically what happens is, the current time is set into var t, since t = current time, no clear cache action needs to be executed to worry us.

P.S:- Credits to Srikanth Jeeva for inputs on the clear cache approach..

Overcoming RVM Command Not Found Error in Ubuntu 11.04 Server

Hi,

I faced this weird issue of rvm command not being found, inspite of installing it quite a few times.

Please find details wrt the issue:-


I am trying to set up RVM On Ubuntu 11.04 Server.

Making use of a multi user install..

The error I am currently getting is:-

    $  sudo bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer )
    -sh: Syntax error: redirection unexpected
    $

I am not sure whats wrong with the command, as I am using an exact copy of the command from the [RVM installation guide]

Any inputs, could be really helpful..

When I login as root, I am able to atleast run the command and install rvm. But the rvm gives me a command not found.


    root@host:/home/s244574# sudo bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer )
    Downloading RVM from wayneeseguin branch stable
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100  796k  100  796k    0     0   139k      0  0:00:05  0:00:05 --:--:--  261k
 
    Upgrading the RVM installation in /root/.rvm/
    installing - /root/.rvm/man/man1/rvm.1.gz -
    installing - /root/.rvm/man/man1/rvm.1 -
        RVM system user group 'rvm' exists, proceeding with installation.
 
    Upgrade Notes:
 
      * No new notes to display.
 
    # RVM:  Shell scripts enabling management of multiple ruby environments.
    # RTFM: https://rvm.beginrescueend.com/
    # HELP: http://webchat.freenode.net/?channels=rvm (#rvm on irc.freenode.net)
    # Screencast: http://screencasts.org/episodes/how-to-use-rvm
 
    # In case of any issues read output of 'rvm requirements' and/or 'rvm notes'
 
    Upgrade of RVM in /root/.rvm/ is complete.
 
    # root,
    #
    #   Thank you for using RVM!
    #   I sincerely hope that RVM helps to make your life easier and more enjoyable!!!
    #
    # ~Wayne
 
    root@host:/home/s244574# rvm
    No command 'rvm' found, but there are 19 similar ones
    rvm: command not found

Few points to note, wrt what I tried:-

Initially, rvm was installed for me in the path:-

/usr/local/rvm

but somehow rvm command doesn't seem to recognize the path where it is insalled, if I am guessing correctly.

I also tried [install if root only] , the installation path changes(to /root/.rvm/ ) but still I face the same issue.

I have a user, with loginname "user1" is there a way, I can let the user1 identify the rvm path, which has the post installation files, so that the command can be recognized

Thank you..


  [1]: http://beginrescueend.com/rvm/install/
  [2]: http://beginrescueend.com/support/faq/#root


The Fix which did the trick for me:-



source ~/.bash_profile