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 .
Wednesday, April 02, 2008
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
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..
So if you want a head start , ThoughtWorks is the place to be ;)
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
- 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 .
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();
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()
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());
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.
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
}
}
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;
}
}
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
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)
{}
};
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 .
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);
}
}
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());
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
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.
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 .
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 .
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))
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
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.
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.
Subscribe to:
Posts (Atom)
Labels
. linux
(1)
algorithm
(15)
analytics
(1)
bash
(2)
bigoh
(1)
bruteforce
(1)
c#
(1)
c++
(40)
collections
(1)
commands
(2)
const
(1)
cosine similarity
(1)
creating projects
(1)
daemon
(1)
device_drivers
(1)
eclipse
(6)
eclipse-plugin-development
(9)
equals
(1)
formatting
(1)
freebsd
(1)
game programming
(1)
hashcode
(1)
heap
(1)
heaps
(1)
immutable-objects
(1)
java
(19)
JDT
(1)
kernel
(1)
linux
(4)
little sugar
(23)
logging
(1)
machine learning
(1)
marker-resolution
(1)
markers
(1)
mergesort
(1)
mixins
(1)
numbers
(1)
opengl
(2)
patterns
(2)
priority-queue
(1)
programming
(51)
ps
(1)
ranking
(1)
refactoring
(3)
references
(1)
security
(1)
set
(1)
shell
(1)
similarity
(1)
statistics
(1)
stl
(1)
tetris
(1)
threads
(1)
trees
(2)
unicode
(1)
unix
(2)
views
(2)
windows programming
(2)
XNA
(1)