Monday, December 27, 2010

CTM 3G modem settings in OSX

Just arrived in Macau. Friend passed me his CTM (a mobile service provider I reckoned) 3G dongle to use during my stay. Googled around and found the correct APN + username + password settings.

Telephone Number: *99#
Account Name: guest
Password: guest

Under "Advanced", use

Vendor: Generic
Model: GPRS (GSM/3G)
APN: ctm-mobile

Thursday, December 23, 2010

Diffing tables in Cucumber

Then /^I should see the following within "([^"]*)" area:$/ do |selector, table|
actual_table = tableish("table#{selector} tr", "td,th" ).to_a


Sunday, December 19, 2010

Transition to HTML using HTML5 tags as CSS classes

So instead of

Difference between l10n & i18n

On Wed, Mar 29, 2000 at 11:39:22PM +0200, Antonio Larrosa wrote:
> David Faure wrote:
> >
> > > Hi,
> > >
> > > I just wondered why the directories are called i10n in
> > > kdebase, and what the difference to i18n is....
> >
> > l10n = localization (country-specific settings such as how to represent
> > numbers, dates, money, ...)
> > i18n = internationalization (translations)
> Btw, does anybody knows why are they called with those names ?
> I've been wondering for a long time :-)

Hehe, yes.
Count the number of letters between the starting and the ending
letter, in both words ;-)


Friday, December 17, 2010

Debugging: Show the webpage after a cucumber step

# Example
Scenario: Signing in
When I go to the home page
And I fill in "username" with "john"
And I fill in "password" with "john"
Then show me the page

# Actual implementation
# Uses webrat's method
Then /^show me the page$/ do

Suppress NOTICE messages from Postgresql when running rake cucumber

# Notice messages spewed
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index ...

# Fix
# Add to database config in config/database.yml
min_messages: WARNING;;

Thursday, December 16, 2010

Stop rvm from complaining about world writable /usr/local/bin

# Error message
/Users/velvetpd/.rvm/gems/ruby-1.9.2-p0@babylon/gems/bundler-1.0.7/lib/bundler.rb:199: warning: Insecure world writable dir /usr/local in PATH, mode 040777

# Fix
# This was probably caused by instructions to install Homebrew
chmod o-w /usr/local/bin
chmod o-w /usr/local

Wednesday, December 15, 2010

Git completion for git installed via Homebrew in OSX

# In .bashrc

if [[ -s "/usr/local/Cellar/git/" ]]; then
source "/usr/local/Cellar/git/"

Monday, December 13, 2010

get forward (alt-f) and backward (alt-b) word working in OSX terminal

Under "Preferences > Keyboard" check "Use Option as Meta key"

Installing Nokogiri on CentOS

sudo yum install -y libxml2 libxml2-devel libxslt libxslt-devel
sudo gem install nokogiri

Installing postgresql on CentOS

sudo yum install postgresql postgresql-devel postgresql-server

mkdir /usr/local/pgsql/data
chown postgres /usr/local/pgsql/data

sudo su
su postgres

/usr/bin/initdb -D /usr/local/pgsql/data

createuser OR
psql -c "create role ROLE with superuser"

Installing rvm on CentOS

sudo yum install git
bash < <( curl ) # issue "rvm notes" and follow instructions on dependencies

Sunday, December 12, 2010

Install postgresql using homebrew on OSX

If there's existing postgres install,

brew rm postgresql --force


brew update
brew install postgres

Then follow instructions on printed by homebrew

initdb /usr/local/var/postgres
cp /usr/local/Cellar/postgresql/9.1.4/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/
launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

Installing rvm on OSX

brew install readline
brew install most
sudo gem install rvm #install rvm
rvm install 1.8.7 -C --enable-shared,--with-readline-dir=/usr/local
rvm install 1.9.1 -C --enable-shared,--with-readline-dir=/usr/local
rvm install 1.9.2 -C --enable-shared,--with-readline-dir=/usr/local
rvm 1.8.7 --default


