Tuesday, January 26, 2010

Adding feedback loop to your applications

These days everyone is talking about smart applications.

One very simple feature that smart applications have is measuring user interactions.
Learning from user interactions and acting in a more personalized manner towards the user.

User interaction can mean different things for different applications. Here i am going to talk about one popular user interaction metric.

"Time spent by a user on a given feature"

Assuming you have some way of measuring the time spent by a user on a given feature. You can calculate the average time spent by a user and compare it with the time spent by other realistic users by using some statistics.

Assuming you have a list of users and their corresponding time's spent on the feature.
You can calculate the mean time for the list.

Lets call this mean_time.

You can also calculate the standard deviation for the list.

Lets call this time_range_delta

you actual time_range interval is then (mean_time - (time_range_delta * range_factor), mean_time + (time_range_delta * range_factor))

where range factor is the amount spurious information you are will to tolerate a range of [1-3] for this factor is generally considered good.

once you have this range interval, you can ignore all times that fall outside this range interval.

this will give a new list, from which you can calculate the mean and standard deviation again.

By following this process iteratively you can get the actual list of genuine users and their corresponding times.

Calculating the mean of this list will give the average time spent by the user.

You can then classify any user by using this average time.

Monday, September 14, 2009

Little Sugar: Creating a device node

To create a device node use mknod

mknod /dev/mem c 1 1

here the device name is /dev/mem

c represents character device this can be block device also

the first 1 represents the major number
the second 1 represents the minor number

Sunday, September 13, 2009

Little Sugar: FreeBSD total RAM

to find out the total RAM installed on your FreeBSD box use something like this

sysctl hw.physmem

Thursday, September 10, 2009

Little Sugar: insmod

Linux kernel extensions have a .ko extension are inserted directly into the kernel
using insmod command.

The kernel modules are removed using rmmod.

Kernel modules are generally placed at /lib/modules.

To update kernel dependencies run depmod

Wednesday, September 09, 2009

Finding Document Similarity

If you need to find how similar a document is we can use vector algebra to our advantage. If we have 2 document d1 and d2 then

Let D1 be a vector of the word-frequency of the document d1
Let D2 be a vector of the word-frequency of the document d2

then the deviation of the 2 documents can be calculated by

using the fact that

cos(theta) = (D1 * D2)/(N(D1) * N(D2))

where N(D) is the normalized vector represented by

N(D) = sqrt(D * D)

Wednesday, September 02, 2009

OpenGL: Diffuse, Specular, Ambient, Emissive lights

In the OpenGL world there are different types of light types

Diffuse
--------
These type come from one direction bu are scattered equally in all directions.

Specular
--------
This type of light comes in one directions and is also bounced off in one direction

Ambient
--------
This type of light source comes from different light sources and is also scattered in different directions

Emissive
---------
This represents light originating from the object

So in general A light source has two types of properties associated with it
LR,LG,LB => the RGB components that make up the light and
MR,MG,MB => the RGB components that are reflected away
Hence the net effect of the RGB is given by a vector

(LR.MR, LG.MG, LB.MB)

if light is coming from two or more sources the light is added and next effect is
of the form

(R1 + R2, G1 + G2, B1 + B2)

Tuesday, September 01, 2009

Opengl : Hidden Surface Removal and LIghting

Hidden surface removal is a common technique in the graphics world. The technique says
we should draw only parts of objects that are visible to the user.

What support does OpenGL have for hidden surface removal.OpenGL supports hidden surface removal through a combination of DEPTH BUFFER and COLOR BUFFER.

Depth Buffer and Color Buffer
------------------------------
Our screen is flat basically we see a flat 2D rectangular screen made up of pixels. Associated with these pixels we have a corresponding value in the Depth Buffer and
Color Buffer. So what pixel appears forward or backward depends on its value in the depth buffer. The color value it shows depends on its value in the color buffer.

to enable the depth buffer we need use something like the following:

glClear(GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT);

Material And Ambient Light
---------------------------
OpenGL understands RGB. A material quality decides the amount of RGB that is reflected or absorbed. An area can be lit by many light sources.Say in a room the bulb can the primary source of light.But there might be light reflected from walls which can be called secondory sources, the light contributed by such sources is called ambient light.

ps options

If you invoke the ps command like this

ps -C -o etime,pid,pri,cmd

this will show processes that match the command name and show output using the
fields followed after -o i.e

etime - how long the process is running
pid - the pid of the process
pri - priority of the process
cmd - the full command line of the command

Sunday, August 30, 2009

Looking back at mergesort

For mergesort the recurrence relation is

T(N) = 1 if N == 1
T(N) = cn + 2T(N/2) if N != 1

so if we draw the recursion tree for such a recurrence relation we get
Height of tree = lg N
Number of leaves = N
--------------
Leaves at level 0 -> 1
Leaves at level 1 -> 2
Leaves at level 2 -> 4
Leaves at level 3 -> 8
...
Leaves at level lg N -> N

Total Work Done
----------------
Work done at level 0 -> cn
Work done at level 1 -> cn
Work done at level 2 -> cn
....
Work done at level lg N -> cn

So total work done => cn * lg N => O(n lg n)

Similarity between objects

Lets say we need to find the similarity between people based on how they rank different items. Based on the that collected data we need to recommend some new
items to the users.People who are similar to each other have a higher likelihood of
liking things that we recommend them.

Now lets consider a Set of Users.A Set of Items and a set of Rankings which users give to these Items.

Given this information how can we find the similarity between 2 Users.

Approach 1)
------------
Take user A and user B
Calculate union of items chosen by user A & B , call it A_UNION_B
Calculate the intersection of the items chosen between A & b, call it A_INT_B
then the value A_INT_B/A_UNION_B represents the similarity of the 2 users A and B

Approach 2)
------------
For every item that is common between A & B we can calculate the Euclidean distance between the rankings of the 2 items.
D = RA (ranking A gave to an item) - RB (ranking B gave to an item)
Sum = Sum + D^2

The once we have the sum we can call it Similarity Sum and use a formula
like

Similarity = 1/(1 + Sum)

The 1 is added to prevent the 1/0 off case, where our magic factor factor is 1
we can choose an arbitrary magic factor say N

Then Similarity = N/(N + Sum)

Approach 3)
-----------
Use the Sum that we got in Approach 2 above
Similarity = Sum / N where N is the number of items common between A and B that have the same rating
Similarity = Sqrt(Similarity)
then to make Similarity fall between the range 0 and 1

Similarity = 1 - tanh(Similarity)

Approach 4)
-----------
Use the Similarity that we calculated in Approach 3
NN = Number of items common between A and B
Similarity = Similarity * (N / NN)

Wednesday, June 17, 2009

Little Sugar: Writing an oscillator function

Say you need to transform values v1, v2 in such a way that they lie between lowerlimit L and upper limit U

then u can use an oscillator function

new value = U - (L + (U * (1 / (1 + value))))

this new value will be between L and U, if u omit L then new value
would be between 0 - U

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 .

Refactroing : Handling Duplicate Code

In legacy code bases we see lot of duplicate code . so how do we handle it ?

I am assuming you are using a tool that supports refactoring . In that case ,

Case 1:

If in a class you have lot of repeated code , use extract method refactoring to move the repeated code into a common method inside the class . Now replace if not automatically all occurance s of the repeated code with the call to the newly created method.

Case 2:

You have 2 sibling classes that have same piece of code .

Use extract method to create method with the same name in the 2 classes . Then use pull up refactoring to pull up the common method now in a super class . If the super class does not exist create it now .

Case 3:

You have 2 sibling classes that have almost the same piece of code , but some different bits here and there .

