Saturday, February 25, 2017


1. To convert an existing integer column to auto-increment type 'serial' : 
# Create a sequence called TABLE_id_seq (replace TABLE with actual table name). Find the maximum number and start the sequence with the next number. For example say max(id) is 30, then start with 31. 
Command: create sequence TABLE_id_seq start with 31;
Anytime you can restart the sequence with 'restart with' option. 

#Alter the table's column with default nextval function which will increment the integer when new rows are inserted into the table. 
Command: alter table TABLE alter column COLUMN set default nextval('TABLE_id_seq');

2. To copy a table to a new one use commands:
 create table NewTable as select * from OldTable;
 alter table OldTable rename to Newname;

3. To rename a column:
  alter table Table rename column Column to Newname

Saturday, December 5, 2015

Performance Comparison of C, Swift, Go and Python

To compare the performance of different languages, let us write a simple algorithm that does the following. Say the given number is 5. Then the algorithm calculates the sum of all numbers for numbers from 1 to 5.
1+ (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5) = 35

C Program - test.c:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
  long sum = 0;
  int V = atoi(argv[1]);
  for (int C=1; C<=V; ++C) {
    for (int c=1; c<C+1; ++c)  {
        sum = sum + c; 
  printf("sum = %li\n",sum);
  return 0;

Swift Program - test.swift:

  var sum = 0;
  var V = Int(Process.arguments[1])
  for var C = 1; C <= V; ++C { 
      for var c = 1; c < C+1; ++c { 
        sum = sum + c;
  print("sum = \(sum)");

Go Program - test.go:
package main
import "os"
import "fmt"
import "strconv"
func main() {
 sum := 0
 V,err := strconv.Atoi(os.Args[1])
for I:=1; I<=V; I++ {
  for i:=1; i<I+1; i++ {
  sum = sum + i
if err == nil {
fmt.Println("sum =",sum)}

Python C extension: Say we want to create a module named "pal" with a function called "f1" to just do the same as test.c

Step 1. Create a file called "palmodule.c" :
#include <Python.h>
static PyObject * pal_f1(PyObject *self, PyObject *args)
  int x;
  PyArg_ParseTuple(args, "i", &x);
  long sum = 0;
  for (int C=1; C<=x; ++C) 
    for (int c=1; c<C+1; ++c)
        sum = sum + c;
  return Py_BuildValue("l", sum);

static PyMethodDef PalMethods[] = {

  {"f1", pal_f1, METH_VARARGS},

static struct PyModuleDef palmodule = {

   "pal",   /* name of module */
   "", /* module documentation, may be NULL */
   -1,       /* size of per-interpreter state of the module,
                or -1 if the module keeps state in global variables. */

PyMODINIT_FUNC PyInit_pal(void)

    return PyModule_Create(&palmodule);


Step 2. Create a file called ""
from distutils.core import setup, Extension
setup(name='pal', version='1.0', ext_modules=[Extension('pal', ['palmodule.c'])])         

Step 3. Install the extension using the following command:

sudo python3 install

 Step 4. Now write a python program "" using the pal module:

from sys import argv
from pal import f1
print("sum = %s" %f1(int(argv[1])))

Runtime Performance Comparison 

Run the above four different programs one by one and find the time taken as shown below. The number used is 100,000 :

1. C program

$ time ./test.o 100000
sum = 166671666700000
real 0m10.999s
user 0m10.992s
sys 0m0.000s

2. Swift program
$  time ./test.sw 100000
sum = 166671666700000
real 0m19.318s
user 0m19.304s
sys 0m0.000s

3. Go program

$  time ./test.g 100000
sum = 166671666700000
real 0m2.155s
user 0m2.152s
sys 0m0.004s

3. Python C extension program
time ./ 100000
sum = 166671666700000
real 0m1.618s
user 0m1.616s
sys 0m0.000s

This shows that Python with C extension is the best that takes the least time. The second best is "Go", then "C". Swift is the worst among them.


Sunday, October 4, 2015

Upstart Job Setup in Ubuntu

At Ubuntu start-up, say you want to to adjust brightness, you can add an upstart job for this.
1. Add a file brightness.conf at /etc/init/ with following lines
  description "Job to control brightness at startup"
  author "..."
  start on runlevel [2345]
  exec intel_backlight 14  # to set brightness to 14%
2. Changes will take effect after restart or by changing run levels.

3. You can start the job by typing:
  sudo start brightness  or
  sudo service brightness start

Wednesday, September 30, 2015

Yield Expression and Generator Function in Python

Yield expressions are only used within a generator function. Here is an example:

>>def pp():
     x = yield      #1
     yield x*x       #2
     yield x*x*x     #3
     yield x*x*x*x   #4 
     yield x*x*x*x*x   #5
     yield x*x*x*x*x*x   #6

>>g = pp()
>>next(g)     #starts the generator and executes line #1
>>g.send(5)  #sends value 5 to x at line #2 and gets the result
>>next(g)     #gets the result of next line #3
>>next(g)     #gets the result of next line #4
>>g.send(2)  #gets the result of next line #5 
3125       #cannot send a new value in the middle of execution
>>next(g)     #gets the result of next line #6
>>next(g)    #Throws StopIteration exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

Saturday, September 12, 2015

Vim AutoCompletion for Python

Installing Pydiction to enable Auto-Completion for Python in Vi (Vim) editor:
1. First install Pathogen using the System Package Manager.
2. Download vimogen int the home directory using command-line:
 git clone
3. Create .vim and .bundle directories by command-line:
 mkdir ~/.vim
 mkdir ~/.vim/bundle
4. Create file .vimogen_repos with the following content:
 echo "" > ~/.vimogen_repos
5. Run vimogen by command-line:
  ~/vimogen/   (and type 1 to install) 
  This will install pydiction in directory ~/.vim/bundle/
5. Under ~.vim do the following link:
  cd ~/.vim
  ln -s bundle/pydiction/after .
6. edit ~/.vimrc file and add the following lines:
filetype plugin on
let g:pydiction_location = '~/.vim/bundle/pydiction/complete-dict'
if has("autocmd")
  autocmd FileType python set complete+=k/path/to/pydiction iskeyword+=.,(
endif " has("autocmd")

That all you need to do. 
Now open an existing or new *.py file and check auto-completion by typing any python keyword or module partially and press tab to show the available choices.
For further reading check the following links.

Thursday, July 23, 2015

Grep between two words in string

Say from the string "Age: = 24 years", you want to extract the value 24. Grep can be used to search for a pattern between two words. Here is the grep command for that:
echo "Age: = 24 years" | grep -P -o '(?<=Age: = ).*(?= years)'

Wednesday, July 22, 2015

Using iTunes & iPhone in Virtual-Box Windows from Ubuntu Linux host

Using iTunes to access iPhone in Ubuntu is not possible but you can do it with a Windows Virtual Machine.

#1. Install Virtualbox from Oracle in Ubuntu.

#2. In Ubuntu add user to vboxusers group by this command:  
sudo gpasswd -a $USER vboxusers

#3. Connect your iPhone to the Ubuntu USB port. 

#4. Within Virtualbox install Windows-7

#5. Once installed run Windows-7 and install Guest Additions Extension Pack.

#6. Reboot the Windows-7 Virtual Machine and from the Devices menu on top, select USB and check the "Apple Inc". 

#7. Install iTunes within Windows-7. Run iTunes and it will detect your iPhone. 

Monday, July 6, 2015

Range or Sequence in Shell Script

Following is an example to print numbers 1 to 20 in a shell script. The numbers below 10 need to be printed with 2 digits like 01..09 

for i in $(seq 20) 
if [ $i -le 9 ] 
then echo 0$i
else echo $i

Tuesday, June 30, 2015

Concatenate or Convert audio or video files

In Ubuntu Linux, install the utility ffmpeg:
sudo  apt-get  install  ffmpeg

Say you want to convert all the mp3 files in a directory to a single file called output.mp3. Then do the following. 
1. cd  to the directory
2. ls  *.mp3  >  list.txt
3. ffmpeg  -f  concat  -i list.txt  -c  copy  output.mp3

Sunday, June 28, 2015

Avoid shutdown or sleep when lid is close on Ubuntu Laptop

To avoid the Ubuntu laptop from shutting down when lid is closed, open the file '/etc/systemd/logind.conf' and add the following line at the bottom.
Then restart the following service:
sudo restart systemd-logind

Tuesday, June 16, 2015

Date Command with Format

Date command in Linux shows the results as below:
#Tue Jun 16 16:18:50 EDT 2015

But if you want to display the date say in the format 16-06-15 then use the following format option with date command:
#date +"%d-%m-%y"

Choose vi editor to open with crontab

Generally "crontab -e" opens with nano editor or gives an option to choose editor when opened for the first time. 
If you want to change the editor later on, enter the command "select-editor" and choose vi. This will force crontab to use vi.

To find your ip address

To find your local IP address type the following command:
  • ip addr | grep global | grep 'inet ' | sed -e 's/\/.*//' -e 's/.*inet //'

To find your global or internet ip address, type the following command:
  • curl -w '\n'
  • curl 

Monday, June 8, 2015

To find the time response of a website

Using the command 'curl', the time response of a website or a webpage can be found. The following is an example to find the response time for the website ''

curl -s -w '\nLookup time:\t%{time_namelookup}\nConnect time:\t%{time_connect}\nPreXfer time:\t%{time_pretransfer}\nStartXfer time:\t%{time_starttransfer}\nTotal time:\t%{time_total}\n' -o /dev/null

The response will be:
Lookup time: 0.004
Connect time: 0.062
PreXfer time: 0.062
StartXfer time: 0.123
Total time: 0.248

Thursday, June 4, 2015

Python Interpreter - Removing leading dots.

Create a file with following lines in the default home directory (~):

import sys
sys.ps1 = '>>'
sys.ps2 = ''

Add the following line in .bashrc or profile file to export variable.