Thursday, June 11, 2009

Little Sugar: Useful commands while programming on Unix Systems

Here are a list of commands that re use file while programming on unix systems

pid = process id

ps aux | grep process_name
- to search for a given process name , generally use this to fetch pid of process

lsof -p pid
- to get all the files or file descriptors being used by the process having pid

lsof | grep file_name
- to get the list processes using a given file

sockstat | grep process_name
- to see the socket connections between a host and desinations

strace -p pid
- to see what the process is doing in general

nc hostname port
- to see data flowing from the hostname at the given portu

Tuesday, June 09, 2009

Little Sugar: Things to remember while creating a daemon

While writing a daemon on unix systems. The daemon should not be attached to any
terminals. So make sure the following things hold valid.

chdir '/'

umask 0

Map STDIN to /dev/null
Map STDOUT to your logging system
MAP STRERR to STDOUT

setsid # Make the daemon a session leader

Wednesday, October 15, 2008

use find magic to create etags

To create a TAGS file so that you can work with emacs / vim use the following command

find . -ipath '*.p*' -print | etags -

the above command for example will create etags for all the pl , pm files in the current directory

Saturday, September 27, 2008

Little Sugar:Decreasing capacity in C++

When you use vector,string class in C++, the problem that happens is that the capacity just increases and does not decrease, causing the data structure to hog lot of memory.
For example, say in the vector 10 elements were added , then to the same vector 1000000 elements were added. Then 900000 were deleted. This will not cause the capacity to decrease. This might result in the vector still holding on to a lot of memory.

One way to fix this is the sap trick.

vector < int > elements; // the original vector

vector < int > (elements.begin(), elements.end() ).swap(elements)

Wednesday, August 13, 2008

vector::assign

"assign" is a method in STL for the vector class. When ever you need to erase the contents of the vector and replace it with totally new contents use the assign member function .You should use the operator= then all elements of the right hand side container would be copied to the container on the left hand side.

e.g

v1.assign(v2.begin() + v2.size()/2 , v2.end())

Thursday, June 05, 2008

C++ : std::swap and template specialization

say you want to use the swap method provided in std namespace for your own class . Then instead of using the std::swap option blindly , that would involve making use that your class has at least a copy constructor and that the assignment operator is overridden.

It makes more sense to use template specialization for std::swap

class MyClass {
public:
void Swap(MyClass &) ;
};

namespace std {
template<> swap(MyClass& a, MyClass& b){
a.Swap(b);
}
}

so that way we just tune the default swap to use our class specific Swap and things become fast and simple for us .

Wednesday, June 04, 2008

C++ : std::mem_fun

Say you have a class

class MyClass {
public:
int DoSomething(){
}
};

now say you have

std::vector classes;

you can use something like this

for_each(classes.begin(), classes.end(), &DoSomething);

where DoSomething is

int DoSomething(MyClass& e){
d.DoSomething();
}


to call the member function DoSomething rather than the wrapper function use function calls like these

for_each(classes.begin(), classes.end(), mem_fun_ref(&MyClass::DoSomething));

if the classes vector was defined something like this

vector classes

then you would use something like this

for_each(classes.begin(), classes.end(), mem_fun(&MyClass::DoSomething));

C++ : Template specializations

Assuming you have a piece of code that is templatized and looks like this

template
void prettyPrint(T value, char* buf);

now assume that you are using sprintf for formatting the input .

that being the case you can use template specializations like this :

template<> void prettyPrint(int value, char* buf){
sprintf(buf, "%d", value);
}

template<> void prettyPrint(char value, char* buf){
sprintf(buf, "%c", value);
}

Tuesday, June 03, 2008

C++: copy magic

Say if you have a vector and you want to print it . Then instead of the normal for loop and cout call inside the loop you can do the following :

if you have a vector "v"

copy(v.begin(), v.end(), ostream_iterator(cout, "\n"));

this will print the entire vector .

To generalize this you could use something like this :

template
OutputIterator copy(const Container& c, OutputIterator result){
return std::copy(c.begin(), c.end(), result);
}

C++ : pragma warning

if there is a header file after including which you start getting warnings , and especially if that header file is a third party header file , its better to wrap the header file with your own custom wrapper .

#pragma warning(push)
#pragma warning(disable:line_number_causing_warning)
#include
#pragma warning(pop)

Thursday, May 22, 2008

C++ : Little Sugar

In C++ when ever you see a function that accepts a const reference than its a valid candidate for temporaries . Temporaries are objects that are created and destroyed whenever there is mismatch in function arguments and a constructor exists that takes the passed argument and converts it to a destination entity via the constructor .

C++ : Little Sugar

mutable keyword is useful in C++ , when you are changing a member variable in side a constant function . A simple way to remove constantness of the "this" pointer is to use code like this

const_cast(this)

C++ : new operator and operator new

The new operator in C++ is something that cannot be changed . For example
when you use code something like this ,

string *ps = new string("Memory Management");

the new operator is used . Its sole purpose is to allocate memory and initialize it.

The new operator in turn uses the operator new to allocate memory which can be overloaded.

its prototype looks like this :

void * operator new(size_t size);

there is another version of new operator called the placement new , that is used to create objects in pre initialized memory. example usage for it looks like this :