Use extract method to create method with the same signature in both the classes . Then identify the parts that are different , extract these different parts into methods of their own . Make sure that the names of these different parts is same in both sibling classes.

Now use template method design pattern , to create a common method in a super class of these 2 siblings . Using polymorph ism and inheritance to implement the different methods in the sibling classes.

Tuesday, April 08, 2008

C++: Object slicing and pass by value

In C++ , when a object is passed by value to a function that accepts a parameter then object slicing might happen. Consider the following class

class Base {
public:
virtual const char * toString() throw();

};

class Derived : public Base {
public:
virtual const char* toString() throw();
};

Derived derived;
Base base;

void doSomething(Base base){
....
}

doSomething(base);
doSomething(derived);


now we have 2 classes Base and Derived with a common virtual function that have been overridden in the derived class . We create 2 objects "derived" and "base".

Both of them are passed to the function doSomething . What happens in this case .

In the first case , it works the way its supposed to . In the second case , object slicing takes place and the members that are just of derived class are chopped off and the virtual function of the base class is called.

Monday, April 07, 2008

C++ : pointer to member function

class Foo{
public:
int iVal;
int Bar(int);
};


int Foo::* pm;

is a pointer to a member variable that is an integer.

pm = &Foo::iVal;

is used to initailize a pointer to a member variable

Foo foo;

int i = foo.*pm

is used to retrieve values of the pointer to member variable

int (Foo::*pmf) (int) = &Foo::Bar;

is a pointer to member function that is initialized by the address of member function Bar

C++ : Preventing implicit type conversion

class Foo{
public:

Foo(int n ){
...
}

};

Foo foo(42);
Foo boo = 42;

In the above mentioned snippet , the first constructor is matched and called. In the second case , for the assignment operator since the right hand side is 42 and since we have a constructor that takes integer as an argument . The corresponding constructor is called . This is syntactic sugar that can lead to lots of problems . To prevent something like this .

the explicit keyword should be used in front of constructors .

Wednesday, April 02, 2008

C++: Rethrowing exceptions

Consider the following piece of code

catch (Base& w)
{
...
throw;
}
catch (Base& w)
{
...
throw w;
}

What do you think is the difference between the 2 approaches above .

In the first case , the exception is re thrown . In the second case a copy is made and a new exception is thrown . Also the copy is based on the static type i.e
Base (copy constructor is called )

C++ : Object Copies in C++ are based on Object's Static Type Not Dynamic Type

Consider the following piece of code

class Base { ... };
class Derived: public Base { ... };

void passAndThrowDerived()
{
Derived local;
...
Base& rw = local;

throw rw;

}


In the above mentioned case . When a copy of rw is made while throwing it .
The copy constructor for the type is called . In this case the since rw is a reference to Base there fore the copy constructor of Base is called rather than the
Copy Constructor of Derived class.

C++ : Why are objects thrown as exception always copied

When an exception is thrown , the objects are generally copied. To explain this consider the following :

{
MyObject myObject;
cin >> myObject;
throw myObject;
}

if the object myObject was passed by reference then the same myObject would be thrown out . If the same object is thrown out then as soon as it goes out of scope , its destructor would get called and as a result of which some garbage would finally reach the exceptional handling code .

It is for this reason that copies of myObject are thrown rather than the original one .

Monday, March 24, 2008

Little Sugar : C++

In C++ have you imagined what would happen if the destructor of your class throws an exception . For starters , the object would not get destroyed properly . Actually in reality the control would go back to the callee from the current point directly.

Alright , now think what would happen if the destructor got called as a part of some exception handling code and this destructor threw an exception .

Since the active callee is calling the destructor due to some raised exception .
it would result in the terminate() function getting called and though would terminate the program immediately

Sunday, March 23, 2008

ThoughtWorks: Why it should be your first Software Company ??

ThoughtWorks , should be your first software company because:

You will learn..

  • What good software design is all about. You will hone the skills that will enable you to write good solid beautiful code .
  • Good coding practices e.g ( Test Driven Development .. )
  • To re factor code properly and effectively .
  • How to test your code like crazy
Other reasons why you will love Thoughtworks..

  • People adore Ruby and Python ;) and use them for their project work
  • Fellow developers try out cool and technologies like Erlang and haskell and incite you to try something or do something different.
  • Free Food
  • XBox , PlayStation
  • Table Tennis and other games .
  • Cool outings and free booze ;)
  • Amazing people from whom you 'll learn like crazy almost everyday , till the next 1.5 yrs
  • You can play pranks on the CEO and he wont fire you .
And finally an average ThoughtWorker with 1.5 yrs of work experience = most of the Software Engineers with 3.5 yrs of experience .

So if you want a head start , ThoughtWorks is the place to be ;)


Thursday, March 20, 2008

Java Thread Programming : Using Semaphores

The java concurrent framework provides Semaphore . Semaphores are useful when the end user wants to implement some kind of resource pool.

In a semaphore permits can be acquired and released . A semaphore when created can be initialized with the number of entries it can contain at any point of time .

Semaphore s = new Semaphore(N);

// acquire a permit

s.acquire();

// release a permit

s.release();

Java Concurrent Programming : CountDownLatch

CountDownLatch in the concurrent programming framework provided by java is pretty cool.
In principle it works like a binary latch . (Once set it remain in that state for ever )

So when would something like a countdownlatch be useful for thread programming .

Consider a scenario , you have a big task T to be done by N threads .

1) Now you want all the threads to be started at the same time so that they get equal opportunity
to participate in the completion of the task .

2) You want your main thread to do something when all the threads finish .

You can create two CountDownLatch objects.

CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch endLatch = new CountDownLatch(N);

Then you can construct all the threads like this

Thread thread = new Thread(){
public void run(){
try{
startLatch.await();
// do the task
endLatch.countDown();
}catch(InterruptedException e){
Thread.currentThread.interrupt();
}

}
}


thread.start();

so when the thread starts it will block cause of the CountDownLatch (await method call)

when startLatch.countDown() is called the latch opens and all the threads can flow now and start working .

similarly the main thread that is waiting for all threads to finish .

will continue when all the threads have called endLatch.countDown()

Monday, March 17, 2008

Eclipse Plugin Development : Small nuggets

Small snuggets for eclipse plugin development are small snippets of code useful in eclipse plugin development.

In eclipse windows that you see contains pages . Each of this page hosts a view or an editor .
Generally these editors are not hosted directly but indirectly via references ( aka proxies to the actual editor / views )

So to get reference to the actual editors / views from the pages use code like this :

IWorkbenchPage page = getPage();
IEditorReference[] editors = page.getEditorReferences();

Once you have the references you can get the actual hosted editor / view.

Editors in eclipse implement IEditorPart , so to get an editor some thing like this would work:

IEditorPart editor = editor.getEditor(true);

To reveal IJavaElement in the editor ( basically any java method , entity ) using JDT ( eclipse for java development is based on it )

JavaUI.revealInEditor(part , javaElement);

To add an action (aka tool bar item ) in the toolbar for your view something like this would work :

IActionBars actionBars = view.getViewSite().getActionBars();
IToolBarManager manager = actionBars.getToolBarManager();
manager.add(new MyToolBarItem());

Thursday, March 13, 2008

Eclipse Plugin Development : Programatically saving all open editors

In Eclipse editors are contained in WorkbenchWindow . To save all open editors one can call code like this

IWorkbench workbench = PlatformUI.getWorkbench();
return workbench.saveAllEditors(false);

This will get the current workbench and save all open editors.

Sunday, March 09, 2008

Java : Inner Classes and Parent Reference Escaping

