Locating current position on map

HTML5 introduced new set of specifications which include geolocation APIs. Using them one can find the location of a device. While exploring it further, I found a simple Javascript program that neatly demonstrates the overall idea (references (i)). The following code has been modified a bit from the original one to make it more verbose.

  if(navigator.geolocation) {


      // success callback, where 'position' holds the found coordinates.
      function(position) {
      // Instantiate a Google Map's LatLng object using the position coordinates.
      initialLocation = new google.maps.LatLng(position.coords.latitude,
        Now 'initialLocation' can be used to place a marker on the map or
        other coordinates related stuff.

      // error callback, where 'positionError' holds various error related
      // attributes (see reference (ii) for details).
      function(positionError) {
      // log the error message
      console.log("Geolocation service failed. MSG: " + positionError.message);
      {maximumAge:Infinity, timeout:10000});

  // Browser doesn't support Geolocation
  else {
    console.log("Your browser doesn't support geolocation.");

i) https://developers.google.com/maps/articles/geolocation
ii) http://dev.w3.org/geo/api/spec-source.html

Shell script: recursive find/replace

Lately I had a requirement of finding & replacing a specific string from all the files under a directory tree, while keeping the file permissions intact. Here is the shell script that I eventually came up..


cd target_dir

for _file in `find .`;
  if [ ! -d $_file ]; then
    sed "s/SEARCH_STR/REPLACE_STR/g" $_file > tmp; cp tmp $_file; rm tmp;

Hope this would help somebody.. disfrutar!

Shell: test: argument expected

The following shell script might work just fine on many of the available shell interpreters but the same would fail with the ‘test: argument expected’ error if you try to execute it under sh on Solaris platform.


touch /tmp/i_exist
if [ -e /tmp/i_exist ]; then
  echo "file exists!"

So, what we are trying in the above script is to check if the given file exists using shell’s [condition].
As per Solaris test(1):

-e file — True if file exists. (Not available in sh.)

A simple solution to this issue is to use ‘-f’ instead. It checks for the existence of regular files and supposed to work on most of existing shell interpreters.

How to debug signal handlers using GDB

At times, one might want to debug a signal handler using GDB. Looks simple, just set a breakpoint at the entry! But there is tiny glitch. Consider the following program.

  @file : sig.c


void signalhandler(int signum) {
  printf("\n SIGINT caught : %d", signum);

int main() {
  signal(SIGINT, (void*)signalhandler);

  while (1) {
    printf("\n looping : inside main()");

Now, lets try to debug the signal handler function using GDB.

# Set a breakpoint in the signal handler function.
(gdb) b signalhandler 
Breakpoint 1 at 0x40058f: file sig.c, line 5.
(gdb) r
Starting program: /home/nirbhay/project/sandbox/c/signal/a.out 

 looping : inside main()
 looping : inside main()
 looping : inside main()
 looping : inside main()
 looping : inside main()
# And now, Ctrl-C
Program received signal SIGINT, Interrupt.
0x00007ffff7af5120 in __nanosleep_nocancel () at ../sysdeps/unix/syscall-template.S:82
82	../sysdeps/unix/syscall-template.S: No such file or directory.
	in ../sysdeps/unix/syscall-template.S

Its apparent that the signal that we are trying to send to the program is being intercepted by GDB and hence control never enters the signal handler (where we have already set a breakpoint).

In such scenarios, GDB’s handle command can be used. With this command we can alter the default behaviour of GDB towards signals. The handle command takes, as argument, a list of signals (to be handled) followed by actions. Of all the actions, ones that are of interest to us are : nostop (do not re-enter debugger if this signal happens) & pass (let program see this signal).

Lets now watch ’em in action :

(gdb) handle SIGINT nostop pass
SIGINT is used by the debugger.
Are you sure you want to change it? (y or n) y

Signal        Stop	Print	Pass to program	Description
SIGINT        No	Yes	Yes		Interrupt
(gdb) r
Starting program: /home/nirbhay/project/sandbox/c/signal/a.out 

 looping : inside main()
 looping : inside main()
Program received signal SIGINT, Interrupt.

Breakpoint 1, signalhandler (signum=2) at sig.c:5
5	  printf("\n SIGINT caught : %d", signum);

Figlet : A cool tool

I recently came across ‘figlet‘. Its a handy tool to generate generate text in different styles & sizes that can be used in mail signatures, text documents, etc.

On ubuntu, ‘figlet’ package also comes with some other related tools like figlist (lists figlet fonts & control files), showfigfonts (prints a list of available figlet fonts).


Go sorting, an example

I was recently trying to figure out a way to sort entries stored in a map using Golang. And then, I came across the “sort” package. It provides a Sort() function which can used to sort slices and user-defined collections.

func Sort(data Interface)

All you need is to define the functions listed under the Interface type.

Here is an example to demonstrate the same :

package main

import (

type keys []int

/* Definitions for all 'Interface' functions. */
func (k keys) Len() int           { return len(k) }
func (k keys) Less(i, j int) bool { return k[i] < k[j] }
func (k keys) Swap(i, j int)      { k[i], k[j] = k[j], k[i] }

func main() {
        var (
                k keys
                i int

        var varMap = map[int][]string{
                3: []string{"Harry"},
                1: []string{"Tom"},
                2: []string{"Dick"}}

        k = make(keys, 3)

        for key, _ := range varMap {
                k[i] = key


        for i = 0; i < len(k); i++ {
                fmt.Println(k[i], " : ", varMap[k[i]])

Output :
>  go run sort.go 
1  :  [Tom]
2  :  [Dick]
3  :  [Harry]

Multiline statements in Golang

As Golang (unlike C, C++, Java, etc.) frees a programmer from using semi-colon ‘;’ to terminate a statement, one might find it problematic to write a miltiline statement in Go.

Lets start with a quote :

“Like C, Go’s formal grammar uses semicolons to terminate statements; unlike C,those semicolons do not appear in the source. Instead the lexer uses a simple rule to insert semicolons automatically as it scans, so the input text is mostly free of them. “

So, based on my experience so far, here is a trick that I would suggest, one can break a line after “an operator”.

        result := a +
                b +
func add(a int,
        b int,
        c int) (result int) {
        result = a + b + c

Now coming to strings, they can we written in two ways.

1) Interpreted string literal :

        str := "Lorem ipsum dolor sit amet, consectetur adipisicing" +
               " elit, sed do eiusmod tempor\nincididunt ut labore " +
               " et dolore magna aliqua. Ut enim ad minim veniam," +
               " quis nostrud\nexercitation ullamco laboris ..."

2) Raw string literal :
For multiline strings, back quote ‘`’ can also be used with a couple of restrictions :
a) Any character is legal except back quote.
b) Escape sequences won’t be interpreted.

        str := `Lorem ipsum dolor sit amet, consectetur adipisicing 
                elit, sed do eiusmod tempor incididunt ut labore et
                dolore magna aliqua. Ut enim ad minim veniam, quis
                nostrud exercitation ullamco laboris ...`

go go go…

Create static and shared libraries in Unix

Static Library
Lets first look at how static library can be created and used :

(a) Compile print.c to get an object file :
gcc -c print.c -o print.o

(b) Create a static library (archive) of the object file :
ar rcs libprint.a print.o

According to *nix norms, static library’s name should start with ‘lib’ and have ‘.a’ extension. ar is a unix tool to create, modify and extract from archives.

(c) Now compile main.c and link it statically to the library.
gcc -static main.c -L. -lprint -o statically_linked

$ ./statically_linked
hello world!

Shared Library
One of the most important things to note while creating shared libraries is the object files should be compiled with -fPIC option (position-independent code).

(a) gcc -fPIC -c print.c -o print.o

(b) gcc -shared -o libprint.so print.o

(c) gcc main.c -o dynamically_linked -L. -lprint

$ LD_LIBRARY_PATH=. ./dynamically_linked
hello world!

Note: Detailed explanation of the above used gcc switches can be found in gcc manual pages.

Singleton : Restrict instantiation of a class to one object

In order to achieve this, first thing which we need to do is make the class’s constructor private, which in turn will not allow any other class (outside) to create an abject of that class directly using the constructor. After this we can just define a getInstance method, which does the required two things:
1. Check how many objects of the class have been created.
2. Depending on (1) return an instance of the class.

Here is the code :

  @file : test.java

class Singleton {
  private static int counter=0;

  private Singleton() { //private constructor
    System.out.println("Object instantiated!");

  static Singleton getInstance() {
    if (counter < 1 ) { // to allow only 1 object creation.
      Singleton inst = new Singleton();
      counter ++;
      return inst;

    System.out.println("Can't instantiate further ..");
    return null;

public class test {
  public static void main(String str[]){
    Singleton ins1 = Singleton.getInstance();
    Singleton ins2 = Singleton.getInstance();
    Singleton ins3 = Singleton.getInstance();

Output :

$ java test
Object instantiated!
Can't instantiate further ..
Can't instantiate further ..