string *ps = new(memory) string("Memory Management");

same is the case for delete operator and operator delete

operator new[] is another type of operator that can be used to allocate new arrays

Tuesday, May 20, 2008

C++ : Little Sugar

While creating objects in C++ , in order to initialize objects use the member initialization list. When initialization of a class starts , initialization of its members happens . If the member initialization list is not used the default constructor of all the class members is called even before entering the constructor . Once inside the constructor the copy constructor or operator = is called to initialize the member objects .

On the other hand if member initialization list is used only the copy constructor is called once and hence you prevent the over head of an extra call.

Monday, May 19, 2008

C++ : Creating Objects

Here are 2 simple rules to allocating and deleting objects.

MyObject * myPointer;

while updating object memory always use code like this:

MyObject::update(){
delete myPointer;
myPointer = NULL;
myPointer = MyObject::CreateNew();
}

while deallocating always use code like this:

MyObject::~MyObject(){
delete myPointer;
myPointer = NULL;
}

Tuesday, April 29, 2008

Refactoring Large Methods: Refactoring

Refactoring Large Methods:

"The object programs that live best and longest

are those with short methods. Programmers new to

objects often feel that no computation ever takes

place, that object programs are endless sequences

of delegation. When you have lived with such a

program for a few years, however, you learn just

how valuable all those little methods are. All of

the payoffs of indirection—explanation, sharing,

and choosing—are supported by little methods" -

Refactoring Book - Martin Fowler

Large Methods are code smells.To refactor large

methods follow the following methods :

-> Use extract method refactoring to extract a

lot of small methods

-> In case of a method having a number of

temporary variables , temporary variables can be

replaced by query methods

-> A query method is a small method that is

intended to replace variables .

e.g int myVariable = oldValue1 * oldValue2

create a new method like

int getValue(){
return oldValue1 * oldValue2;
}

now replace all usages to myVariable by the
method getValue()

-> Then try introduce Parameter Object

refactoring to take care of huge number

parameters in the extracted method

-> Use Preserve Whole Object Refactoring in case

lot of parameters are passed to methods , and

each of these parameters are local values.

-> If still extract method refactoring becomes

difficult use "Replace method with Method Object"

refactoring

Sunday, April 27, 2008

QuickSort : C++

i was having a re look at quick sort.

Here is the code in c++ :


template< class T >
int partition(T a[], int p, int r){
T x = a[r];
int i = p - 1;
for(int j = p;j < r;j++){
if(a[j] <= x){
i++;
swap(a[i],a[j]);
}
}
swap(a[i+1] , a[r]);
return i + 1;
}


template< class T >
void quickSort(T a[], int p, int r){
if(p < r){
int q = partition(a, p , r);
quickSort(a, p , q-1);
quickSort(a, q+1 , r);
}
}


The idea of quicksort is to take an array and divide it into partitions .
First a key is chosen . That is called the pivot . Here 'x' is the pivot .
Based on the value of 'x' other values in an array are put in 2 partitions .
One partition that contains values less than 'x' and other partition contains values greater than x .

Here i and j are used to mark the extent of these 2 partitions .

The beauty of the algorithm lies in the fact , how integers are used to manipulate partitions . 'i' is initially set to value that precedes a real boundary . 'j' is set to the first location in the array . Now as values are compared with 'x' ( the key)
if value is less than 'x' the partition extent marked by 'i' are increased , else the partition extent marked by 'j' is increased . In the first case where values of 'i' is less than 'x' and since 'i' now occupies what 'j' occupied the values at those indices are swapped .

the partition method does in place sorting of the array and the quickSort method is responsible for choosing partitons .

Sunday, April 13, 2008

C++ : template specialization

template <>
char* Add<char*>(char* a , char* b){
return strcat(a,b);
}

char * res = Add<char*>("foo","bar");

This code refers to a new type of syntax for templates called template specialization syntax.
Generally when you write code for templates .

you end up using stuff like

template<class>

but say you want the same generic code for many cases . In the above mentioned code for example if the add function used the "+" operator to add two types it would have not worked for char* pointers , because the "+" operator does not work with them .

by using the syntax as mentioned above its possible to tell the compiler that there are exceptions to your generic code and that for special cases these new methods should be called.

C++ : The need for virtual destructors

With the advent of object oriented languages the use of polymophism became very common .
In C++ when you have a derived Class and a base class .

when you have code like this :

class Base {
};

class Derived : public Base{
};

Base * p = new Derived();

delete p;

what's wrong with it .

Since this piece of code is based on polymorphism , the base pointer will refer to an instance of a derived class object .

when delete on the pointer p is called , due to static typing in c++ , destructor of Base is called , instead of Derived . To correct this

virtual ~Base(){
}

should be added . By making the destructor virtual the destructor of the derived class would be called now .

Saturday, April 12, 2008

Refactoring : Self Encapsulate Field

Some times in a code base , especially inside a class , a field is referenced from many places.
Say you decide to move this field to another class .

A clean way of doing this is to first extract a getter method for that field within the same class .
Now with all occurances replaced by the getter method , move this getter method to the new class .
Similarly replace the code where the field is being set by the appropriate setter code and then move the setter code to another class .