When an inner class is created inside a class in java, it transparently contains a reference to its parent class. If by chance this reference leaks out , it compromises the thread safety of the parent class. To avoid these kind of issues , factory methods should be used to create inner classes .

Another thing that should be best avoided is : starting of a thread inside the constructor of a class.
Since the thread object also shares the reference to its parent class, this reference might be in an inconsistent state when the thread is started .

To prevent these type of scenarios factory methods are best.

e.g

public class Prent {

private childThread;

private Parent(){
childThread = new Thread();
}

public static Parent newInstance(){
Parent parent = new Parent();
childThread.start();
return parent
}

}

Monday, March 03, 2008

Eclipse : Adding nature to a project

In Eclipse plugin development terminology adding a nature to a project is like tagging the project with a specific tag . Generally natures are used to install various builders for the project. I will talk about builders in a later post . Lets look at some code and see how how natures are added to projects:

IProjectDescription projectDescription = project.getDescription();

description is a description of the project . It gives a lot of information including the entire list of
nature ids and build commands.

String[] ids = projectDescription.getNatureIds();
String[] newIds = new String[ids.length + 1];
System.arraycopy(ids,0,newIds,0,ids.length);
newIds[ids.length] = YOUR_NATURE_ID;
projectDescription.setNatureIds(newIds);
project.setDescription(projectDescription,null);

the remove nature id code is kind of similar .

To actually implement your nature , you need to contribute to the extension point
org.eclipse.core.resources.natures

Basically that boils down to adding something like this in your plugin.xml

id="yourNatureID"
name="Your Nature Name">







"id" here represents the id of the nature .
"name" represents the name of the nature .
"class" represents the class implements the IProjectNature .

the requires-nature here represents the nature id that is required for this nature to be successfully installed .

Next , finally the class that implements the IProjectNature interface.

public class YourProjectNature implements IProjectNature {
IProject project;
public YourProjectTestNature() {
}
public IProject getProject() {
return project;
}
public void setProject(IProject project) {
this.project= project;
}
}

Sunday, March 02, 2008

Little Sugar : C++

The only to initialize const pointers in c++ within a class , is via member initialization list.

class MyClass{

Data * const data_ptr;

MyClass(Data * const value) : data_ptr(value)
{}
};

Tuesday, February 05, 2008

Remove from Array : Java Quickie

lets say you have a problem . You have an array of N numbers . You want to remove the i th number . Then you need a new array not containing the j th number . You are using java . How can you do it ??

Here 's a quickie:

int[] result = null;

result = new int[n-1];
if(i > 0 ) System.arraycopy(array,0,result,0,i);
if(i+1 < n ) System.arraycopy(array,i+1,result,i,n-1-i);

}

This is quick way of removing the element you need and getting a new array devoid of the removed number .

Thursday, January 31, 2008

Thnking in Heaps : Algorithms

An interative version of max-Heap :

void iter_maxHeapify(int * a,int rootIndex,int heapLength){
int largest = rootIndex;
int leftIndex = left(rootIndex);
int rightIndex = left(rootIndex);

for(int largest = rootIndex;
(leftIndex < heapLength) || (rightIndex < heapLength);
leftIndex = left(rootIndex),rightIndex = right(rootIndex)){

if(leftIndex < heapLength && a[rootIndex] < a[leftIndex]){
largest = leftIndex;
}
if(rightIndex < heapLength && a[largest] < a[rightIndex]){
largest = rightIndex;
}
if(rootIndex != largest){
swap(a[largest],a[rootIndex]);
rootIndex = largest;
}
}

}

Building the Heap:

void buildMaxHeap(int * a,int heapLength){
for(int i = heapLength/2;i >=0;i--){
maxHeapify(a,i,heapLength);
}
}


Sorting a heap:

void heapSort(int * a ,int heapLength){
buildMaxHeap(a,heapLength);
for(int i = 0;i < heapLength;i++){
swap(a[i],a[heapLength-1]);
maxHeapify(a,1,heapLength-i-1);
}
}

Tweaking JDT : eclipse

To create a new Java Class/Interface using JDT you can use the following code :

IJavaproject prj;
IPackage package;

prj.createType(package, "your class body");

To find subclasses of a given type using JDT use :

IType type = prj.findType("class name");
ITypeHierarchy typeHierarchy = type.newTypeHierarchy(prj,new NullProgressMonitor());
IType[] subclasses = typeHierarchy.getAllSubtypes(prj);



To check if the given class aka IType is part of this project

IType type;

IResource resource = type.getUnderlyingResource();

boolean isPartOfClass = resource.getProject().equals(project.getProject());

Marker Resolutions for markers : Eclipse

In Eclipse it is possible to associate marker resolutions with markers . This is more commonly known as Quick Fixes also evoked by using the key combination Ctrl + 1.

You need to implement the extension point with id :

"org.eclipse.ui.markerResolution"

for the markerType attribute under that extension point specify the marker id
you want to associate this resolution with .

Then in the "class" attribute specify the class that implements the MarkerResolutionGenerator

The world of wide characters aka Unicode

Wide characters aka unicode characters are characters that occupy 16 bits per character .
In C we have a header file specifically for that .



that contains special data type for that

wchar_t

wchar_t * text = L"Hello";

is used to tell the compiler that it should use 16 bit aka wide variants of characters.

strlen for wide characters becomes wcslen .

To take care of these problems windows provides TCHAR.H

it contains many functions starting with _t , like. ..

_tprintf


by defining _UNICODE

like

#define _UNICODE

its possible to use 16 bit / 8 bit versions of functions without much verbosity .

the same _t functions then correctly map on to their 8 bit and 16 bit counter parts.

Monday, January 28, 2008

Fnding markers in a workspace : eclipse

If you have a marker or you know a marker id :

let the id be : org.my.marker

then all markers of that type can be easily found . The way to found those markers is :

IWorkspaceRoot root = ResourcePlugin.getWorkspace().getRoot();
root.findMarkers("org.my.marker",false,IResource.DEPTH_INFINITE);

To create a marker :

getProject().createMarker("org.my.marker",false,IResource.DEPTH_INFINITE);

generally since workspace changes are expensive , an IWorkspaceRunnable should be used
to batch many workspace operations together .

IWorkspaceRunnable runnable = new IWorkspaceRunnable(){
public void run(IProgressMonitor monitor) {
IMarker marker = resource.createMarker(markerId);
setAttributes(marker);

}

};


the setAttributes method sets the marker . This generally boild down to populating a hashtable
and setting it .

resource.getWorkspace().run(runnable , null);

An imageProvider can be specified in the marker definition to define an image for the marker .

Sunday, January 27, 2008

Overloading the && , || , " , " operators : C++

&& , || and comma operator in C++ are very useful . && and || are useful in short circuiting code .
Now when you overload these operator at the global level or at the member level . Then at that case

an expression like

(exp1 && exp2)

gets transformed into something like

(exp1.operator&&(exp2))

that being the case , both the arguments exp1 and exp2 are evaluated . Hence since we are not
sure in which order the arguments are evaluated , short circuiting is thrown out of the window.

So commonsense says it makes sense not to overload the && , || and the comma operator .

Friday, January 25, 2008

Little Sugar (Trees : relations)

A complete binary tree has odd number of nodes .

Number of leaves + number of internal nodes ( both even) +
1 = number of nodes in a tree

The number of internal nodes + 1 = number of leaves

number of internal nodes = number of leaves - 1

n = number of nodes

n = number of leaves + number of internal nodes

n +1 = 2 * number of leaves

number of leaves = (n+1)/2

The number of total nodes upto height h :

= pow(2,h+1) - 1

The number of nodes for any binary tree at height (h) :

= ceil(n / pow(2,h+1))

