Vagrant 101: Getting Started

Although late to party, but finally I joined. Until now I had been manually managing my VMs in Virtualbox without Vagrant, but that process was very tedious and slow. Find the image, download it, import it, boot the machine, configure networking, assign the IP addresses, setup the machine. But with Vagrant its as easy as:

Note: Dont’ worry about what it means, I will explain in later chapters.

vagrant init <url to box>
vagrant up
vagrant ssh

As you can see how easy it is to get your new sandbox environment up and running within few minutes. Its not just the basic setup, but Vagrant allows you to completely setup your new VM with everything you need in your dev environment.

The great part is you don’t have to leave your local machine to write code. Confused? Vagrant actually mounts your local folder (where you ran vagrant init) in your VM, so what ever changes you make on your local machine will be available in your vagrant box.

Let’s Dive into Vagrant

Enough of the praising, let’s dive in and experience the power of vagrant. First you need to find Vagrant boxes (VM images), so you can use them for your development. The following instructions assumes that your are using some flavor of linux (the concept is same for other OS, you just have to convert the commands as per your OS).

The best place to find the Vagrant boxes are Vagrant Cloud. Once you find the suitable box for your development. Create your development directory and do the vagrant init (remember git or hg init?) with the the name of the box from Vagrant Cloud. See the commands below:

mkdir web-app-dev
cd web-app-dev
vagrant init hashicorp/precise32

This will create the Vagrantfile and add the box name to the Vagrantfile. You are ready to launch your first vagrant controlled sandboxed dev environment. Just run the vagrant up to get the VM up and running. See the example below (run the command in same folder where you ran vagrant init):

vagrant up

This will download the box (VM image) from the Vagrant cloud, after downloading it will boot the box, do the provisioning and then it will mount your development folder on VM at /vagrant. After few minutes your new VM will be up and running.

Once the VM is up, you can login to the VM by just doing a vagrant ssh. Yes it is this simple, see the example below:

vagrant ssh

Now that you are logged into the VM, you can configure it for your development manually (for now). Later on I will write about how can you automate the setup part too, based on your development needs.

Checkout the folder share, by creating files in /vagrant folder on your new VM and then go back to your local folder and see them appear there. Similarly you can create files on local and they will immediately appear in your VM.

Where is the Version Control?

You can add Vagrantfile to your version control so you can replicate your Vagrant setup to other devs or on other locations too. Don’t add other Vagrant files to version control, for now it is just Vagrantfile. Simply just run the following commands (from same folder where you ran vagrant init):

git init
git add Vagrantfile
git commit -m "Add Vagrantfile"

What’s next?

I tried my best to make this getting started guide as simple as I could, and not be confusing for the new developers who are still trying to figure out how linux works. Later on I will write about provisioning and advanced networking setup in Vagrant.

If you have any questions, confusions feel free to ask them in comments and I will try to help you as much as I can.

Howto Setup Vim IDE for PHP Development

As a PHP developer one has quiet a lot of choices of IDE. Some are graphical will built-in features like debugging, code completion, auto indentation, syntax highlighting, code checking and many more. But those IDEs are very heavy and slow to use, and I know many people like me who just can’t live without Vim and want to use Vim for all type of text editing they do, whether they are writing code, editing configuration files or may be creating simple text files.

Recently I posted a screenshot of my Vim editor and got a lot of emails that how did I setup Vim that way. So, I hope this howto will be easy enough for everyone to follow and setup their Vim as their PHP  IDE. For the sake of simplicity I am assuming you are using Vim on Linux or Linux like system. If you are a windows user then this guide should still work for you, but I might not be able to provide Windows related details where needed.

Features that we will add or enable in Vim to make it a complete IDE.

  • Code Completion
  • Tag Lists
  • Project Management
  • Syntax Highlighting
  • Code Checking

First we need to download following Vim scripts and extract them in our ~/.vim directory.

Download above scripts one by one and install them. Installing them is easy just unzip them in you .vim directory which is located in your home directory. Now we need to download few files in our .vim/plugin directory. Download the following Vim scripts directly into your .vim/plugin directory.


Now that you have installed above scripts, you are almost all set to go. You just need to paste the following content in your .vimrc file which is located in your home directory.

" ~/.vimrc                                                      "
"                                                               "
" Version: 0.1                                                  "
"                                                               "
"                                                               "
" Hightlight the ifs and buts
syntax on
" Plugins and indentation based on the file type
filetype plugin indent on
" Don't remember source of this, i think it was already in my .vimrc
" Tell vim to remember certain things when we exit
"  '10 : marks will be remembered for up to 10 previously edited files
"  "100 : will save up to 100 lines for each register
"  :5000 : up to 5000 lines of command-line history will be remembered
"  % : saves and restores the buffer list
"  n... : where to save the viminfo files
set viminfo='10,\"100,:5000,%,n~/.viminfo
" omnicomplete from:
set completeopt=longest,menuone
inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
inoremap <expr> <C-n> pumvisible() ? '<C-n>' :
  \ '<C-n><C-r>=pumvisible() ? "\<lt>Down>" : ""<CR>'
