Saturday, May 9, 2015

Use case diagram of library management system

In library management system, the  borrower borrows the book available and the returns the book within specified time and the system needs to check the available books before uses borrows book and during returning of books, system needs to check the return data to verify the return book.

further the system also need to register the new user before the user borrows the book.


USE CASE diagram of library management"


Proposal Report on android based minor project(GPS based travel)

GPS Based travel Project is aimed at people with Smart Phones helps them to figure out the effective route from their current place to their friend’s place. It will be developed as an application for android based phone systems which utilizes the GPS service of the phone system and Google Maps to show the effective route to his destination.

The positions of the bus stops are stored in the database which is used as nodes to form a graph for finding the shortest path. The position of the bus// vehicles   is tracked in every nodes (bus stops) it passes through. The location of the application user is found out by the GPS service of the phone system. After obtaining the destination, the effective path is calculated based on the position and route of the vehicles. This effective/optimum path is then plotted in the map and provided to the user.


The proposed system is an application for android phones which helps the  user to show the optimal routes from his current place to a particular destination. The optimal route is displayed in pictorial form by using google maps and highlighting the route.
Considering the privacy and security of the application user , the user can choose whom to display the information about his location as his will. This will create a network of friends which are able to share their real time location with each other.
The application that we are developing is aimed mostly at people of Kathmandu Valley. Since this application is developed on Android platform, a smart phone with Android OS with GPS support is needed for running the application. By acquiring information about location of user through GPS and the destination through the user, the effective route between the users place and the destination is then provided to the user through the use of Google Map.


The full copy of this Report is available here for download

Thursday, April 16, 2015

source code of separation of string into substring at specified delimeter in C(Line parsing)

In writing a program , we may reach to a situation where we need to read the string and seperate the string depending upon certain symbol or delimeter. Here I have written a simple program to parse the string with new line character.

Requirement:

let's say I have a string as "this \n is  \n a \n test \n program" and I need to read the string and seperate the string. To acheive this, we have a strtok function included in string.h.

Source code:
#include <stdio.h>
#include <string.h>


int main()
{
	char *token, *remstr=NULL ;
char str[] = " this \n is \n the \n test\n program";
token = strtok_r(str,"\n",&remstr);



        

		while(token != NULL)
		{
		
		    printf("here i=%s\n",token);
		    printf("remstr=%s\n",remstr);

		    token = strtok_r(NULL, "\n", &remstr);
		
		}

		return 0;

}

strtok function takes the string and the seperation symbol and this function scan the seperator and save the seperated sub string at token .  At remstr the remaining string is stored and the loop is repeated until there is substring at the remaining string. The loop is repeated until token has null value. When the last substirng is reached, the strtok function will produce the null value and this null value is the indication of end of string.

Note: At the end of string , the remaining string will store a null value in mac where as in ubuntu/linux the empty string is stored.

similarly we can seperate the string to sub string depending upon different seperator as per our requirement  in the program using strtok or strtok_r function included in string.h header.


In large program , we may come across the situation that we need to accumulate the seperated token or substring in to the array of string  and return the array of substing to the main calling function to perform the specific task for each substring.

for accmulation of substring , I have used the list of glib library.

source code:
#include <stdio.h>
#include <string.h>
#include <glib.h>

char *col_trim_whitespace(char *str)
{
  char *end;

  // Trim leading space
  while(isspace(*str)) str++;

  if(*str == 0)  // All spaces?
    return str;

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace(*end)) end--;

  // Write new null terminator
  *(end+1) = 0;

  return str;
}


GSList* line_parser(char *str,GSList* list)
{


        
        char *token, *remstr=NULL ;
 
		token = strtok_r(str,"\n",&remstr);


		while(token != NULL)
		{
			if(token[0] == ' ')
			{

			token = col_trim_whitespace(token);
			if(strcmp(token,"")==0)
		         {
		             token = strtok_r(NULL, "\n", &remstr);
		              continue;
		          }
		    }

		    list = g_slist_append(list, token);
            token = strtok_r(NULL,"\n",&remstr);
            
             


		}


        

		
		return list;


}