Little Sugar (Trees : relations)

A complete binary tree has odd number of nodes .

Number of leaves + number of internal nodes ( both even) +
1 = number of nodes in a tree

The number of internal nodes + 1 = number of leaves

number of internal nodes = number of leaves - 1

n = number of nodes

n = number of leaves + number of internal nodes

n +1 = 2 * number of leaves

number of leaves = (n+1)/2

Sunday, January 20, 2008

type conversions : C++

Implicit type conversions in C++ can be quite problematic . To take care of type conversion issues , C++ provides us with a simple mechanism .

use the explicit keyword .

so for a class like Array

class Array{

public:
explicit Array(int size){
...
}

};

so by using the explicit keyword in this manner , you tell the compiler to use the constructor only
when explicit object construction is taking place.

another way around the explicit keyword is :

class Array{
public:
class ArraySize{
public:
ArraySize(int size)
this->size = size;
}

private:
int size;
};

Array(ArraySize size){
...
}
};

So by using the nested public ArraySize class in this manner , you 'll see that even if the compiler makes implicit type conversions for cases like

Array a(10);

the integer 10 is correctly transformed to ArraySize and the constructor having ArraySize as a parameter is called .

The beauty of this last technique is that it works in many cases , cause the compiler is allowed to make 1 implicit type conversion but now two.

Tuesday, January 15, 2008

Default Constructors : C++

Just imagine if your class does not have a default constructor and infact has one that accepts a parameter . In that case few things might not be possible . To illustrate

class Piece{
public:
Piece(int n);

};


Things like these will not work

Piece pieces[10];

Why?? -> cause u don t have a default constructor and trying to create an array of 10 piece instances just tries to call exactly that for every one of them .

Piece * pieces = new Piece[10];

wont work.

How to get it working :

Piece pieces[] = {
Piece(1),
Piece(2),
Piece(3)
};


Another way to get it working would be :

Piece * pieces[10];

: here you are just declaring an array of 10 Piece pointers;

Or Piece* *pieces = new Piece*[10];

But you still need to initialize all the pointers like this :

for(int i = 0;i < 10;i++){ pieces[i] = new Piece(i); }

Another way of initializing accomplishing this would be :

void * memory = operator new[](10 * sizeof(Piece));

this will create memory for 10 piece objects . Now we can go an and make the memory more specific to Piece :

Piece * pieces = static_cast<piece*>(memory);

Now that pieces points to memory for Piece , lets initialize the pieces with code like

for(int i = 0;i < 10;i++){ new(&pieces[i]) Pieces(i); }

Though this arcane technique will get the job done . It seriously is arcane . Not only that it also has the disadvantage of boilerplate code like this :

for(int i = 9;i >= 0;i--){
pieces[i].~Piece();
}

operator delete[] memory;

If we do not follow the 1st approach , we see that what problems we can face . A small hack to get around this problem would be :

class Piece{
public:
Piece(int n = Piece::UNDEFINED);
private:
static const int UNDEFINED;
};


const int Piece::UNDEFINED = -1;

Hello Windows Facts

windows.h is the mother of all other header files in windows . It includes other header files .

Windef.h => basic type defintions

winnt.h => type definitions for unicode support.

winbase.h => kernel functions.

winusr.h => user interface functions

wingdi.h => graphics device interface functions.

WINAPI => is a naming convention like __stdcall .

Moving Patterns

If you have a layer of objects and each object in that layer shares a certain set of methods . Those methods can be moved in a common super type . This super type that is common for a whole layer is called a layer super type .

Remote Facade is a facade for objects that are not part of a given process address space , in other words whenever you need to access objects that line in other processes you should use a remote facade to encapsulate and operate on remote objects via the facade . The facade make a number of operation invisible and may also cache the most commonly use objects.

When ever data has to marshaled across processes boundaries and lot of data needs to sent . A Data Transfer Object can be used . The parameters are packed into a simple POJO called a DTO and marshaled . On the server side , the server used some sort of assembler to break the DTO and set the corresponding properties on domain objects.

Friday, January 11, 2008

Floating in a Tree

If you have a priority queue setup of many nodes. Lets say we want to bring the node with the highest value to the top . IN orther words if i have given a heap than how do i modify the heap so that the biggest element is always present at the root.

One simple logic can be . Given a root node of a subtree .

  • Assume the root node is the largest node .
  • Now compare the value of root node with left child and mark the one with the bigger value as biggest
  • Then compare biggest with the right child now and make the bigger of the two as the new biggest.
  • now repeat the above mentioned steps with the new largest node
In terms of code this looks like :

void maxHeapify(int * a,int rootIndex, int heapLength){
int largest = rootIndex;
int leftIndex = left(rootIndex);
int rightIndex = right(rootIndex);

if(leftIndex < heapLength && a[rootIndex] < a[leftIndex]){
largest = leftIndex;
}
if(rightIndex < heapLength && a[largest] < a[rightIndex]){
largest = rightIndex;
}
if(largest != rootIndex){
swap(a[largest],a[rootIndex]);
maxHeapify(a,largest,heapLength);
}
}

The worst case time for floating a node to any another node depending on your optimization would be approximately equal to the height of the tree , which would generally result in something like ~ lg(N) . To give a counter example for a max Heap operating in a heap . lets give a value of 0 to the root , and let all the other nodes be 1 . In that case the program would go all the way down the heap till the last leaf .

Thursday, January 10, 2008

casts in C++

C++ provides us with 4 types of casting mechanisms . Namely:
  1. static_cast
  2. const_cast
  3. dynamic_cast
  4. reinterpret_cast
static_cast

In C casting is done via () operator

int i = 7;
e.g double d = (double) i;

in c++ to do something like this one should use static_cast .
e.g double d = static_cast<double>(i);

const_cast

const_cast is used to remove constness of an object .

jump(Person * person);

Person p;
const Person& constPerson = p;

then some thing like this wont work.
jump(&constPerson) , cause jump expects a non const object . To fix this you would have to use something like this.

jump(const_cast<person*>(&constPerson));

dynamic_cast

This cast is used with inheritance hierarchies . Say to cast a between pointers or references of base classes to references or pointers of derived classes.

e.g

Mammal * mammal;

jump(dynamic_cast<person*>(mammal));

if there was a function like

jump(Person& person); then

we would have something like

jump(dynamic_cast<person&>(*mammal));

if the casting is not possible , the dynamic_cast mechaism throws an excetion or the result is null (This is implementation specific)

Wednesday, January 09, 2008

Little Sugar: C++ references

C++ references are a variant of const pointers that always point to something .

Now consider

string s1("abc");

string s2("def");

string & refTos1 = s1;

Now refTosi points to s1.

Even after refTos1 = s2. Its still points to s1 . But the value of s1 is now changed from "abc" to "def"

Tuesday, January 08, 2008

Little Sugar : Big Oh

Consider a scenario where you had a list of N numbers . Now say you have an algorithm that finds the does some sort of comparison . If comparison strategy used compares every element with all the succeeding elements . Then on an average the number of comparisons possible in different cases would be something like this :

(n) + (n-1) + (n-2) .... 1

for the 1 st case we have n comparisons
for the 1 st element we have n-1 comparisons
for the 2 nd element we have n-2 comparison .. and so on.

the sum is = ((n)*(n+1))/2 = O(n^2)

Saturday, December 29, 2007

Java + meta programming framework == EMF

Meta programming is a popular buzz word these days . There is a framework for java , called EMF (Eclipse Modeling Framework ) that tries to add that support to java . The framework makes meta programming look like total crap . It overly complicates stuff to such a large extent that you just feel like just removing it from your project code.