"##       PHP             ##
" The php doc plugin
" source ~/.vim/php-doc.vim
inoremap <C-P> <ESC>:call PhpDocSingle()<CR>i
nnoremap <C-P> :call PhpDocSingle()<CR>
vnoremap <C-P> :call PhpDocRange()<CR>
" run file with PHP CLI (CTRL-M)
:autocmd FileType php noremap <C-M> :w!<CR>:!/usr/bin/php %<CR>
" PHP parser check (CTRL-L)
:autocmd FileType php noremap <C-L> :!/usr/bin/php -l %<CR>
" Do use the currently active spell checking for completion though!
" (I love this feature :-)
set complete+=kspell
" disable tabs
set expandtab
set shiftwidth=4
set softtabstop=4
" highlt matches
set hlsearch
" Taken from
" Make Vim open and close folded text as needed because I can't be bothered to
" do so myself and wouldn't use text folding at all if it wasn't automatic.
set foldmethod=marker foldopen=all,insert foldclose=all
" Enable enhanced command line completion.
set wildmenu wildmode=list:full
" Ignore these filenames during enhanced command line completion.
set wildignore+=*.aux,*.out,*.toc " LaTeX intermediate files
set wildignore+=*.jpg,*.bmp,*.gif " binary images
set wildignore+=*.luac " Lua byte code
set wildignore+=*.o,*.obj,*.exe,*.dll,*.manifest " compiled object files
set wildignore+=*.pyc " Python byte code
set wildignore+=*.spl " compiled spelling word lists
set wildignore+=*.sw? " Vim swap files
" Enable completion dictionaries for PHP buffers.
autocmd FileType php set complete+=k~/.vim/dict/PHP.dict
" PHP Autocomplete
autocmd FileType php set omnifunc=phpcomplete#CompletePHP
set ofu=syntaxcomplete#Complete
" You might also find this useful
" PHP Generated Code Highlights (HTML & SQL)                                              
let php_sql_query=1
let php_htmlInStrings=1
let g:php_folding=2
set foldmethod=syntax
" --------------------
" Project
" --------------------
map <A-S-p> :Project<CR>
map <A-S-o> :Project<CR>:redraw<CR>/
nmap <silent> <F3> <Plug>ToggleProject
"let g:proj_window_width = 30
"let g:proj_window_increment = 150
nnoremap <silent> <F8> :TlistToggle<CR>
let Tlist_Exit_OnlyWindow = 1     " exit if taglist is last window open
let Tlist_Show_One_File = 1       " Only show tags for current buffer
let Tlist_Enable_Fold_Column = 0  " no fold column (only showing one file)
let tlist_sql_settings = 'sql;P:package;t:table'
let tlist_ant_settings = 'ant;p:Project;r:Property;t:Target'
" auto change directory from:
autocmd BufEnter * if expand("%:p:h") !~ '^/tmp' | lcd %:p:h | endif
" when we reload, tell vim to restore the cursor to the saved position
augroup JumpCursorOnEdit
 autocmd BufReadPost *
 \ if expand("<afile>:p:h") !=? $TEMP |
 \ if line("'\"") > 1 && line("'\"") <= line("$") |
 \ let JumpCursorOnEdit_foo = line("'\"") |
 \ let b:doopenfold = 1 |
 \ if (foldlevel(JumpCursorOnEdit_foo) > foldlevel(JumpCursorOnEdit_foo - 1)) |
 \ let JumpCursorOnEdit_foo = JumpCursorOnEdit_foo - 1 |
 \ let b:doopenfold = 2 |
 \ endif |
 \ exe JumpCursorOnEdit_foo |
 \ endif |
 \ endif
 " Need to postpone using "zv" until after reading the modelines.
 autocmd BufWinEnter *
 \ if exists("b:doopenfold") |
 \ exe "normal zv" |
 \ if(b:doopenfold > 1) |
 \ exe "+".1 |
 \ endif |
 \ unlet b:doopenfold |
 \ endif
augroup END
" PHP code sniffer
" If code sniffer is installed you can run it on current php file by running 
" :Phpcs
function! RunPhpcs()
    let l:filename=@%
    let l:phpcs_output=system('phpcs --report=csv --standard=YMC '.l:filename)
"    echo l:phpcs_output
    let l:phpcs_list=split(l:phpcs_output, "\n")
    unlet l:phpcs_list[0]
    cexpr l:phpcs_list
set errorformat+=\"%f\"\\,%l\\,%c\\,%t%*[a-zA-Z]\\,\"%m\"
command! Phpcs execute RunPhpcs()

Thats it, now you are all set to go. Following are the few quick commands to get you started to use all the features you have just enabled in your Vim IDE.

F3: To start using project manager.
\C: After starting project manager this key combination will allow you to add new project.
F8: Tag list window
Ctrl+L: To run the syntax checking on your php file
Ctrl+P: On any class/function definition to add php doc strings
“:PhpCs”: To run PHP Code sniffer on your php script. (this requires code sniffer to be installed).
Ctrl+n: On any word to use Auto completion feature of PHP.