Installing Homebrew on OSX

sudo chown -R $USER:staff /usr/local

curl -Lsf | tar xvz -C/usr/local --strip 1

brew install git

git clone /tmp/homebrew
mv /tmp/homebrew/.git /usr/local/
rm -rf /tmp/homebrew


Difference between staff and wheel groups in OSX

User admin belongs to "staff" group while User root (the only one) belongs "wheel" group.


List groups in osx

more /etc/group

Tuesday, December 7, 2010

Using gnome-mplayer to play embedded mpeg videos in Firefox

sudo apt-get install gnome-mplayer mozilla-mplayer

# Remember right click on the video in Firefox and configure video output to be X11.

Sunday, December 5, 2010

Upgrading my Samsung Galaxy S to Froyo

I went through the ordeal of installing Samsung Kies, their mobile/player manager and getting it to recognize my phone, only to find out that the custom firmware on my phone installed during a visit to Samsung Service Center couldn't offer an upgrade through Kies.

But thanks to the wonderful internet, there're other ways to flash the ROM to the latest and greatest. The links below provide a very clear step by step instructions.

Flashing to Froyo:

Upgrading Kernel for lagfix:

Wednesday, December 1, 2010

Finding source location for a rail method

# Eg. if you want to find source location for DateTime.tomorrow

irb(main):001:0> DateTime.method(:tomorrow).source_location

Friday, November 26, 2010

Network manager in Ubuntu 10.10

Not sure which version of Ubuntu has this been implemented.

# Previously

sudo etc/init.d/NetworkManager stop

# Updated

sudo etc/init.d/network-manager stop

Sunday, November 21, 2010

Enabling bash completion

Uncomment the following in /etc/bash.bashrc

if [ -f /etc/bash_completion ]; then
. /etc/bash_completion

Hijacked keyboard shortcut

Somehow when I upgraded to Ubuntu 10.10, my "Shift + f" launches firefox.

Apparently that keybinding was assigned to run command_1 in metacity which was assigned to launch firefox. To disable it go to,

gconf > apps > metacity > global_keybindings

Saturday, November 20, 2010

Thursday, November 11, 2010

Error messages for Rails 3

# Deprecated

<%= error_messages_for :question %>

# Use partial in app/views/shared

<% if target.errors.any? %>  

<%= pluralize(target.errors.count, "error") %> prohibited this record from being saved:

    <% target.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>
<% end %> # Render partial in view <%= render "shared/error_messages", :target => @question %>

Monday, October 18, 2010

17 Don'ts Of Mobile Application Design Development


... assume a need
... go chasing waterfall
... be short-sighted
... assume browsers are equal
... trivialize choice of platform
... downplay user experience
... gloss over bits & bytes
... be online only
... favour branding over users
... disrupt the experience
... load too much too fast
... squeeze the world in
... re-invent the wheel
... make user type
... do roll-overs
... forget to test
... forget to guide your users


Friday, October 8, 2010

Compressing a PDF file

To compress a PDF file:

Open Preview, in your Applications folder.

Choose File > Open, select the PDF file to compress, and then click Open.

Choose File > Save As, choose Reduce File Size from the Quartz Filter pop-up menu, and choose a name and location for the new PDF file.

Click Save.

Thursday, October 7, 2010

Kill applications using killall in Mac OSX Terminal

# This doesn't kill the processes

killall "Google Chrome"

# Need to append with sudo

sudo killall "Google Chrome"

Monday, September 13, 2010

Sorting searchlogic results

params[:filter][:order] = "ascend_by_created_at"
@search =[:filter])
@notes = @search.all

URL encoding


ASCII Control characters
    Why:These characters are not printable.
Characters:Includes the ISO-8859-1 (ISO-Latin) character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal.)
Non-ASCII characters
    Why:These are by definition not legal in URLs since they are not in the ASCII set.