So in short meta-programming in EMF + java = night mare :(

But on the other hand if you are building your domain layer . EMF is a pretty decent choice . It has in build support for a notification mechanism that allows you to listen to various model changes . So your GUI can become lightly couple to the domain layer and can become very responsive .

If other people have tried EMF , i would love to hear their experiences.

Monday, December 17, 2007

Little Sugar : Sequences

Given a sequence , the sum of elements from the i th position to the j th position can be easily found by adding the elements from the i th location to the j th location . A better optimization over this is generally to do a cumulative sum of all the elements upto the j th element . Then the
sum of any sub sequence can be found by taking the starting i th location and the ending j th location and subtracting the result of the element at the i th place from the element at the j th place .

Saturday, December 15, 2007

All About Heap Sort -- Part 1

HeapSort is a sorting algorithm . It performs in place sorting . Its complexity it O(n lg n).
It makes use of a data structure called heap. The heap data structure is like an array which looks like a complete binary tree.If you imagine the heap array as a tree then each node in the tree will have left and right children . Each of the nodes in the tree map on to elements in the array . Every parent at index (i) will have a left child at index (2 * i ) and a right child at index (2 *i +1 ) in the array . Nodes in the heap follow the heap property . Heaps can be a max heap or a min heap.
In a max heap every Parent will have a higher value than any of its children . Its the opposite in the case of min heap. For the heap sort algorithm a max heap is used , generally a min heap is used for a priority queue.

Since a heap of (n) elements is like a complete binary tree its height is (lg n ) and all basic operations run in a time proportional to the height of the tree . Heap is a complete binary tree filled with elements at all levels except the last one . So the max number of elements in a heap of height (h) is (pow(2,h+1) - 1) . The minimum number of elements is equal to the number of elements in a heap of height (h-1) + 1 element. We add the extra one element because in the actual heap there would be at least one element on the last row containing leaves.
So the minimum number of elements = (pow(2,h) -1 ) + 1

The height of a heap is actually = floor(lg n ) . Since , a heap with height h will have elements (n) = pow(2,h) <= n <= pow(2,h+1)-1 < pow(2,h-1) and hence
h <= lg n < 1 =""> height = floor ( lg n )

Monday, November 26, 2007

What would happen if locks in Java were non re-entrant

Locks in java are re-entrant , that aids locking to work effectively with Object Oriented Programming . Why ??

Just consider , if you have a base class

class Mybase{
public synchronized doStuff(){
}

}

Now If you have a child class extending the base class then,

public class MyChild extends MyBase{
public synchronized doStuff(){
super.doStuff();
}

}

This would cause a deadlock . Why ??

When on the child doStuff is called a lock on the MyBase object is obtained . Now in MyChild::doStuff when super.doStuff() is called the code would again try to get a new lock on
Mybase and if locks were non re-entrant then the thread would block and hence would cause a deadlock.

Thursday, November 22, 2007

Little Sugar : Showing an Eclipse view

You can use an IWorkbenchPage.showView(viewId) to programatically show a view .

To access the current active page you can use the following code

IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage activePage = workbenchWindow.getActivePage();

Little Sugar : Eclipse Views live in pages

In eclipse we have a workbench window in which different types of pages exist .

thats is WorkbenchWindow > Pages
> ActivePage

a workbench window also contains the currently active page .

Each page is a IWorkbenchPage. A WorkbenchPage contains many views .
Each view is a IViewPart.

So Views live in pages and pages live in workbench window

Wednesday, November 21, 2007

Little Sugar : Why constantness helps

Say u have a method like this :

const Rational operator*(const Rational& lhs,
const Rational& rhs);


Now consider this (a * b ) = c

If the above method returned a non const object then the above mentioned
assignment would make sense , ideally it should not as it would be violating the
api contract for built ins.


Tuesday, November 20, 2007

Little Sugar : Pointers to Member Functions

Pointers to member functions is a feature that not many people use but its good to know .
So lets have a look at it . Lets assume you have a class

class Person ;

typedef void (Person::*PPMF)();

class Person{
public :
static PPMF blahFunction(){
return &(Person::processAddress);
}

private :
Address address;
void processAddress();

};

Here blah function returns a pointer to the member function processAddress .
Now you have the pointer to the member address , even if it private ( its evil to to access private member function like this) you can invoke this member function now on an instance of a person
class.

Person boo;

eg. PPMF pmf = boo.blahFunction();

invoke the member function like this :

(boo.*pmf)();

Tuesday, November 13, 2007

Little Sugar : Casting away constant ness

In C++ if you create a constant object , say

const String A("Hello World");

String& B = const_cast(A);

can be used to create a non constant reference to the so called constant object and hence
manipulate it .

Monday, November 12, 2007

Little Sugar :const function pointers and references

The syntax in c++ for constant function pointers is like this

Handle& (*const getHandle) = handle;

where handle is a function returning a reference to the handle.

The syntax for reference function pointers is like this:

Handle& (&getHandle) = handle;

Thursday, November 01, 2007

Little Sugar : What does virtual in C++ mean

In c++ if a function is declared virtual for any class, then that class has an associated
virtual table . With each of those virtual functions a special type of virtual table pointer is associated , which has an entry in the virtual table associated with the corresponding class.

These virtual pointers are used at runtime to figure out which virtual function to invoke at runtime.

Making virtual functions inline does not make sense ?? why ...

Inline functions are meant to be made inline , so that means they don't have an explicit address but then if it does not have an address and its virtual then how will it have an entry in the virtual table ??

It will have an entry , cause our friend compiler will generate a function body for us and embed the address somewhere for it .

Tuesday, October 30, 2007

Private lock Object Idiom

The private lock object idiom is generally used in making a class Thread Safe.
Instead of using the instance of the object as a lock object an internal private object is used
as a lock object.

private Object lock = new Object();

so the method need to acquire a lock should use the lock object instead of this object.
e.g.

public void foo(){
synchronized(lock){
....
}
}

Sunday, October 21, 2007

Lazy Initailization Idioms

Double check idiom is supposedly the best lazy initialization technique

private static Foo foo = null;

public static void getFoo(){
if (null == foo){
synchronized (Foo.class){
if ( null == foo){
foo = new Foo();
}
}
}
return foo;
}

This is the double check idiom , it works great with primitives but is flawed when it
comes to object references cause the behaviour of object references after synchronized is
undefined.

Solution 1:

private static Foo foo = new Foo();

public static void getFoo(){
return foo;
}

Solution 2:

private static Foo foo = null;

public synchronized Foo getFoo(){
if (null == Foo)
foo = new Foo();
return foo;
}

Solution 3:

Initialize on demand - holder class Idiom

private static class Holder{
static Foo foo = new Foo();
}

public static Foo getFoo(){
return Holder.foo;
}

set_new_handler in

The correct way of overriding the new operator can be something. Here i try to highlight how one can go about doing so .

typedef void (*new_handler)();


In the new header file , a typedef new handler is defined . This typedef basically refers to
the function that the new operator will call if it is not able to allocate memory properly.
Generally the new operator specification looks for the new_handler to allocate more or release
memory so that the new operator can call it properly.

new_handler set_new_handler(new_handler handler);

is a function also found in that installs the new handler . A typical implementation
of this should return the old_handler that was replaced.

The new operator throws std::bad_alloc exception when it is not able to allocate memory.

Class specific handlers can be installed for class specific new operator .
The code for managing the operator and the handler can go in one templatised base class.
Derived classes can then inherit from this class . The base class is very specialized class
as it only provides only one type of functionality.Such type of classes are called mixins.

template
class NewHandler{
public:
static new_handler set_new_handler(new_handler handler);
static void* operator new(size_t size);

private:
static new_handler currentHandler;
};

template
new_handler NewHandler::currentHandler;

template
new_handler NewHandler::set_new_handler(new_handler handler){
new_handler oldHandler = currentHandler;
currentHandler = handler;
return oldHandler;
}

template
void* NewHandler::operator new(size_t size){
new_handler globalHandler = std::set_new_handler(NewHandler::currentHandler):
void * memory;
try{
// try to allocate memory using global new operator
memory = ::operator new(size);
}catch(std::bad_alloc &){
std::set_new_handler(globalHandler);
// propogate all the exceptions
throw;
}
// reinstall the saved gloabal handler
std::set_new_handler(globalHandler);
return memory;
}

Now any class X can use NewHandler like this :

class X : public NewHandler {
};

Thursday, October 18, 2007

Finalizer guardian Idiom

Finalizer Guardian idiom is nothing but an anonymous class assigned to a private final instance variable within a class that wants to override the finalize method .

The anonymous class takes the responsibility of calling the finalize method of the enclosing class.
All this in code looks like :

public class A{
private final Object b = new Object(){
protected void finalize() throws Throwable {
// finalize the outer A here
}
};
}

Little Sugar (Handling Exceptions in Finalize )

Lets consider a scenario where you have a class A and a subclass of that class called B.
Now say you override the finalize method in class B then you need to explicitly invoke the
finalize method of the parent.

So your implementation should look like this :

protected void finalize() throws Throwable {
try{
}finally{
super.finalize();
}

}

That way ,
any exceptions thrown in the finalize method would not cause the finalize method to terminate and leave the object in a corrupt state.

Little Sugar (Java Finalization )

Uncaught exceptions thrown in the finalize method of an object are not caught . Infact they cause the finalization process to terminate and leave the object in a corrupt state . Now that's weird ...

So the best of the rule of thumb would be to avoid finalizers. Instead explicit termination methods should be called that can be invoked in the finally block .

Monday, October 08, 2007

Contributing to the Eclipse Cool Bar

To add stuff to the eclipse cool bar , u need to
1) implement the extension point org.eclipse.ui.editor .
2) Specify a contributorClass for the above mentioned extension point.