I will soon write another howto to explain how can you use further features of your IDE. You should subscribe to the feed or follow me on twitter to stay updated. 🙂

Develop Your First Android Application in Python

Android is getting popular among mobile users very rapidly, and the fact that Android’s user base is increasing the demand for more usable applications on Android is increasing too. The demand for more applications is causing more and more developers to get into Android development, unfortunately until now the only way to develop for Android was to develop in Java.

But thanks to Google that one of their employee has come up with a solution that allows not only Python programmers but Perl, lua and bash programmers to develop on Android. The new project that has come out from Google is called SL4A and it allows you to use Python to develop for Android. You can get to know more about SL4A from the home page of the project on Google Code. This article tells you the exact steps you can take to setup Android SDK, Install SL4a and Python for Android and then Write your first Android Application in Python and run it.

Setup Android SDK and Android Virtual Device.

First you will have to download latest Android SDK from Google and setup your Android Virtual Device. If you like you can directly develop your Android application on your phone device. Skip to “Installing SL4A and Python for Android” if you want to directly develop on your phone.

1. Download Android SDK. For Linux download the tar ball and for Windows download the executable (recommended).

2. Install the SDK. You might also want to read the Installing the SDK document on Android’s developer site.

On Linux:

Extract the tarball in any directory of your choice.

On Windows:

Run the executable to install the Android SDK.

3. Go into the “tools” directory inside the extracted or installed directory.

4. Run the “android” executable.

On Linux:

$ ./android

On Windows:

Double click the executable to run it.

5. The android executable will start the Android SDK and AVDManager.

AVD (Android Virtual Device) manager

6. Click on the Create New AVD to setup the new AVD for your Android application development.

Create new AVD

7. When the new AVD is created, select it and click on Start. You will see a Android device emulator screen and an Android Logo, the Android OS is booting, you will have to wait for some time. After some time you will get a fully loaded Android OS on your Android emulator to develop and test your Android Application.

Android Emulator

Installing SL4A and Python for Android

Scripting Layer For Android is the main Android Application you need to be able to run your Python applications on Android, so first you need to install SL4A on either your Android emulator or on the real Android device in case if you are going to do the development directly on your device. Follow the steps below to install the SL4A on your Android.

1. Open Android Browser and browse to the SL4A home page:

2. Tap on the QR code icon (the big square box) to download the SL4A application.

Android Browser SL4A home page

3. Tap on the download notification to install the app.

4. Once the installation is complete tap OK and then go back to SL4A home page on your Android Browser.

5. Tap on Python for Android in the Featured Downloads section to download Python for Android.

SL4a Python for Android Download

6. Tap on the download notification to install Python for Android.

7. Once the Installation is complete go to SL4A application which is located under your applications menu. You will see some python scripts that got Installed along with Python for Android.

SL4A Python for Android Test

8. Tap the, a menu will popup.

SL4A run menu

9. Tap the second icon from left. The script will execute and will demonstrate some of the possibilities of the SL4A API available for your Python programs.

Note: The most left icon is to run the application in terminal, the second from left is to run the application normally, the third from left is to edit the script, the fourth from left to rename the script and the last one from left is to delete the script.

Writing the First Android Application in Python

Now that our Android is ready and you have already tested that everything is working fine, its time to write your first Python application. You will write a very simplest version of hello world, this application will ask your name and then it will greet you. Thats it.

1. Copy the following code to on your computer.

import android
app = android.Android()
name = app.dialogGetInput("Enter your name:", "Please enter your name: ").result
app.dialogCreateAlert("Greetings!!!", "Hello %s, how are you?" % name)

2. Goto “platform-tools” directory which is found under the Android SDK directory.

3. Copy (push) the to your Android by running the following command.

$ ./adb push /sdcard/sl4a/scripts/
4. Press the menu button on your Android device or Android emulator, and tap Refresh.

5. will appear in the script listing, tap the script.

6. The SL4A run menu will appear, click the second icon from left.

SL4A First Python Android Application

7. A popup will appear asking you for your name, enter your name and click OK.

SL4a first Python Android Application running

8. Another popup will appear with a greeting message for you.

SL4A Greetings


Congratulations!!! You are done here. Its now up to you how you make use of the Android API available via SL4A. Best of luck.

You should subscribe to the feed to stay updated about the next article that will describe how you can build a stand alone .APK application from your Python script.

For all of you Django developers tighten your seat belts for DjangoDash

DjangoDash, let see who is the fastest and coolest. A competition of its kind which is based on Django Frame work is about to start. Every team can have 2 participants and they will need to build a Django app in a very tight timeframe of 48 hours.

This competition is going to prove that “Django is the webframe work for perfectionists with deadline”. So a 48 hours deadline and you need to build a coolest app, with good code quality and everything a perfect django app should have. See DjangoDash judging for more information.

Note: If you don’t know Django and want to participate in DjangoDash and you think you a good/innovative coder, please grab your copy of Django now and start learning and coding in Django. There is still time in competition to start.