int main()
{
	

 int *av,i,j,length;
 i=0;


char str[] = " this";

 GSList* list = NULL;

 
GSList *list1 = line_parser(str,list);
// printf("The list is now %d items long\n", g_slist_length(list));
 length = g_slist_length(list1);
for(int j=0;j<length;j++)printf("string = %s\n",(char *)g_slist_nth(list1,j)->data);
return 0;
}

Thursday, April 2, 2015

creating a GCC shared library in linux and accessing the shared library in C/C++

A library is a file containing compiled code from various object files stuffed into a single file.  A library can be of two types:

1.     Shared Library
2.     Static library

1.   Shared Library:


Shared Libraries are the libraries that can be linked to any program at run-time. They provide a means to use code that can be loaded anywhere in the memory. Once loaded, the shared library code can be used by any number of programs.

 2.   Shared Library Names:


Every shared library has a special name called the “soname”. The soname has the prefix “lib”, the name of the library, the phrase “so'', followed by a period and a version number that is incremented whenever the interface changes .

Eg libtest.so, libtest.so.1.1

3.   Placement in File System:

There are mainly three standard locations in the filesystem where a library can be placed.

·      /lib
·      /usr/lib
·      /usr/local/lib

we can even use the non standatd library location. In that case the path should be added to the LD_LIBRARY_PATH

1.   How to create the Shared library with GCC  in linux


Step 1:Let us suppose a simple code  shared.c
int a(int b)
{
  return b+1;
}

int c(int d)
{
  return a(d)+1;
}




Step2:  compile our library source code in to position independent code(PIC)

          gcc –c  -Wall –Werror –fpic  shared.c

       Here libtest.so is the name of the shared library



Step 3: create a shared library from object file

     gcc  -shared –o libtest.so  shared.o

Step 4: making the library available at runtime using LD_LIBRARY PATH

     export LD_LIBRARY_PATH=/home/username:$LD_LIBRARY_PATH

Here /home/username is the sample path to the shared library. This should be
different as per the location of the shared library

Step 4:  create a  file that uses the shared library name test.c

     
#include 
#include 
#include 

typedef int (*pointer)(int b);


int main()
{
int b,d;
void *lib;
 pointer calc;
  lib=dlopen("libtest.so",RTLD_LAZY);
   if (!lib)
 {
  printf("failed to open libtest.so: %s \n", dlerror());
  exit(1);
 }


  calc= (pointer) dlsym(lib,"a");
  b= calc(2);
  calc= (pointer) dlsym(lib,"c");
  d= calc(2);

  dlclose(lib);


  printf("b is %d d is %d\n",b,d);
  return 0;
}

Here  the above program uses the <dlfcn.h> library to open the shared library  libtest.so , locate the symbol and call the function from shared library.

dlopen() function opens the shared library and dlsym() looks up a symbol in a shared library.

Wednesday, March 25, 2015

source code of reading json configuration file from command line in python

In many application , we want to read a file as a configuration file from command line . here I have written a source code  to read json configuration file in python


source code:
#!/usr/bin/env python

from optparse import OptionParser
import re
import json
import collections

def utf8(data):
    """Encodes the given text as utf-8.
    Returns a string of bytes.
    """
    if isinstance(data, str):
       
        return data
    elif isinstance(data, unicode):
        
        return data.encode("utf-8")   

    return _modify_children(data, utf8)

def _modify_children(data, operation):
    if isinstance(data, collections.Mapping):
  
        return dict(map(operation, data.iteritems()))
    elif isinstance(data, collections.Iterable):
        
        return type(data)(map(operation, data))
    else:
        
        return data

     


def main():
    parser = OptionParser(usage="usage: %prog [options] filename",
                          version="%prog 1.0")
 
    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.error("wrong number of arguments")


    with open(args[0]) as f:
      data = re.compile("^\s*//.*$", re.MULTILINE).sub("", f.read())
    

    print "**** DATA  *********"
    print data

    


    valid_data = json.loads(data) 

   
   
    # print valid_data 

    # print valid_data["jobs"][0]
    # print valid_data["jobs"][1]

    new_data = utf8(valid_data)




    print "********* unicode encoded data *********" 

    print new_data





if __name__ == '__main__':
    
    main()