This contributor class will provide actions that would be contributed to the
coolbar.
Lets call this calls MyContributorClass.

3) Have this class extend BaseEditorContributor , It should override contributeToParentCoolbar .

4) In the given method create a ContributionItem that would be contributed to the coolbar.

Lets call this myContributionItem.

5) Use the parentCoolBarManager to add create a ToolBarManager.

IToolBarManager toolbar = new ToolBarManager(parentCoolBarManager.getStyle())

6) Add myContributionItem to toolbar.

toolbar.add(myContributionItem);

7) Create a ToolBarContributionItem and add it to the parent cool bar.

ToolBarContributionItem toolBarItem = new ToolBarContributionItem(toolbar,myContributionItem.getId())

parentCoolBarManager.add(toolBarItem);

and finally

coolBarItems.add(toolBarItem);

parentCoolBarManager and coolBarItem are protected members and are available from the base class .

Sunday, September 23, 2007

what is e raised to i * Pi

The other day i was seeing some presentation . During the presentation i came across a mathematical puzzle . The puzzle asked about what is the value of

value = e ^ (i * Pi) ??

now this would have been really really easy if i was in 12 th grade . But Since its a been long time since 12 th grade and few yrs since by B.S degree . It took some thinking ..

So the solution is :

well if you remember complex numbers then then you can say

e ^ (i * x ) = cos (x) + i sin(x)

so e ^ ( i * Pi ) = cos (Pi) + i sin (Pi)

since cos (pi) = -1
sin (pi ) = 0

e ^ (i * pi) = -1

Duh .. so much for my memory :( ..

Tuesday, August 21, 2007

Showing an Eclipse View Programatically

In eclipse non savable containers are called views . It pretty easy to create a view , all you need to do is to implement an extension - point (org.eclipse.ui.views) and add features to a class . If you want to implement your own view , you can google it you 'll find a number of articles about it .

In this blog entry i tell you how to show/hide an existing view programatically .

Scenario1
: Assuming you have created a view whose view ID is "my.view" and you want to show this view .

Scenario2: You know the view id of some view and you want to show that view programatically.

IWorkbench workbench = PLatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
workbenchWindow.getActivePage().showView("my.view");

// to hide a view

workbenchWindow.getActivePage().hideView("my.view");

PlatformUI is a plugin that can give information about currently active windows and objects in an eclipse session . Its available to us so we use it to get the current workbench window . In eclipse workbench window is the main window . Each window has one or more pages . We get the active page . In the active page we either show or hide the view we are interested in .

Monday, August 13, 2007

Little Sugar (Heaps)

  • Heap is a data structure whcih satisfies the MAX-HEAP or MIN-HEAP property
  • All basic operations on a heap run in a time proportional to the height of the heap (lg n ) where n being the total number of nodes in a heap
  • A heap is generally a complete tree
  • IN an array represenation of an N-element heap the leaves nodes are indexed by n/2+1 , n/2 + 2 ... n
  • In an N element heap , the number of nodes of height H are n/pow(2,h+1)

Sunday, July 29, 2007

Programatically Creating a java package in Eclipse

In my last post we saw how we can create a java project programatically in eclipse. In this post we will see how to create a package in this java project.

The steps needed to do this are :

1. Create a source folder under the java project created earlier .

IFolder src = javaProject.getFolder("src");
folder.create(force , local , nullProgressMonitor);
IPackageFragmentRoot packageRoot = javaProject.getPackageFragmentRoot(folder);
IClasspathEntry[] classPath = javaProject.getRawClasspath();
List entries = new ArrayList(Arrays.asList(classpath));
entries.add(JavaCore.newSourceEntry(root.getPath()));

javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[0]) , null ProgressMonitor);

The code becomes pretty clear if you had followed my previous post.


2. Create the actual package .

src.createPackageFragment(packageName, force , nullProgressMonitor);

Yeah thats done , in the next post well see how to create a class programatically

Wednesday, July 25, 2007

Creating a new project in Eclipse Programatically

If you have done Eclipse plugin development you would know that any non trivial task is not obvious , unless you have gone and dug into the eclipse source code. Going through the eclipse source code is not easy cause its a massive rhino . Finding the right code requires tons of patience for a newbie .

Here i am presenting a small snippet that creates a java project programatically
This code can also be found in the eclipse source tree , i am presenting here just for handy reference .

  1. Create an IProject with a name
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("dummyProject");
IProgressMonitor nullProgressMonitor = null;
project.create(nullProgressMonitor);

ResourcesPlugin is the plugin that gives us access to all the resources in eclipse including the workspace . When eclipse creates a project it shows a progress bar , we are passing null for that.

2. Open the above created java Project

IJavaProject javaProject = JavaCore.create(project)

'create' is a misonomer . This creates a decorated Java version of an eclipse project.

3. Add the java nature to the project

IProjectDescription description = project.getDescription();
description.setNatureIds(new String[]{JavaCore.NATURE_ID});
project.setDescription(description,null);

Eclipse has the concept of natures , its kinda tagging a project with java label.

4. Set the class path for the java project

IClasspathEntry[] rawClassPath = javaProject.getRawClassPath();
List classPath = new ArrayList(
Arrays.asList(rawClassPath));
classPath.add(JavaRuntime.getDefaultJREContainerEntry());
javaProject.setRawClasspath(classPath, nullProgressMonitor);

Since java and class paths are closely tied . We need to add the different class libraries to the project class path . In Eclipse every plugin has its own class loader . By adding add class libraries to the project class path we make class libraries accessible to the class loader .