Characters:Includes the entire "top half" of the ISO-Latin set 80-FF hex (128-255 decimal.)
"Reserved characters"
    Why:URLs use some characters for special use in defining their syntax. When these characters are not used in their special role inside a URL, they need to be encoded.
 Dollar ("$")
 Ampersand ("&")
 Plus ("+")
 Comma (",")
 Forward slash/Virgule ("/")
 Colon (":")
 Semi-colon (";")
 Equals ("=")
 Question mark ("?")
 'At' symbol ("@")
"Unsafe characters"
    Why:Some characters present the possibility of being misunderstood within URLs for various reasons. These characters should also always be encoded.
Why encode?
Space2032Significant sequences of spaces may be lost in some uses (especially multiple spaces)
Quotation marks
'Less Than' symbol ("<")
'Greater Than' symbol (">")
These characters are often used to delimit URLs in plain text.
'Pound' character ("#")2335This is used in URLs to indicate where a fragment identifier (bookmarks/anchors in HTML) begins.
Percent character ("%")2537This is used to URL encode/escape other characters, so it should itself also be encoded.
Misc. characters:
   Left Curly Brace ("{")
   Right Curly Brace ("}")
   Vertical Bar/Pipe ("|")
   Backslash ("\")
   Caret ("^")
   Tilde ("~")
   Left Square Bracket ("[")
   Right Square Bracket ("]")
   Grave Accent ("`")


Some systems can possibly modify these characters.

Random select ruby array elements

[horse, donkey, mule][rand(3)]

Functional test for respond_to :json in Rails

# Notes controller

def index
  respond_to do |format|
    format.json { render :json => @notes }

# Notes functional test

params = {:format => 'json', :title => ...}

get :index, params

notes = JSON.parse(@response.body)
assert_equal note.title, notes[0]['note']['title']

Friday, August 13, 2010

Renaming file extensions in Mac OSX

Downloaded a .zip file and tried renaming it to .apk but OSX keeps recognizing as a zip file...

Apparently Mac tries to be smart in knowing the original file type so to really change the file type, you gotta right click select "Get info" and rename it from there. There'll be a prompt warning you about the type of application associated with the new file extension.

Fix for Samsung Galaxy S terrible lagginess

Fresh out of the box the Samsung Galaxy S sped like a rocket but after a week of usage it began to lag TERRIBLY. Killing apps or rebooting phone doesn't help. Googling the issue reveals its a known bug in the way the phone does I/O with its internal SD card.

Here's a fix by Tayutama at I've edited the instructions to be more accurate after trying it out myself.


1. The installs all the files needed. It is attached here;
2. Place it in the top folder on your internal sdcard, ie. /sdcard
3. Turn off your phone.
4. Hold down Up(Volume) + Power Button + Menu button(Home button) simultaneously for a couple of seconds until u see the manual boot screen.
5. Use the up and down buttons to get to
6. Press menu button on to select it
7. It installs root, correct busybox (1.17.1),, as well as all the scripts needed for the fix and the 'MCR Scripts' app to run the scripts.
8. After install, the phone restarts.
9. Go to the newly installed 'MCR Scripts' application from the app list, open it and choose from 3 scripts. For example, Lagfix10024 is the 1gb ex2 version.
10. The script would launch superuser permission prompt. Click "Allow" and it should run in a terminal for about 10 minutes. Don't worry if it seems to get stuck on "...takes a while...". You'll see some output of what it's doing later.
11. You should see an 'All complete' terminal prompt, and this means you can close the application.
12. Run Quadrant app (install from Market) to test if the fix was applied. You should see results like in

**PLEASE READ!!! Some hiccups that I've encountered.**

The first time I clicked "Allow" in step 10, the script encountered Permission denied and didn't do anything. I had to stop the script and try it another time before it got going.

Before 'All complete' prompt, the script seemed to have repeated what it needed to do. After "installing" my Market app couldn't work. Rebooting phone caused screen to be blank. I had to press Up + Menu + Power to enter manual boot and do Factory reset. That meant losing data on my phone. At least I didn't have anything important irrecoverable as my Contacts are synced with Gmail Contacts. I installed and ran Quadrant just to see if the fix had been applied and saw that benchmark results were that of before fix.

I tried again by repeating from step 3. This time the script seemed to have executed properly. I ran Quadrant again and got the benchmark results. Running applications did seem MUCH FASTER but I hope it's not because I've factory reset the phone...

Monday, August 2, 2010

Lithium ion batteries first charge

According to an article at

Unlike nickel and lead-based batteries, a new lithium-ion pack does not need cycling through charging and discharging. Priming will make little difference because the maximum capacity of lithium-ion is available right from the beginning. Neither does a full discharge improve the capacity of a faded pack.
So really the "full discharge and initial charge of 8 hours" were obsolete practices of the Nickel Cadmium batteries era.

Sunday, July 25, 2010

Remapping keyboard keys in Mac OSX

Use KeyRemap4MacBook to remap keys on your OSX keyboard.

Snow Leopard Only:

It'll enable "FN + Numpad" by default. What I would really like is a way to do "Left/Up/Down/Right" without using the arrow cursor which forces my hand to shift down the keyboard too much. The utility provides a "Vi Mode" where you can map "FN + hjkl" for Left/Up/Down/Right.

To change CapsLock to Escape you need to download another utility from the website.

Snow Leopard Only:

Tunnel Firefox connections through a server

Use openSSH to open up SOCK5 tunneling to server

Configure network connection in Firefox to use manual proxy. Leave everything blank except

SOCKS Hosts: localhost Port: PORT_NO

Wednesday, July 21, 2010

Controling a Mac OSX using VNC

From "System Preferences > Sharing > Screen Sharing", click "Computer Options" and set password and voila!


Tuesday, July 20, 2010

Using curl to post data to a rails app

curl -X POST -d "location[lat]=111&location[lng]=222" http://localhost:3000/users/123/devices/456/locations

However rails require authenticity token. To overcome that just turn forgery protection off.

# config/environment.rb
config.action_controller.allow_forgery_protection = false

Monday, July 12, 2010

Print screen in Mac OSX


- Hold down Apple key ⌘ + Shift + 3 and release all
- Mouse click on screen

Portion of screen:

- Hold down Apple key ⌘ + Shift + 4 and release all key
- Drag mouse to select portion of screen to capture


Sunday, June 20, 2010

Untrack file in git

git rm --cached FILENAME

Saturday, June 19, 2010

Blank screen after resuming from suspend in Ubuntu

Of late I'm getting blank screen from suspend on my Ubuntu netbook after starting to use a second external monitor. Not sure the reason why but the fix for me is to hit "CTRL + ALT + F7".

Friday, June 18, 2010

X11 error: BadAlloc (insufficient resources for operation) while using mplayer

mplayer -vo x11 PATH_TO_FILE

Use mplayer to play stuttering web flash videos on browsers (high CPU load)

Playing web flash videos on my Ubuntu Firefox can yield super high CPU load as flash is poorly supported on Linux. Couple that with a sub-optimal Firefox Flashplayer plugin which causes CPU load to spike up to almost 100% and this makes the video stutter like mad.

One solution is to start and pause the video to initiate caching and use mplayer to play the cached flash video instead.

mplayer /tmp/Flash*

Now it plays smooth. Fullscreen? No problem. Just toggle "F" on your keyboard!

Tuesday, June 8, 2010

Share iTunes playlist and files over network using Ubuntu as fileserver

# Install mt-daapd
sudo apt-get install mt-daapd

# Edit mt-daapd.conf and specify media folder
sudo vi /etc/mt-daapd.conf

# Restart mt-daapd
sudo /etc/init.d/mt-daapd stop
sudo /etc/init.d/mt-daapd start

# Configurations can be done on webpage
# Remember to port forward 3689 to ubuntu machine

Sunday, May 23, 2010

Undo git add


Friday, May 21, 2010

"No more PTYs. Sorry, could not find a PTY" error in GNU Screen

It's a /dev/ptmx file permission problem.

chmod a+w /dev/ptmx

No root user created for mysql in Ubuntu Hardy

/etc/init.d/mysql stop
mysqld --skip-grant-tables &
mysql -u root mysql
mysql> INSERT INTO user VALUES ('localhost','root',password('newpassword'),'Y','Y ','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y', 'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','' ,'','','',0,0,0,0); 

Saturday, May 15, 2010

Turning on ALT keys in Mac OS X Terminal

Under Terminal "Preferences", make sure to check the ""Use options as meta key" in the "Keyboard" tab

Friday, May 14, 2010

Installing Hamachi on Mac OS X Snow Leopard


Remember to download and install Tun/Tap package!

After that just download and install hamachi for Mac OS X

cd /Users/you/Downloads/hamachi-
sudo ./install
sudo /usr/sbin/tuncfg
hamachi start
hamachi login
hamachi join NETWORK
hamachi go-online NETWORK

Cannot pair up newly bought Aztech 109E with existing Aztech 110E + 110EW pair.

Aztech Homeplug models 108*, 109*, 110*, ie. 200mbps series, are supposed to be able to work with each other. Had trouble pairing up newly acquired Aztech 109E with already existing 110E* pair.

The solution was to reset the Private Network Name that the existing pair was using. This can be done by simply pressing the "Simple Connect" button for ALL the pairs for 10secs.

'BadAlloc (insufficient resources for operation)' errror message while playing mp4 using mplayer

Fixed this by specifying video driver as such

mplayer -vo x11 PATH_TO_VIDEO

Selecting GNU screen profile in Ubuntu Lucid Lynx

screen is now managed by byobu package


Monday, May 10, 2010

Streaming radio using mplayer

mplayer -playlist RADIO_STREAM_URL

Tuesday, May 4, 2010

Finding uninvoiced fees in rails

# Models

Class InvoiceItem < ActiveRecord::Base
  belongs_to :fee

Class Fee < ActiveRecord::Base
  has_one :invoice_item

# Namedcope in Fee model

namedscope :uninvoiced, {
  :conditions => " NOT IN (SELECT fee_id FROM invoice_items)"

Monday, April 26, 2010

Find ubuntu release and version on the command line



cat /etc/lsb-release

Thursday, April 22, 2010

Configure git colors and output format

# Add color
git config color.ui auto

# Format for log, whatschanged
git log --pretty=

Monday, April 19, 2010

Installing OSQA

While installing OSQA, an opensource clone of StackExchange (Stackoverflow) written in Python (Django), I encountered a few gotchas

Installation instructions:


1. Install mod-wsgi for Apache2

sudo apt-get install libapache2-mod-wsgi
2. Commented code in Apache.conf

The following commented code seems to screw up restarting of apache

WSGISocketPrefix /path/to/socket/sock #must be readable and writable by apache
WSGIPythonHome /usr/local #must be readable by apache
WSGIPythonEggs /var/python/eggs #must be readable and writable by apache
Just get rid of them.

3. WSGI script in documentation

As documented in

That pipe screws things up. I'm not exactly familar with python so maybe it's deprecated in Python 2.6? Anyways just get rid of it.

os.environ['DJANGO_SETTINGS_MODULE'] = 'osqa.settings'
4. Table migration

Apparently if you followed the recommendation to use South for migration you'll soon find that it FAILS. Yikes! Search their Q&A (meta) provides an answer.

Just do

./ syncdb --all
./ migrate --fake

Sunday, April 11, 2010

Recover deleted branches in Git

Accidentally deleted a branch? No problem. Git reflog to the rescue.

git checkout -b recover_lost_commits

git reflog

e9c17db... HEAD@{0}: checkout: moving from stable to master
e9c17db... HEAD@{1}: checkout: moving from stable to e9c17dbfffd79f2bf30530e144c43c0f47322826^0
318c0f2... HEAD@{2}: checkout: moving from master to stable
e9c17db... HEAD@{3}: commit: Forgot to add images to CSS and adjusted positions.
3baab51... HEAD@{4}: commit: Added new buttons.

git merge e9c17db

Wednesday, April 7, 2010

Using minitest for speedier unit tests

sudo gem install minitest # Install MiniTest
sudo gem install minitest_tu_shim # Install Test::Unit shim
sudo use_minitest yes


If you've freezed rails into a project then trying to script/server will throw the following error.

.../vendor/rails/activesupport/lib/active_support/dependencies.rb:445:in `load_missing_constant': uninitialized constant Test (NameError)

Saturday, March 20, 2010

Finding and killing application processes in the command prompt on Windows XP

To find PID or process name

Note: Not available in Windows XP Home edition by default. Google and download it.

To kill the PID or process name, look for tskill.exe under c:\windows\system32\

tskill.exe PID | PROCESS NAME

Friday, March 19, 2010

HP F2410 printer on Ubuntu

Wanted a printer that works on Ubuntu. Did some research and realized HP printers are the most well supported.

Acquired a cheap SGD99.00 HP F2410 printer off local store. Installing it isn't as easy as plug and play but it's close enough. Essentially CUPS doesn't have the right PPD so it's off to HP website to download the the driver. They even provide a neat installation run file that does dependency checks!

Printing well and scanning works with Xsane. At such a low price I can't be happier. I owe HP one!

Monday, March 15, 2010

Play remote media files over ssh using mplayer

ssh username@ "cat ~/Video/apprentice.avi" | mplayer -

Sunday, March 14, 2010

Set Ubuntu to use Google DNS for internet

Sometimes my 2Wire router doesn't seem to route to the DNS properly. As such I can ping IP addresses but not domain names. To fix that just tell Ubuntu to use Google DNS (or any other free DNS service) directly.

# In /etc/dhcp3/dhclient.conf

prepend domain-name-servers,;

Friday, March 12, 2010

Sync music/podcasts to mobile phone

Essentially use rsync to sync folders between multiple machines which in this case the host machine with the music files and the mobile phone storage.

rsync ~/Music /media/disk/Music -rP
For podcasts it'll be a good idea to use cronjob to download new podcasts. I'm using a remote server to download them.

# On my remote server

sudo apt-get install podget

# crontab -e on server
0 * * * * /usr/bin/podget -s

# On my local host machine with mobile phone plugged in

rsync username@remote-server:./Music/Podcasts /media/disk/Podcasts -rP

Thursday, March 11, 2010

Stop restart popup after automatic updates in Windows XP

Absolutely annoying feature of windows is a popup that keeps asking you to restart the system after a Windows update. Disable that!

# Disable current popup from the command prompt

net stop "automatic updates"

# Disable future auto restarting of system. 
# I'm using Windows XP Home so can't access gpedit.msc. 
# Need to use a registry script instead --> stop_update_restart.reg
# P.S. note the first line.

Windows Registry Editor Version 5.00


Wednesday, March 10, 2010

Full path of file in ruby


Monday, March 8, 2010

cp with progress indicator by using rsync instead

# Instead of

cp -r folder destination_folder

# Use rsync instead

rsync folder destination_folder -P

Sunday, March 7, 2010

Comparing 2 files using diff

diff -uN app/models/common_test.rb app/models/major_test.rb  | vi -

Running ruby scripts as cron jobs in rvm environment

# This will fail to run properly

*/5 * * * * /usr/bin/env ruby /home/username/twitter.rb

# Need to run the script in full bash environment

*/5 * * * * bash -c 'source /home/username/.rvm/scripts/rvm && /usr/bin/env ruby /home/username/twitter.rb'

Cron log in Ubuntu

* Edit /etc/syslog.conf and uncomment the line starting with cron.*
* touch /var/log/cron.log
* Run /etc/init.d/rsyslog restart
* Run /etc/init.d/cron restart

Changing of syslog.conf location in Ubuntu Karmic




Saturday, March 6, 2010

Changing timezone in terminal

sudo dpkg-reconfigure tzdata

Friday, March 5, 2010

Rvm notes

Getting prepared

sudo apt-get update
sudo apt-get -y install build-essential zlib1g zlib1g-dev libxml2 libxml2-dev libxslt-dev sqlite3 libsqlite3-dev locate git-core libssl-dev openssl autoconf subversion bison
sudo apt-get -y install curl wget

For Ubuntu, use rvm package to download and complie zlib

rvm package install zlib
rvm remove 1.8.7
rvm install 1.8.7 -C --with-zlib-dir=$rvm_path/usr

Before installing any versions of ruby using rvm

sudo apt-get install libssl-dev
Installing Ruby Enterprise Edition

Error running './installer -a /home/username/.rvm/rubies/ree-1.8.7-2010.01  --dont-install-useful-gems ', please check /home/username/.rvm/log/ree-1.8.7-2010.01/install*.log
There has been an error while trying to run the ree installer. Aborting the installation.

# Need to install the following library first
sudo apt-get install libreadline5-dev
rvm install ree

Thursday, March 4, 2010

Rails 3 notes


Grab the jQuery driver at and put it in your javascripts directory. Include the file in the layout.


Rails requires an authenticity token to do form posts back to the server. This helps protect your site against CSRF attacks. In order to handle this requirement the driver looks for two meta tags that must be defined in your page's head.



link_to :controller => 'user_sessions', :action => 'destroy'

# Route
match '/log' => "user_sessions#destroy", :as => :logout

# View
link_to 'Logout', '/logout'

Vim can't make backup file

Ensure that the backup directory in .vimrc exists.

# in .vimrc

set backup
set backupdir=~/.vim/backups

mkdir -p .vim/backups

Vim unable to open swap file

If you see the following message when opening a vim file

Unable to open swap file for "{filename}", recovery impossible

The directory specified in your vim for swap files is missing. In my case it's ~/.vim/tmp.

# in .vimrc
set directory=~/.vim/tmp

mkdir -p ~/.vim/tmp

Sunday, February 28, 2010

Git diff changes staged

# On branch master
# Changes to be committed:
# (use "git reset HEAD ..." to unstage)
# modified: app/views/matriculations/new.html.erb

To see changes,

git diff --cached (pre-1.6)
git diff --staged

Rails, RedCloth, textilize gotcha

# This doesn't work! It returns html in pure strings and not the html elements!

textilize @blog.content

# Need this extra step.

sanitize(textilize @blog.content)


The problem lies that Rails 3 ERB uses h() helper by default

<\%= xxx %>
<\%= h(xxx) %>
To get past this use context_tag() or raw()

xxx = content_tag(:p, "blah")
<\%= xxx %>

xxx = "<\p>blah<\/p>"
<\%= raw xxx %>

Saturday, February 27, 2010

Using Fn triggered blue numpad keys for navigation on your laptop

Laptop keys are usually cramped and accessing the usual arrow and page keys are a hassle. I find it useful to use the "numpad" triggered by Fn key.

Fn + 7 = Home
Fn + 1 = End
Fn + 9 = Pg Up
Fn + 3 = Pg Down
Fn + 8 = Up
Fn + 2 = Down
Fn + 4 = Left
Fn + 6 = Right

Sunday, February 21, 2010

Bringing jobs into background in terminal

# Suspend job
CTRL + z

# View jobs

# Bring job into background
%1 &

# Bring job into foreground

Open files at line number in Vim


:e app/models/user.rb:10

Sunday, February 14, 2010

Friday, February 12, 2010

Installing Flash & Java on Firefox & Chromium browsers

1. Install Flash & Java
2. Symlink executables to browser plugin folder










# Firefox 

# Chromium 


NOTE: symlinks must be updated after every java upgrade

Wednesday, February 10, 2010

Factory Girl has many associations gotcha

Suppose Post has many Items

class Post < ActiveRecord::Base
has_many :items

class Item < ActiveRecord::Base
belongs_to :post

When setting up data for tests using factory girl

Factory.define :item do {|p| p.association(:post)}

Don't do this!

@post.items << Factory(:item)

Factory will create an item with another post_id and this will not be automatically changed to Instead do this.

Factory(:item, :post => @post)

Friday, February 5, 2010

Undo last Git commit with last commited files for edit

git reset --soft HEAD^
git reset

Running Shoulda & Factory Girl in Rails 3

Rails 3 uses Bundler gem to handle gem dependencies. Encountered some problems with Shoulda and Factory Girl.

# Gemfile

group :test do
gem "shoulda"
gem "factory_girl"

Shoulda and Factory Girl macros are not loaded so I had to require the gems in test/test_helper.rb

# test/test_helper.rb

require 'shoulda'
require 'factory_girl'
Factory.definition_file_paths = [ File.join(Rails.root, 'test', 'factories') ]

Problem installing sqlite3-ruby gem

Never learnt my lessons. Encountered this so many times.

sudo gem install sqlite3-ruby

Building native extensions. This could take a while...
ERROR: Error installing sqlite3-ruby:
ERROR: Failed to build gem native extension.

/usr/bin/ruby1.8 extconf.rb
checking for fdatasync() in -lrt... yes
checking for sqlite3.h... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.

The solution is to make sure the following library's installed!

sudo apt-get install libsqlite3-dev

Thursday, February 4, 2010

Review git commits in terminal

git log -u HEAD^..HEAD

Saturday, January 30, 2010

Play asx streams with mplayer

mplayer -playlist URL

# if steams gets choppy

mplayer -playlist URL -ao sdl

Wednesday, January 27, 2010

rake cucumber:tags in verbose mode

rake cucumber:ok CUCUMBER_OPTS="--verbose"

rake test:units with verbose output

rake test:units TESTOPTS="-v"

Tuesday, January 26, 2010

View git object tree in terminal

git log --graph --oneline --all

Thursday, January 21, 2010

SHOUTcast on Ubuntu

sudo apt-get install tunapie

Wednesday, January 20, 2010

Download file from Linux machine to Windows machine using SCP

- Download PSCP.exe (
- Open up Command Prompt
- Type the following

# Eg. if my pscp.exe is on my Windows desktop

"C:\Documents and Settings\Jason\Desktop\pscp.exe" jasonong@IP_ADDRESS_OF_LINUX_MACHINE:./PATH/TO/FILE "c:\Temp"

Monday, January 18, 2010

Count number of files in directory

find files | count lines

find . -type f | wc -l

Sunday, January 17, 2010

Reset Gnome keyring password

rm .gnome/keyrings/login.keyrings
rm .gnome/keyrings/default.keyrings

X Forwarding in Windows

XMing + Putty

- XMing & launch XLaunch
- Launch Putty, making sure that "SSH" > "Enable X11 forwarding" is checked and "MIT-Selected-Cookie-1" is selected.

Thursday, January 14, 2010

Connect linux and windows machine via hamachi vpn gotcha

Make sure window's firewall is off...

Monday, January 11, 2010

Default image viewer on ubuntu

# Eog is the default image viewer in Ubuntu

eog image.jpg

Thursday, January 7, 2010

Launch applications with X display in remote machine

DISPLAY:0 application executable


DISPLAY:0 gnome-terminal
DISPLAY:0 rake selenium:rc:start

Blog Archive