here I have used python library optparse to parse the command line argument in our python code. This library helps to read the configuration file mentioned in command line. the json .loads is used to decode the json data to unicode then is again encoded to the python string. To encode the json file , the utf8 function is created. this utf8 function Encodes the given text as utf-8 and returns a string of bytes.

python source code to Convert dictionary / list of strings from Unicode to python string

while using a unicode, we can come to the situation that we have data in unicode and are supposed to convert in ASCII. Here I have written a simple python code to convert dictionary from unicode to ASCII.

in using unicode, if we have simple unicode data as a= u"hello". Then we can easily use a.encode('utf-8') and we can get the desired result in python string. However if we have data in dictionary or tuple or list then in such case we cannot use encode as before .

Source Code:


#!/usr/bin/env python

import json

def convert(input):
    if isinstance(input, dict):
        return {convert(key): convert(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [convert(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input



data={
    "books": [
        {
            "id": "1",
            "name": "Mathematics",
            "type": "Engineering",
            
            "run_at": {"day": "*/1", "second": 5},
            "start_date": "2011-12-21 17:00:23",


         
            "interval_type": "day",
            "timezone": "Asia/Kathmandu"
        },
        {
            "id": "124",
            "name": "Data Mining",
            "type": "Engineering",
            "run_at": {"second": 0},

           
            "interval_type": "day",
            "timezone": "Asia/Kathmandu"
        }
    ]
}

test = json.dumps(data)
valid_data = json.loads(test)
final_data = convert(valid_data)
print final_data




data1= [ { 'a':'A', 'b':(2, 4), 'c':3.0 } ]
test1 = json.dumps(data1)

valid_data1 = json.loads(test1)

final_data1 = convert(valid_data1)

print final_data1


here I have a dictionary and tuple data type and first I encoded to unicode by using json.load . Later I have writted a convert function which takes a unicode dictionary data then it encodes in to the python string.

Monday, March 23, 2015

Installation of CMake and using cmake for simple C program for creating of makefile

Installation of makefile and  using cmake for simple C program for  creating of makefile

Makefile is a file which tells how to compile and link a program. The instruction of compiling a source file , including library file and linking the file to produce the final binary file is written in Makefile. In Linux based system , If we are using an IDE then makefile is created by IDE. However if we are not using IDE and simply compiling and linking through command line, in such case we need to create MakeFile. CMake is a tool used to easy generation of cross platform Makefile.


here I have presented the use of Cmake to create a MakeFile in simple ways. The following procedure are tested in Linux/Mac OS.

1) Installation of CMake:

first install CMake. It is available in all the platforms. In mac, linux Cmake-gui is also available with GUI feature available. Be sure that command line feature is also installed along with GUI in linux and Mac OS.

Just type cmake to ensure that cmake command line is available in linux and mac.


2) creation of simple C project file  named cmake.c

 first let us create a simple C file as
#include <stdio.h>



int main()


printf("this  is the test file");


2) create CMakeLists.txt along with source file

After creation of source file , next we need a CMakeLists.txt file. This file is used by the Cmake to create a Makefile.

cmake_minimum_required (VERSION 2.6)

set(TARGET learn)

set(SOURCE cmake.c)



add_executable(${TARGET} ${SOURCE})

message("Success")




here we set learn as TARGET and cmake.c as SOURCE  and we want our makefile to create a executable file named as learn .

3) Generation of Makefile

first create a new folder and name it "build" so that all the file generated by Cmake are placed here. This new folder is not a compulsary one but is created to manage the files.

This makefile can be generated in two ways . Either by cmake-gui or command line

a) using GUI

 first open the gui of cmake . then there is input fields as "where is the source code"
 and where ti build the binaries. Just browse to the source code folder in the first input field and browse to the recently created build folder in the later input box.

 then finally press the Configure and Generate button of the GUI.

 then after this makefile is created in the build directory. make sure to see it.




 b) using command line

 first move the the build directory.
 then  input the command
   cmake ..

   this will create the makefile in the build folder.



4) running of MakeFile recently created

   then move to the folder build as MakeFile created is placed here.

   run the command

    make

    this will create the binary file learn as we have named our binary to be learn in earlier CMakeListes.txt at the start.

    5) so run the executable as

      finally move to the folder inside build where learn executables is created and run the command

      ./learn

      wow we get the output.