5. Create the bin folder and mark it as output folder

boolean force = true;
boolean local = true;
IFolder binFolder = project.getFolder("bin");
binFolder.create(force,local,nullProgressMonitor);
IPath fullPath = binFolder.getFullPath();
javaProject.setOutputLocation(fullPath,nullProgressMonitor);

This code will create a project in the Runtime Eclipse Workbench that appears when you launch a new eclipse instance from your eclipse instance.

Monday, July 09, 2007

Extension Object Pattern : an Eclipse Example

In short an Extension Object pattern is a nice way of extending an interface of class by 3 rd party classes without polluting the base interface of the class.

I am going to take eclipse as an example to explaing this pattern . For those of you , who have done eclipse plugin development . You would have come across ed the interface IAdaptable. This interface is at heart of the Extension Object Pattern implemented by Eclipse .

So what is the Extension Object Pattern ???

Say you have an interface IFile . This interface represents an abstraction of a file . Apart from being a basic file this IFile interface could offer many services . So the question is how do you offer those services .

One simple way would be to extend the IFile interface . Add the extra functionality to the new new interface and have come class implement that new interface . e.g you could have a IUIFile interface . Once you have that interface , you could implement that interface .

But the problem with that approach is that , you end up polluting the base beautiful interface and have a bloated class ( implementor) . Well the above mentioned approach would work if you are fine with extending the object every time you want to implement a new service , but as the number of services increase the class becomes super duper bloated monster .

So how does the extension object pattern help us in solving this evolution problem ??

I ll continue with the IFile interface from eclipse to explain how can we go about using the interface to implement the extension pattern .

We know that IFile might have to support a number of services at some point of time in future . So rather than have IFile implement all the new interfaces , we just implement the IAdaptable interface . This interface is a place holder , saying that the class implementing IFile is now ready to be extended by 3 rd party classes without polluting the base interface IFile.

This Adaptable interface can contain a simple method that does the job of resolving the service to the correct service provider .

public interface IFile extends IAdaptable , .... {
.....

public Object getAdapter(Class adapter);
...
}

}

Now lets say that we want to check if IFile supports ServiceA , or ServiceB.
We can do that now passing ServiceA.class to the getAdpater method .
This method would return a valid object if the service is supported or on the other hand it would return a null object .

Instead of having a number of if conditions in the getAdapter method what eclipse does is that for each interface supported by the type , eclipse creates an adapter factory . The different factories are then registered with an AdapterManager . The getAdapter method then returns
the appropriate AdapterFactory via the AdpaterManager. e.g

public Object getAdapter(Class adapter);
return Platform.getAdapterManager.getAdpater(this,adapter);
}


Something like this can later be used to return the right adapter for intended service.

public interface IAdapterfactory {
public Object getAdapter(Object adaptableObject, Class adapterType);
....
}


The adapter manager uses different adapter factories to resolve the reference for the asked interface , for the given type .

So in this manner multiple behaviors can be added to a single type . This is a nice way to support class extensions.

Friday, June 29, 2007

Logging using the Eclipse Logging Framework

if you are using eclipse in your day to day work and you want to log activities using the in built eclipse logging frame work .

Here is a small example to do the same ,

if u have a plugin class then say MyPlugin that extends AbstrarctUIPlugin then u can a have method in that class that does the logging for you .

public static void log(String message , int status ){
getDefault().getLog().log(new Status(status, getPluginID( ), message,null) );
}

the values , status can take are like :

  • IStatus.ERROR
  • IStatus.WARNING

Thursday, June 28, 2007

Immutable Objects In Java

What is an Immutable Object ?

An immutable object is an object that does not change its state once its created .Java has a number of inbuilt classes that provide that functionality e.g String , Integer etc..

So how do you create an immutable object :
  • Remove or make setters less accessible.
  • Preveting methods from getting overriden.
  • Make all fields final.
  • Make defensive copies of mutable objects.
  • Do not provide a clone method
  • Do not provide a copy constructor
  • return a fuctional object
Returning a functional object means applyting a function on the parameters of a method and returning the function rather than calculating the function and returning the value . e.g

public class Complex {
public Complex(int real, int imaginery){
this.real = real;
this.imaginery = imaginery;
}

public Complex add(Complex left , Complex right) {

// fuctional return
return new Complex(left.real + right.real , left.imaginery + right.imaginery);
}
}

The advantage of having an immutable class is that its thread safe.
The disadvantage being creating many new objects for different operations can lead to memory bloat

Little Sugar ( Mixins in Java)

Mixin ?? what is a mixin ...

Thats what i wondered when i cam accross the phrase . A Mixin is a way of adding features to the core functionlaity of a class . It is different from extending the class , cause it generally pertains to adding features not related to the core or default behaviour of a class .

A little example will make things clear . Say you have a small class Person that represents a person wholly . Not if you want to compare 2 instances of Person , you could implement the Comparable interface . By implementing the Comparable interface you add a functionlity that is not directly related to a Person object but is a help ful feature .

So a simple way to implement a Mixin is to implement an interface .. so much for buzz words...

Wednesday, June 27, 2007

Little Sugar (Security Manager , Java)

Today i ll gloss over a few small things worth remembering about security
in java . So lets get started :

In Java , we hava a Java API . The java API provides us with a lot methods to accomplish different type of tasks . Now if for some reason we want to enforce security on these tasks so that only selected operation can be performed and that to by selected users . In that case we need to create a security policy file.

In the security policy file , we specifiy how permissions are applied to different code sources . We specify differnt permissions in terms of Permission objects that are applied to CodeSource objects .

At runtime a policy object is created corresponding to the policy file .

For the policies to take effect a SecurityManager needs to be installed . Once the security manager is installed it uses the AccessController ,which inturn checks the different permissions based on different permission objects .

When the class loader loads a type in the JVM . It places the type in a protection domain , which encapsulates the permissions . At runtime , when methods on the type instance are invoked the security manger is checked to see if the method can be invoked .

Tuesday, June 19, 2007

Litttle Sugar (Java Collections)

The other day I was reading about java collections . I came accross this trivial point about Sets in java that is worth remembering . In java there are 3 different implementations of the Set interface , namely :
  1. HashSet
  2. TreeSet
  3. LinkedHashSet
HashSet:
The fastest among the 3 implementations , but does not maintain ordering.

TreeSet:
The slowest among the 3 implementations , uses red black tree to internally store items and orders the items by value.

LinkedHashSet:
Its performance comes in between the 1st two but maintain the ordering in which items are
inserted . Uses hashtable with linked list to store items.

Saturday, June 16, 2007

String formatting using C++

Say you need to create a special string that does shows floating point numbers.
Lets put another constraint , say you need to show upto K decimal places.

e.g u need an output like this
123.45 <--- 2 decimal places

say double d = 123.456

then u can create a string which shows upto 2 decimal places like this.

ostringstream o;
o.setf(ios::fixed);
o.precision(2);
o << d;
cout << o.str();

Thursday, June 14, 2007

Const in C++

The const keyword in C++ is a very useful keyword . Apart from declaring constants it is useful in declaring few important things . Lets talk about two important const advantages
  1. pointer to a const
  2. const reference
Pointer to a const:
Pointer to a const basically says that the object being pointed to by the pointer should remain const and the pointer should not try to change the contents of that object . But this does not mean that that value of the object will not get changed m it just says the given pointer is not going to change the value of the object.

e.g String(const char * = ""){
.....
}

a simple rule of thumb is that if the function is not going to modify the object it should accept a const object

const reference:


void do_something(const Thing &);

This is analogous to pointers , the only advantage is that by declaring a reference const you prevent unnamed temporaries . Basically its the same concept which says if your not gonna change it then pass it as a const .

cannot use do_something(get_something()) // un named temporary not allowed

Things get_something();

Thing t(get_something());
void do_something(Thing&);

Const member functions:
const member function are member function in which the argument list is followed by the const keyword. In a const instance of an object only const member functions can be invoked.
From non const member functions unnamed temporaries can be invoked.

Implementing operator as member or nonmember functions

The answer to implementing an operator as a member or a non member lies in the following simple points
  • if any operand of an operator is susceptible to implicit type conversion , implement it as a member function
  • if the result of an operation does not effect the two operands or an operand implement it as a non-member function.

Sunday, June 10, 2007

Tutorial: Writing a Tetris Clone using XNA

One of the Hello World programs in game programming is Tetris . I am making the assumption that you the reader have played tetris and know the rules of this simple game knows C# and under stands Object Oriented Concepts . Tetris is a very simple game , simple graphics simple collision detection and animation if you want to call the rotation of blocks as animation . So lets not any more time and lets get started with the code and step by step explanation of how to create a Tetris Using XNA .

Step 1:
Step 1 is figuring out all the the blocks that are used in the Tetris game . If you think about the game it consists of the following blocks
  1. a line
  2. a square shaped block
  3. a L shaped block
  4. a J shaped block
  5. a S shaped block
  6. a T shaped block
  7. a Z shaped block
Now each of these blocks contain exactly 4 squares . So the basic unit is a square and we build blocks out of these squares .

Step 2:
In step 2 ,we will try to see as to how we can map these blocks to their corresponding images and as to how we can rotate the blocks and their corresponding images .Since we saw that each block is made up of 4 squares , we can label the squares as 1 , 2 ,3 ,4 correspondingly . Out of these 4 squares , 1 square we will mark as the pivot around which the block can rotate .
See the image below for a clear understanding of this:



If you look at the blocks they have different names , like L , J , S which basically identify their shape . Each square in a block is numbered and one of the square is circled . The circled square is the pivot for the given block . If you look carefully at block S , that block on rotation looks like the block mentioned directly below it .


Step 3

Now that we understand the basics of the representation and requirements we can get down to some coding , i ll try to avoid the XNA related code till the end . I will try to explain how this simple representation of blocks can be represented using code.

Since we have a number of blocks and each block can rotate and move left , right , down. Also each block has a direction and a current position . So basically every object in this simple game is block and since all these blocks have few things in common , we can take that common functionality and create a simple abstract class called Block . We can then have each one of the blocks extends from this base class called Block . Since the next block that falls from the top should be randomized , we can create BlockFactory that generates these blocks for us . This factory can create an instance of each type of block and cache it . So that we can reuse the block instances . Now that i have explained how Block , BlockFactory fit together lets look at the code for Block :

public abstract class Block
{
// the background image used by the game
protected Texture2D backgroundTexture;

// the current position of the block
protected Vector2 position;

// the 4 squares used by each block
protected Square square1;
protected Square square2;
protected Square square3;
protected Square square4;

// before we rotate the block and calculate the new position for the squares
// we'll use the following variables to store the old positions
protected Vector2 _oldSquare1Position;
protected Vector2 _oldSquare2Position;
protected Vector2 _oldSquare3Position;
protected Vector2 _oldSquare4Position;

// the game field where the actual game is being played
// i ll talk about this later
protected GameField gameField;

// the direction of the block
private Direction direction;

// the movement of the block
private Movements.Movements movements;

// this constructor for the block , this is where the block gets created
// it is given an initial position and a direction , based on this starting
// position the 4 squares get initialized
public Block(GameField gameField, Texture2D backgroundTexture, Vector2 origin , Direction direction)
{
this.backgroundTexture = backgroundTexture;
this.position = origin;
this.direction = direction;
this.gameField = gameField;

square1 = new Square(this.backgroundTexture, position);
square2 = new Square(this.backgroundTexture, position);
square3 = new Square(this.backgroundTexture, position);
square4 = new Square(this.backgroundTexture, position);

movements = new Movements.Movements(this,gameField);

// ignore this for while i ll talk about this
setupBlock();
}

// the code that will respond when a block of a given shape is rotatated to
// the North ,
public abstract void RotateTo(North north);

// similarly it also works for East , West , South

// the core rotating logic is here , first of all we save the positions of
// the 4 squares , then based on the current direction we try to rotate
// the current block , this gives us a new set of positions for the 4 squares
// and a new direction for the block , then we make a final check if we can
// possible rotate if not we revert back to the saved positions .
public void Rotate()
{
savePositions();
this.direction = direction.Rotate(this);
if (!canRotate())
revertPositions();
}

// Similar to rotation we first of all save all the positions of the 4
// squares , based on the current movement we check if we can move to the
// left the given number of units , if the block can move we move else
// we revert back to the saved positions .
public virtual void MoveLeft(int units)
{
savePositions();
if (movements.LEFT.CanMove(units))
{
square1.MoveLeft(units);
square2.MoveLeft(units);
square3.MoveLeft(units);
square4.MoveLeft(units);
}
else
revertPositions();
}

// similar logic applies for Right and Down

// the draw method for the block draws the block , by drawing all the 4
// squares , ignore the SpriteBatch i ll talk about that later
public virtual void Draw(SpriteBatch batch)
{
// draw the given square at the given position
batch.Draw(square1.Texture, square1.Position, Color.White);
batch.Draw(square2.Texture, square2.Position, Color.White);
batch.Draw(square3.Texture, square3.Position, Color.White);
batch.Draw(square4.Texture, square4.Position, Color.White);
}


protected void savePositions()
{
_oldSquare1Position = square1.Position;
_oldSquare2Position = square2.Position;
_oldSquare3Position = square3.Position;
_oldSquare4Position = square4.Position;
}

protected bool canRotate()
{
return canRotate(square1) &&
canRotate(square2) &&
canRotate(square3) &&
canRotate(square4);
}

protected void revertPositions()
{
square1.Position = _oldSquare1Position;
square2.Position = _oldSquare2Position;
square3.Position = _oldSquare3Position;
square4.Position = _oldSquare4Position;
}

// ask the gameField if the given square can rotate
private bool canRotate(Square square)
{
return gameField.CanRotate(square);
}
}
Step 3 was big , indeed it was a mini Leap . But it was needed . In Step i will be talking about the classes that are used by above code .

Step 4:
Lets start with the Square class . A block uses 4 squares . The code for the Square class is pretty simple and looks like this :

public class Square
{
.....

// move the position of the square to the left by given units
public void MoveLeft(int units)
{
position.X = position.X - units;
}

...

// move the position down by given unite
public void MoveDown(int units)
{
position.Y = position.Y + units;
}

...


The square class is pretty simple . Next there is an interface called Direction .
which looks like this

public interface Direction
{
Direction Rotate(Block block);
}


I have 4 classes implementing this interface . The classes being East , West , South and North . Lets look at the code for the East class .

// East implements the Direction class
public class East : Direction
{
// the rotate method tells the block to rotate itself in the east
// direction . Remember the abstract method in Block that rotate in
// different direction , this is where they are used . Why i did this
// well depending upon the shape of the block and using this type of
// reverse delegation helps in keeping the code managable
public Direction Rotate(Block block)
{
block.RotateTo(this);

// since the next direction in clockwise manner is South return that .
return Directions.SOUTH;
}
}


Directions is not a true factory , but just holds static references to different
types of directions . The movement class is also similar in nature to the direction
class . The movement class is an abstract class and there are classes like Left ,
Right , Down that inherit from Movement . Again Movements is similar in nature to
Directions .

To be continued ....