Friday, April 30, 2010

Kerala Congress Merger - Religion in Kerala Politics ?

Rather than elaborating possibiliites , here is what i think might be happening

a) In the Next election ,the Congress led UDF might come to power in
Kerala.

b) Muslim League ( A secular party ! - how can it be ? ) is the second biggest
block after the Congress and Education Portfolio might go to them.

c) Bishops want Kerala Congress faction to come together and become the
second dominant partner in the coailation and get the Ministry of Education.

d) Poor congress wallahs will be on the "recieving" end as coailation partners
will demand more than 50% seats.

The real battle is between the people who follow the Cross and the people who follow the Crescent. The loser is going to be the Congress party as these coailition partners will become dominant.

It is "minority" politics biting back the Congress.

I think "Nuetral" citizens of kerala should give a surprise to these Bishops by bringing LDF back to the power.

An Interesting article...!

Read about Microsoft's anti-piracy drive @

http://www.pcmag.com/article2/0,2817,2363041,00.asp

The problem for M$ is they cannot go beyond a point as
GNU Linux is waiting on the sidelines.

Back in 2001 , I had suspected that FOSS will force M$ to
covertly allow piracy of some of their products to maintain
(mind ) market share.

Some Trivia .... which might be useful...

Today is May day and I got up early. I happen to get an email from an ex-colleague of mine which contain some amusing information.


[EMAIL TEXT]
SOMETHING VERY INTERESTING



Letters 'a', 'b', 'c' 'd' do not appear anywhere in the spellings of 1 to 99.

The letter 'd' comes for the first time in “Hundred”.


Letters 'a', 'b' 'c' do not appear anywhere in the spellings of 1 to 999.



The letter 'a' comes for the first time in “Thousand”


Letters 'b' 'c' do not appear anywhere in the spellings of 1 to 999,999,999.

The letter 'b' comes for the first time in “Billion”


And the letter 'c' does not appear anywhere in the spellings of entire English Counting

[EMAIL TEXT]

Wednesday, April 28, 2010

A Movie which I missed...

Yesterday , i saw Kolilakkam ( a movie ) after it was released almost 30 years ago. The movie is famous for the fact that legendery actor Jayan met with an accident while shooting for climax shots. The director did a remarkable job by changing the climax without a glitch. The Lead hero ( there were four - Jayan , Sukumaran , Soman and Madhu ) might not have died in the original story line.

Tuesday, April 27, 2010

using C# DynamicObject

ExpandoObject and DynamicObject are classes available with the Dynamic Language Run Time. I just finished writing a class which uses Dynamic Object... ( Read msdn documentation for getting an indepth overview of DynamicObject)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
namespace TestVS
{
class DynamicClass : DynamicObject
{
/// <summary>
///
/// </summary>
private Dictionary<string, Object> props =
new Dictionary<string, object>();

/// <summary>
///
/// </summary>
public DynamicClass() { }

/// <summary>
///
/// </summary>
/// <param name="binder"></param>
/// <param name="result"></param>
/// <returns></returns>
public override bool TryGetMember(GetMemberBinder binder,
out object result)
{
string name = binder.Name.ToLower();
return props.TryGetValue(name, out result);

}
/// <summary>
///
/// </summary>
/// <param name="binder"></param>
/// <param name="value"></param>
/// <returns></returns>
public override bool TrySetMember(SetMemberBinder binder,
object value)
{
props[binder.Name.ToLower()] = value;


return true;

}

}

class Program
{
static void Main(string[] args)
{
dynamic dc = new DynamicClass();
//--------- Adding a property
dc.hell = 10;
//--------read back the property...
Console.WriteLine(dc.hell);

//------- Creating an Action delegate...
Action<int> ts = new Action<int>( delegate(int i ) {
Console.WriteLine(i.ToString());

});

//------------Adding a method....
dc.rs = ts;

//----------- invoking a method....
dc.rs(100);

Console.Read();

}
}
}

A Stupid Feature in C# 4.0

Whatever be the usage scenario , Adding methods and properties on the fly is a stupid feature ( This is my opinion ...your's may vary ). This can create all sorts
of readability issues. ( Source code is for others to read as well )

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
namespace TestVS
{

class Program
{
static void Main(string[] args)
{
dynamic ds = new ExpandoObject();
ds.val = 20;
Console.WriteLine(ds.val);
Console.Read();

}
}
}

Monday, April 26, 2010

Visual C++ Lambda Functions - Part 2

This is the second program i wrote to learn about Lambda functions in C++.


/////////////////////////////////
// second_lambda.cpp
// A simple program to learn about
// Visual C++ 2010 lambda function...
//
// cl /EHsc second_lambda.cpp
//
// second_lambda.exe

#include <stdio.h>
#include <functional>
using namespace std;
using namespace std::tr1;

int main()
{
int x ;
//---------- initialize
x=3;

///////////////////////////////////
// auto does type inferencing ...ANSI
// c auto keyword for local variables...
//
// 1 - introducer (& - capture outer variables by reference)
// 2 - parameter
// 3 - return type
// 4 - body
//
// 1 2 3 4
auto t = [&](int z) -> int { x=x+z; return x*x; };

////////////////////////////////////
// invoke the function...
//
printf("%d\n",t(3));
printf("%d\n",x); //x should change...!

}



Visual C++ 2010 Lambda Functions

Mathematical formalism of Lambda calculus is the nucleus of functional programming languages. In the last five years , Lambda Expressions and functional Programming constructs have percolated into the Imperative Languages. C# and VB.net has support for Lambda expressions.

C++ is the latest language which has got support for Lambda Functions....

/////////////////////////////////
// first_lambda.cpp
// A simple program to learn about
// Visual C++ 2010 lambda function...
//
// cl /EHsc first_lambda.cpp
//
// first_lambda.exe

#include <stdio.h>

int main()
{
int x ;
//---------- initialize
x=3;

///////////////////////////////////
// auto does type inferencing ...ANSI
// c auto keyword for local variables...
// 1 - capture outer variables..by value
// 2 - parameter
// 3 - body
// 1 2 3
auto t = [=](int z) { return x + z; };

////////////////////////////////////
// invoke the function...
//
printf("%d\n",t(3));

}



F:\pai\cpp>cl /EHsc first_lambda.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.

first_lambda.cpp
Microsoft (R) Incremental Linker Version 10.00.30319.01
Copyright (C) Microsoft Corporation. All rights reserved.

/out:first_lambda.exe
first_lambda.obj

F:\pai\cpp>first_lambda
6

F:\pai\cpp>

Saturday, April 24, 2010

The Coming urban chaos

I just finished reading an article on urbanization of the nation. By 2030, if not planned properly , we will be in a mess. Planners has to spent a lot now to avoid this "catastrophe".

By nature , i am demophobic and this startles me. Per capita consumption of water will come down from 105 litres a day to 65 during that time.

Mallus who are proud about being people who take bath (more than once ) every day, will be like our much despised "PAANDIS" by that time...! Only solace is those guys will be even more worser than us .

Monday, April 19, 2010

Python is very much here for me

I wrote some Python Programs @ ICE FOSS 2010. Some features seems to be wierd and stupid. The Power of dynamic language is clearly felt and it is enjoyable experience.

Python do not have value semantics ..it is based on Object

Big Integer support...

dir(var)

each is a copy...


a = "Hello";;

a[0] ( index... )
a[-1] (right side indexing )

len(a)

LIST
-----

a = [10 , "hello", 20 ];

len(a) will give count...


a[0:1] = slice...

a.pop -- mutable operation...

a.append(100);

a.pop(<index>) ..will pop one particular number...

a*4 ... replication...

"#"*2=>

__<name>___ (operators...!)

DICTIONARY
----------
>>> a={'a':49 , 'b':56 }
>>> len(a)
2

>>> a['a']
49
>>> a['b']
56
>>>
>>> a.get('vb',0)
0
>>>

>>> a.get('vb',0)
0
>>> a.has_key('a')
True
>>> a.has_key('b')
True
>>> a.has_key('d')
False
>>>

Range
-----
>>> range(4)
[0, 1, 2, 3]
>>> range(10,20)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> range(10,20,2)
[10, 12, 14, 16, 18]
>>>

Test.py
-------
a=[45,47,78];
print a;

test2.py
-------
#-- iterating a range
for a in range(10):
print a*a;
print "-"*20;
#iterating a list
for i in [78,90]:
print i

#iterating a dictionary

c = {'a':67 , 'b':89}
for key in c.keys():
print c[key];

test3.y
-------
for a in range(10):
b = a*a;
if a > 8:
print b*100
elif a<2:
print b*10
else:
print 'ok'
Test5.y
===============================================
#------------------ Functions...

def mysqr(a):
b = a*a
return b;
#------------ main program...
c = mysqr(5)
print c

==================================================


#------------------ class

class abc:
def __init__(self):
self.a = 56
self.b = 78
def getVals(self):
return self.a
def __del__(self):
print "BYE"

a=abc();

print a.getVals();

===============================================
>>> a =input("hello > ")
hello > 34
>>> a
34
>>> a = raw_input("enter a string ...")
enter a string ...asfsdsdf
>>> sdfsdf

==================================File Open/Close
>>> fd = open('test.py' ,'r')
>>> data = fd.read()
>>> fd.close()
>>> print data
a=[45,47,78];
print a;

>>>
================================== Read into a line
>>> fd = open('test.py' ,'r')
>>> sr = fd.readlines()
>>> print sr
['a=[45,47,78];\n', 'print a;\n']
>>>
>>> dir(fd)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'encoding', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
>>>
================================ RegEx support...

>>> a="Praseed Pai K.T."
>>> a.split(".")
['Praseed Pai K', 'T', '']
>>> a.split("")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: empty separator
>>> a.split(" ")
['Praseed', 'Pai', 'K.T.']
>>>

=================================== imports

>>> import commands
>>> c=comands.getoutput('ls -l ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'comands' is not defined
>>> c=commands.getoutput('ls -l ')
>>> print c
total 32
-rw-r--r-- 1 NWUSER1 Domain Users 199 2010-04-20 04:22 test2.py
-rw-r--r-- 1 NWUSER1 Domain Users 187 2010-04-20 04:20 test2.py~
-rw-r--r-- 1 NWUSER1 Domain Users 100 2010-04-20 04:26 test3.y
-rw-r--r-- 1 NWUSER1 Domain Users 122 2010-04-20 04:31 test4.y
-rw-r--r-- 1 NWUSER1 Domain Users 90 2010-04-20 04:29 test4.y~
-rw-r--r-- 1 NWUSER1 Domain Users 188 2010-04-20 04:46 test5.py
-rw-r--r-- 1 NWUSER1 Domain Users 195 2010-04-20 04:39 test5.py~
-rw-r--r-- 1 NWUSER1 Domain Users 23 2010-04-20 04:10 test.py
>>>


==================================
Any python file can be considered as a module !!!
There is difference between module and package...

>>> import sys
>>> sys.path
['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0']
>>>

sys.path.append('/usr/lib');

===================================================
Name/Value database support
Zodb (Object database )
Zope (Application framework )

PLONE
ERP5

Python might crawl into my life

I am writing this from ICE FOSS 2010 @ FISAT , Angamaly. I have just signed up for two days of Linux Programming Workshop conducted as part of the event.

Today i will be taking lessons on Python and SciPy.

Tomorrow it is Linux Kernel Programming.

The details of the event can be retrieved from http://icefoss.in


I am expecting to take home some Python folklore !.

Sunday, April 18, 2010

Objecitve C Programming Tutorial under Linux - Part 20

In this part , we will use Objective C runtime to load a class on the fly and create an instance out of it.

////////////////////////////////////////
// dynload.m
//
// Minimalist Objective C Program
// to demonstrate dynamic class loading...
// (Orielly )
//
// gcc -x objective-c -Wno-import dynload.m -lobjc

#import <objc/Object.h>

@interface Test: Object
{
int i;
}

-(void)Dump;
@end

@implementation Test
-(void)Dump {
printf("Hello World...\n");
}
@end

int main(int argc, char * argv[ ]) {


Class temp = objc_get_class("Test");

id r = class_create_instance(temp);

[r Dump];
return 0;
}

Objecitve C Programming Tutorial under Linux - Part 19

In this part , I will adapt a program from the Objective C Pocket reference book published by Orielly. I will extend the minimal program with Run Time Type Information.

////////////////////////////////////////
// simple.m
//
// Minimalist Objective C Program
// Adapted from Objective C Pocket Reference
// (Orielly )
//
// gcc -x objective-c -Wno-import simple.m -lobjc

#import <objc/Object.h>


int main(int argc, char * argv[ ]) {


Object* obj = [Object new];

if ( [obj isKindOfClassNamed:"Object"] == YES )
{
printf("I'm derived from Object....\n");
}

if ( [obj isKindOf:[Object class]] == YES )
{
printf("I'm derived from Object....\n");
}

return 0;
}

Objecitve C Programming Tutorial under Linux - Part 18

In this part , we will learn about Object Serialization feature of Objective C Programming Language.This is a run time specific feature. I am using GCC run time.

The example is adapted from the following Wikipedia page.

//////////////////////////////////////
// msgsend.m
// A Objective C Program to serialize the
// current time and spit to the console
//
// gcc -x objective-c -o msgsend.exe -Wno-import msgsend.m -lobjc
//



#import <objc/Object.h>
#import <time.h>
#import <stdio.h>

@interface Sender : Object
{
time_t current_time;
}

- (id) setTime;
- (time_t) time;
- (id) send;
- (id) read: (TypedStream *) s;
- (id) write: (TypedStream *) s;

@end




@implementation Sender
- (id) setTime
{
//Set the time
current_time = time(NULL);
return self;
}

- (time_t) time;
{
return current_time;
}

- (id) write: (TypedStream *) stream
{
/*
*Write the superclass to the stream.
*We do this so we have the complete object hierarchy,
*not just the object itself.
*/
[super write:stream];

/*
*Write the current_time out to the stream.
*time_t is typedef for an integer.
*The second argument, the string "i", specifies the types to write
*as per the @encode directive.
*/
objc_write_types(stream, "i", &current_time);
return self;
}

- (id) read: (TypedStream *) stream
{
/*
*Do the reverse to write: - reconstruct the superclass...
*/
[super read:stream];

/*
*And reconstruct the instance variables from the stream...
*/
objc_read_types(stream, "i", &current_time);
return self;
}

- (id) send
{
//Convenience method to do the writing. We open stdout as our byte stream
FILE *fp = fopen("hello.txt","wt");
if ( fp == 0 )
return;

TypedStream *s = objc_open_typed_stream(fp, OBJC_WRITEONLY);

//Write the object to the stream
[self write:s];

//Finish up — close the stream.
objc_close_typed_stream(s);
}
@end


///////////////////////////////////////////
//
//
//
@interface Receiver:Object
{
Sender *t;
}
- (id) receive;
- (id) print;

@end

@implementation Receiver

- (id) receive
{
//Open stdin as our stream for reading.

FILE *fp = fopen("hello.txt","rt");
if ( fp == 0 )
return;

TypedStream *s = objc_open_typed_stream(fp, OBJC_READONLY);

//Allocate memory for, and instantiate the object from reading the stream.
t = [[Sender alloc] read:s];
objc_close_typed_stream(s);
}

- (id) print
{
fprintf(stderr, "received %d\n", [t time]);
}

@end




int
main(int argc , char **argv )
{

if ( argc == 1 )
{
printf("Usage ./msgsend.exe 'R' | 'W' \n");
printf("R - Read from stream \n");
printf("W - Write to stream...\n");
return;
}

char c = argv[1][0];



if ( c == 'w' || c == 'W' )
{
Sender *s = [Sender new];
[s setTime];
[s send];
}
else if ( c == 'r' || c == 'R' ) {
Receiver *r = [Receiver new];
[r receive];
[r print];
}
else {
printf("unknown option....\n");
}


return 0;
}




[sandhya@localhost serialize]$ gcc -x objective-c -Wno-import -o msgsend.exe msgsend.m -lobjc
[sandhya@localhost serialize]$ ./msgsend.exe w
[sandhya@localhost serialize]$ ./msgsend.exe r
received 1271617872
[sandhya@localhost serialize]$ ./msgsend.exe r
received 1271617872
[sandhya@localhost serialize]$ ./msgsend.exe w
[sandhya@localhost serialize]$ ./msgsend.exe r
received 1271617885
[sandhya@localhost serialize]$ ./msgsend.exe w
[sandhya@localhost serialize]$ ./msgsend.exe r
received 1271617890
[sandhya@localhost serialize]$ ./msgsend.exe w
[sandhya@localhost serialize]$ ./msgsend.exe r
received 1271617893
[sandhya@localhost serialize]$

Objecitve C Programming Tutorial under Linux - Part 17

In this part , we will learn about Objective C categories. Catogories are called Extension methods in VB.net and C#.

With this feature , we can add methods to an existing class without having access to the source code...

The code is adapted from the following page on the wikipedia.

///////////////////////////////////////
// cat.m
// A Objective C Program to demonstrate
// Categories. Catogories are also called
// extension methods in VB.net and C#
//
// gcc -x objective-c -Wno-import cat.m -lobjc
//

#import <objc/Object.h>

/////////////////////////////////////////
//
// An Integer class definition and
// implementation...
//
@interface Integer : Object
{
int integer;
}

- (int) integer;
- (id) integer: (int) _integer;
@end


@implementation Integer
- (int) integer
{
return integer;
}

- (id) integer: (int) _integer
{
integer = _integer;

return self;
}
@end

//////////////////////////////////////////////////
//
// A Category for adding arithematic operation...
// This is possible even if we do not have the entire
// source code of Integer implementation...all you
// need is declaration...
//

@interface Integer (Arithmetic)
- (id) add: (Integer *) addend;
- (id) sub: (Integer *) subtrahend;
@end


@implementation Integer (Arithmetic)
- (id) add: (Integer *) addend
{
return [self integer: [self integer] + [addend integer]];
}

- (id) sub: (Integer *) subtrahend
{
return [self integer: [self integer] - [subtrahend integer]];
}
@end

//////////////////////////////////////////////////
//
// A Category for adding methods for Display...
// This is possible even if we do not have the entire
// source code of Integer implementation...all you
// need is declaration...
//

@interface Integer (Display)
- (id) showstars;
- (id) showint;
@end



@implementation Integer (Display)
- (id) showstars
{
int i, x = [self integer];
for(i=0; i < x; i++)
printf("*");
printf("\n");

return self;
}

- (id) showint
{
printf("%d\n", [self integer]);

return self;
}
@end

//////////////////////////////////////
//
// Entry Point.....
//
//
int
main(void)
{
Integer *num1 = [Integer new];
Integer *num2 = [Integer new];

int x;

printf("Enter an integer: ");
scanf("%d", &x);

[num1 integer:x];
[num1 showstars];

printf("Enter an integer: ");
scanf("%d", &x);

[num2 integer:x];
[num2 showstars];

[num1 add:num2];
[num1 showint];

return 0;
}





[sandhya@localhost four]$ gcc -x objective-c -Wno-import cat.m -lobjc
[sandhya@localhost four]$ ./a.out
Enter an integer: 57
*********************************************************
Enter an integer: 59
***********************************************************
116
[sandhya@localhost four]$

Objecitve C Programming Tutorial under Linux - Part 16

In this part , we will learn about Message Forwarding in Objective C Programming Language. This feature is highly run time specific. Consult the document of your Objective C run time... i am
using Default GCC run time.

The source code is adapted from the following page of Wikipedia.

Objective-C permits the sending of a message to an object that may not respond. Rather than responding or simply dropping the message, an object can forward the message to an object which can respond. Forwarding can be used to simplify implementation of certain design patterns, such as the Observer pattern or the Proxy pattern.

The compiler is reporting the point made earlier, that Forwarder does not respond to hello messages. In this circumstance, it is safe to ignore the warning since forwarding was implemented. Running the program produces this output:

////////////////////////////////////////////////////
// msgforward.m
// A Objective C Program to demonstrate Message
// Forwarding.... Adapted from Wikipedia
//
// gcc -x objective-c -Wno-import msgforward.m -lobjc
//
//
#import <objc/Object.h>

//////////////////////////////////////////////////
//
// This class Forwards the message it does not
// recognize to another class....
//
@interface Forwarder : Object
{
////////////////////////////
//
// Forwardee
id recipient;
}


- (id) recipient;
- (id) setRecipient:(id) _recipient;

//--------- generic forwarder....
- (retval_t) forward: (SEL) sel : (arglist_t) args;

@end

//////////////////////////////////////////
//
// implementation of the Forwarder
//
//

@implementation Forwarder

- (retval_t) forward: (SEL) sel : (arglist_t) args
{
/*
* Check whether the recipient actually responds to the message.
* This may or may not be desirable, for example, if a recipient
* in turn does not respond to the message, it might do forwarding
* itself.
*/
if([recipient respondsTo:sel])
return [recipient performv: sel : args];
else {
printf("Recipient does not understand the message\n");

return self;
}

}

//----------- set method...
- (id) setRecipient: (id) _recipient
{
recipient = _recipient;
return self;
}

//-------- Get method
- (id) recipient
{
return recipient;
}
@end

////////////////////////////////////////
//
// A simple Recipient object.
//
//

@interface Recipient : Object
- (id) hello;
@end



@implementation Recipient

- (id) hello
{
printf("Recipient says hello!\n");

return self;
}

@end

//////////////////////////////////////
//
// Entry Point....
//
//
//


int main(void)
{
Forwarder *forwarder = [Forwarder new];
Recipient *recipient = [Recipient new];

[forwarder setRecipient:recipient]; //Set the recipient.
/*
* Observe forwarder does not respond to a hello message! It will
* be forwarded. All unrecognized methods will be forwarded to
* the recipient
* (if the recipient responds to them, as written in the Forwarder)
*/
[forwarder hello];

[forwarder hello2];
return 0;
}




[sandhya@localhost four]$ gcc -x objective-c -Wno-import msgforward.m -lobjc
msgforward.m: In function ‘main’:
msgforward.m:116: warning: ‘Forwarder’ may not respond to ‘-hello’
msgforward.m:116: warning: (Messages without a matching method signature
msgforward.m:116: warning: will be assumed to return ‘id’ and accept
msgforward.m:116: warning: ‘...’ as arguments.)
msgforward.m:118: warning: ‘Forwarder’ may not respond to ‘-hello2’
[sandhya@localhost four]$ ./a.out
Recipient says hello!
Recipient does not understand the message
[sandhya@localhost four]$

Objecitve C Programming Tutorial under Linux - Part 15

In this part , we will learn how to use IMP (implementation pointers ) to do dynamic message dispatching. The messages can take one , two or arbitary number of parameters... and return
a single value...

////////////////////////////////////////////////
// dyndis.m
// A Simple Objective C Program to demonstrate
// Dynamic Dispatch of method....using IMP
//
// gcc -x objective-c -Wno-import dyndis.m -lobjc
//
//

#import <objc/Object.h> // for Object

//////////////////////////////
//
//
//
@interface Test : Object
{
@protected
int _x;
}
//////////////////
//
// ctor
-init;
/////////////////////////
// A method which takes two double arguments
// and return a double
-(double)Gr:(double)gr x:(double) gr2;
//////////////////////////////////////
//
// A method which takes a single integer argument
-(double)Test2:(int)fl;
//////////////////////////////
// A method which returns a double value
//
-(int)Fool;
@end


/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation Test

-init {
_x=1;
return self;
}

-(double)Gr:(double)gr x:(double) gr2 {
printf("Inside.....Gr..\n");
if ( gr > gr2 )
return gr;
else
return gr2;

}

-(double)Test2:(int)fl {
printf("inside ...Test....\n");
return 223.0;
}

-(int)Fool {
printf("Inside ...fool....\n");
return 200;
}
@end


/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{

Test *p = [Test new ];

IMP method_ptr = [p methodFor:@selector(Fool) ];

if ( method_ptr == 0 ) {
printf("Failed to get method ...ptr\n");
return;
}
double c = (( int (*) (id,SEL)) method_ptr)(p,@selector(Fool));
printf("%g\n",c);


method_ptr = [p methodFor:@selector(Test2:) ];

if (method_ptr == 0 )
{
printf("Test2 ..method is not compatible\n");
}

c = ((double (*) (id,SEL,double))method_ptr)(p,@selector(Test2:),100);
printf("%g\n",c);

method_ptr = [p methodFor:@selector(Gr:x:) ];

if (method_ptr == 0 )
{
printf("Gr ..method is not compatible\n");
return;
}

c = ((double (*) (id,SEL,double,double))method_ptr)(p,@selector(Gr:x:),100,101);

printf("%g\n",c);
}






[sandhya@localhost four]$ gcc -x objective-c -Wno-import dyndis.m -lobjc
[sandhya@localhost four]$ ./a.out
Inside ...fool....
200
inside ...Test....
223
Inside.....Gr..
101
[sandhya@localhost four]$

Objecitve C Programming Tutorial under Linux - Part 14

In this part , we will send a message to an object using IMP (implementation pointers )


The following subject matter is taken from the Objective C FAQ

Implementation pointers (IMP)

6.1 What is an IMP ?

It's the C type of a method implementation pointer, a function pointer
to the function that implements an Objective-C method. It is defined
to return id and takes two hidden arguments, self and _cmd :

typedef id (*IMP)(id self,SEL _cmd,...);

6.2 How do I get an IMP given a SEL ?

This can be done by sending a methodFor: message :

IMP myImp = [myObject methodFor:mySel];

6.3 How do I send a message given an IMP ?

By dereferencing the function pointer. The following are all
equivalent :

[myObject myMessage];

or

IMP myImp = [myObject methodFor:@selector(myMessage)];
myImp(myObject,@selector(myMessage));

or

[myObject perform:@selector(myMessage)];

6.4 How can I use IMP for methods returning double ?

For methods that return a C type such as double instead of id, the IMP
function pointer is casted from pointer to a function returning id to
pointer to a function returning double :

double aDouble = ((double (*) (id,SEL))myImp)(self,_cmd);

6.5 Can I use perform: for a message returning double ?

No. The method perform: is for sending messages returning id without
any other argument. Use perform:with: if the message returns id and
takes one argument. Use methodFor: for the general case of any number
of arguments and any return type.


////////////////////////////////////////////////
// IMPSel.m
// A Simple Objective C Program to demonstrate
// run time access of a selector using libobjc
// and use IMP (implementation pointers ) to
// dispatch a method...
//
// gcc -x objective-c -Wno-import IMPSel.m -lobjc
//
//

#import <objc/Object.h> // for Object
//////////////////////////
//
// Declare a Protocol
//
@protocol Renderable
-(void)Render;
@end
//////////////////////////////
//
// Circle implements Renderable Protocol
//
@interface TCircle : Object<Renderable>
{
@protected
int _x;
int _y;
int _radius;
}
//////////////////
//
// ctor
-(TCircle *)initWithXYR : (int) x height : (int) y radius :(int) r;
/////////////////////////
// Rener method from Renderable Protocol
//
-(void)Render;

@end


/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation TCircle

-(TCircle *)initWithXYR: (int) x height : (int) y radius :(int) r{
_x = x;
_y = y;
_radius = r;
return self;
}

-(void)Render {
printf("Rendering Circle x: %d\t y: %d\t radius %d\n",_x,_y,_radius);

}

@end

@interface TArc:TCircle
{
int _sa,_ea;
}

-(TArc *)initWithXYRSAEA: (int) x height : (int) y
radius :(int) r
startangle:(int)sa
endangle :(int) ea;


@end

@implementation TArc
-(TArc *)initWithXYRSAEA: (int) x height : (int) y
radius :(int) r
startangle:(int)sa
endangle :(int) ea{
_x = x;
_y = y;
_radius = r;
_sa = sa;
_ea = ea;
return self;
}
-(void)Render {
printf("Rendering Arc x: %d\t y: %d\t radius %d\n",_x,_y,_radius);

}
@end

/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{


id fp2 = [ [TArc alloc] initWithXYRSAEA:10 height:100
radius:200 startangle:10 endangle:20 ];


////////////////////////////////////////////////////
// -(BOOL) respondsTo: selector ----- true
//
// RTTI

SEL mySel = (SEL)sel_get_any_uid("Render"); // for GNU Objective C


//////////////////////////////
//
// Get the implementation Pointer
IMP myImp = [fp2 methodFor:mySel];

/////////////////////////////////////////
// Call the method using IMP
//
myImp(fp2,mySel);


}






[sandhya@localhost four]$ gcc -x objective-c -Wno-import IMPSel.m -lobjc
[sandhya@localhost four]$ ./a.out
Rendering Arc x: 10 y: 100 radius 200
[sandhya@localhost four]$

Objecitve C Programming Tutorial under Linux - Part 13

In this part , we will learn how we can access selectors using a run time function


SEL mySel = sel_get_any_uid(selectorname);

The following defenitions are taken from the Objective C FAQ

What is a SEL ?

It's the C type of a message selector; it's often defined as a
(uniqued) string of characters (the name of the method, including
colons), but not all compilers define the type as such.

What is perform: doing ?

perform: is a message to send a message, identified by its message
selector (SEL), to an object.





////////////////////////////////////////////////
// Selector.m
// A Simple Objective C Program to demonstrate
// run time access of a selector using libobjc
//
// gcc -x objective-c -Wno-import Selector.m -lobjc
//
//

#import <objc/Object.h> // for Object
//////////////////////////
//
// Declare a Protocol
//
@protocol Renderable
-(void)Render;
@end
//////////////////////////////
//
// Circle implements Renderable Protocol
//
@interface TCircle : Object<Renderable>
{
@protected
int _x;
int _y;
int _radius;
}
//////////////////
//
// ctor
-(TCircle *)initWithXYR : (int) x height : (int) y radius :(int) r;
/////////////////////////
// Rener method from Renderable Protocol
//
-(void)Render;

@end


/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation TCircle

-(TCircle *)initWithXYR: (int) x height : (int) y radius :(int) r{
_x = x;
_y = y;
_radius = r;
return self;
}

-(void)Render {
printf("Rendering Circle x: %d\t y: %d\t radius %d\n",_x,_y,_radius);

}

@end

@interface TArc:TCircle
{
int _sa,_ea;
}

-(TArc *)initWithXYRSAEA: (int) x height : (int) y
radius :(int) r
startangle:(int)sa
endangle :(int) ea;


@end

@implementation TArc
-(TArc *)initWithXYRSAEA: (int) x height : (int) y
radius :(int) r
startangle:(int)sa
endangle :(int) ea{
_x = x;
_y = y;
_radius = r;
_sa = sa;
_ea = ea;
return self;
}
-(void)Render {
printf("Rendering Arc x: %d\t y: %d\t radius %d\n",_x,_y,_radius);

}
@end

/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{

id fp = [[TCircle alloc] initWithXYR:10 height:100 radius:200 ];
[fp Render];

id fp2 = [ [TArc alloc] initWithXYRSAEA:10 height:100
radius:200 startangle:10 endangle:20 ];
[fp2 Render];



////////////////////////////////////////////////////
// Retrieve the Selector using libobjc run time
// RTTI
//
SEL mySel = (SEL)sel_get_any_uid("Render"); // for GNU Objective C


//////////////////////////////////////////
// See if fp responds to selector
//
if ( [fp respondsTo: mySel] == YES ) {

printf( "fp responds to Render method...\n" );

//---------------Now invoke the method ..render
[fp perform: mySel];
}


}






[sandhya@localhost four]$ gcc -x objective-c -Wno-import Selector.m -lobjc
[sandhya@localhost four]$ ./a.out
Rendering Circle x: 10 y: 100 radius 200
Rendering Arc x: 10 y: 100 radius 200
fp responds to Render method...
Rendering Circle x: 10 y: 100 radius 200
[sandhya@localhost four]$

Saturday, April 17, 2010

Objecitve C Programming Tutorial under Linux - Part 12

Long before Java and C# had Reflection API , Objective C had features similar to that. The following program demonstrates four features

[obj isKindOf: class Object ] => Whether class Object is in the inheritance chain of obj
[obj isMemberOf: class Object] =>Whether obj is an instance of
[obj respondsTo: selector ] => Whether obj responds to a selector
[fp perform:selector] => Invoke the selector.

////////////////////////////////////////////////
// MultiHier.m
// A Simple Objective C Program to demonstrate
// inheritance behavior similar to that of java
//
// gcc -x objective-c -Wno-import MultiHier.m -lobjc
//
//

#import <objc/Object.h> // for Object
//////////////////////////
//
// Declare a Protocol
//
@protocol Renderable
-(void)Render;
@end
//////////////////////////////
//
// Circle implements Renderable Protocol
//
@interface TCircle : Object<Renderable>
{
@protected
int _x;
int _y;
int _radius;
}
//////////////////
//
// ctor
-(TCircle *)initWithXYR : (int) x height : (int) y radius :(int) r;
/////////////////////////
// Rener method from Renderable Protocol
//
-(void)Render;

@end


/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation TCircle

-(TCircle *)initWithXYR: (int) x height : (int) y radius :(int) r{
_x = x;
_y = y;
_radius = r;
return self;
}

-(void)Render {
printf("Rendering Circle x: %d\t y: %d\t radius %d\n",_x,_y,_radius);

}

@end

@interface TArc:TCircle
{
int _sa,_ea;
}

-(TArc *)initWithXYRSAEA: (int) x height : (int) y
radius :(int) r
startangle:(int)sa
endangle :(int) ea;


@end

@implementation TArc
-(TArc *)initWithXYRSAEA: (int) x height : (int) y
radius :(int) r
startangle:(int)sa
endangle :(int) ea{
_x = x;
_y = y;
_radius = r;
_sa = sa;
_ea = ea;
return self;
}
-(void)Render {
printf("Rendering Arc x: %d\t y: %d\t radius %d\n",_x,_y,_radius);

}
@end

/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{

id fp = [[TCircle alloc] initWithXYR:10 height:100 radius:200 ];
[fp Render];

id fp2 = [ [TArc alloc] initWithXYRSAEA:10 height:100
radius:200 startangle:10 endangle:20 ];
[fp2 Render];

///////////////////////////////////////////////////
//
// [TCircle class] will give Class Object of TCircle
//
// isKindOf => if the class object is in the inheritance
// chain
if ( [fp isKindOf: [TCircle class ] ] == YES )
printf("fp is derived or an instance of Circle ..\n");

//////////////////////////////////////////////////
//
// if fp2 is derived from Object, it will say YES
//
if ( [fp isKindOf: [Object class ] ] == YES )
printf("fp is a derived from Object..\n");


/////////////////////////////////////
//
// if TArc is in the inheritance chain...
if ( [fp2 isKindOf: [TArc class ] ] == YES )
printf("fp2 is derived or an instance of Arc ..\n");

///////////////////////////////////////////
// if fp2 is an instance TArc
//
if ( [fp2 isMemberOf: [TArc class ] ] == YES )
printf("fp2 is a an instance of Arc ..\n");

////////////////////////////////////////////////////
// -(BOOL) respondsTo: selector ----- true
//
// RTTI

if ( [fp respondsTo: @selector(Render)] == YES ) {

printf( "fp responds to Render method...\n" );

//---------------Now invoke the method ..render
[fp perform:@selector(Render)];
}



}






[sandhya@localhost four]$ gcc -x objective-c -Wno-import MultiHier.m -lobjc
[sandhya@localhost four]$ ./a.out
Rendering Circle x: 10 y: 100 radius 200
Rendering Arc x: 10 y: 100 radius 200
fp is derived or an instance of Circle ..
fp is a derived from Object..
fp2 is derived or an instance of Arc ..
fp2 is a an instance of Arc ..
fp responds to Render method...
Rendering Circle x: 10 y: 100 radius 200

Friday, April 16, 2010

What is testing according to Bjarne ?

Today morning , I read two interviews from the book Mastermind of Programming. The first one was Bjarne Stroustrup and the second one was Guido Van rossum (Python).

"Testing is the systematic search for errors" -Bjarne , Page 6,MasterMinds of Programming.

Objecitve C Programming Tutorial under Linux - Part 11

This part will show a program which simulates Java's always virtual method Philosophy in Objective C. Lot of Java developers are still not aware about this and it has caused many a subtle bugs.

////////////////////////////////////////////////
// MultiHier.m
// A Simple Objective C Program to demonstrate
// inheritance behavior similar to that of java
//
// gcc -x objective-c -Wno-import MultiHier.m -lobjc
//
//

#import <objc/Object.h> // for Object
//////////////////////////
//
// Declare a Protocol
//
@protocol Renderable
-(void)Render;
@end
//////////////////////////////
//
// Circle implements Renderable Protocol
//
@interface TCircle : Object<Renderable>
{
@protected
int _x;
int _y;
int _radius;
}
//////////////////
//
// ctor
-(TCircle *)initWithXYR : (int) x height : (int) y radius :(int) r;
/////////////////////////
// Rener method from Renderable Protocol
//
-(void)Render;

@end


/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation TCircle

-(TCircle *)initWithXYR: (int) x height : (int) y radius :(int) r{
_x = x;
_y = y;
_radius = r;
return self;
}

-(void)Render {
printf("Rendering Circle x: %d\t y: %d\t radius %d\n",_x,_y,_radius);

}

@end

@interface TArc:TCircle
{
int _sa,_ea;
}

-(TArc *)initWithXYRSAEA: (int) x height : (int) y
radius :(int) r
startangle:(int)sa
endangle :(int) ea;


@end

@implementation TArc
-(TArc *)initWithXYRSAEA: (int) x height : (int) y
radius :(int) r
startangle:(int)sa
endangle :(int) ea{
_x = x;
_y = y;
_radius = r;
_sa = sa;
_ea = ea;
return self;
}
-(void)Render {
printf("Rendering Arc x: %d\t y: %d\t radius %d\n",_x,_y,_radius);

}
@end

/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{

id fp = [[TCircle alloc] initWithXYR:10 height:100 radius:200 ];
[fp Render];

id fp2 = [ [TArc alloc] initWithXYRSAEA:10 height:100
radius:200 startangle:10 endangle:20 ];
[fp2 Render];




}






[sandhya@localhost four]$ gcc -x objective-c -Wno-import MultiHier.m -lobjc
[sandhya@localhost four]$ ./a.out
Rendering Circle x: 10 y: 100 radius 200
Rendering Arc x: 10 y: 100 radius 200
[sandhya@localhost four]$

Objecitve C Programming Tutorial under Linux - Part 10

In this part , we will see how one can implement Multiple Protocols. It is how we achieve Multiple Interface inheritance in Objective C

////////////////////////////////////////////////
// SliceSplice.m
// A Simple Objective C Program to demonstrate
// Multiple Protocol implementation
//
// gcc -x objective-c -Wno-import SliceSplice.m -lobjc
//
//

#import <objc/Object.h> // for Object


///////////////////////////////////
//
// Protocol is like interface in java and C#
// or Pure virtual function in C++
@protocol Yelling
-(void)Yell;
@end
/////////////////////////////
//
//
@protocol Yawning
-(void)Yawn;
@end
///////////////////////////////////
//
// Interface of a Class
//
@interface Test : Object<Yelling,Yawning>
{
//----------- private acess specifier
@private
int _num;
int _den;
}

-(void)setNum:(int) num Denom : (int) den;
-(void)dump;
//-------- implementation of Yelling
-(void)Yell;
//--------- implementation of Yawning
-(void)Yawn;
@end

/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation Test

-(void)setNum:(int) num Denom: (int) den {
_num = num;
_den = den;
}

-(void)dump {
printf("%d\t %d\n",_num,_den);

}

-(void)Yell {
printf("Yell......\n");
}

-(void)Yawn {
printf("Yawn .....\n");
}
@end

/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{
Test *rt = [Test new ];
[rt setNum: 5 Denom:6];
[rt dump];
[rt Yell];
[rt Yawn];
}






[sandhya@localhost four]$ gedit SliceSplice.m
[sandhya@localhost four]$ gcc -x objective-c -Wno-import SliceSplice.m -lobjc
[sandhya@localhost four]$ ./a.out
5 6
Yell......
Yawn .....
[sandhya@localhost four]$

Objecitve C Programming Tutorial under Linux - Part 9

In this part , I will write a small example program to demonstrate Protocol (interface as in Java and C# )

////////////////////////////////////////////////
// Protocol.m
// A Simple Objective C Program to demonstrate
// Protocol
//
// gcc -x objective-c -Wno-import Protocol.m -lobjc
//
//

#import <objc/Object.h> // for Object


///////////////////////////////////
//
// Protocol is like interface in java and C#
// or Pure virtual function in C++
@protocol Yelling
-(void)Yell;
@end
///////////////////////////////////
//
// Interface of a Class
//
@interface Test : Object<Yelling>
{
//----------- private acess specifier
@private
int _num;
int _den;
}

-(void)setNum:(int) num Denom : (int) den;
-(void)dump;
-(void)Yell;
@end

/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation Test

-(void)setNum:(int) num Denom: (int) den {
_num = num;
_den = den;
}

-(void)dump {
printf("%d\t %d\n",_num,_den);

}

-(void)Yell {
printf("Yell......\n");
}
@end

/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{
Test *rt = [Test new ];
[rt setNum: 5 Denom:6];
[rt dump];
id r = rt;
[r Yell];
}






[sandhya@localhost four]$ gcc -x objective-c -Wno-import Protocol.m -lobjc
[sandhya@localhost four]$ ./a.out
5 6
Yell......
[sandhya@localhost four]$

Objecitve C Programming Tutorial under Linux - Part 8

There are places where Objective C Syntax is awkward. Some say it is a welcome feature borrowed from the Smalltalk Programming Language. Inspect the code and make a decision for yourself on this.

////////////////////////////////////////////////
// MultiParam.m
// A Simple Objective C Program to demonstrate
// Multiple Parameters
//
// gcc -x objective-c -Wno-import MultiParam.m -lobjc
//
//

#import <objc/Object.h> // for Object

///////////////////////////////////
//
// Interface of a Class
//
@interface Test : Object
{
//----------- private acess specifier
@private
int _num;
int _den;
}

-(void)setNum:(int) num andDenom : (int) den;
-(void)dump;
@end

/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation Test

-(void)setNum:(int) num andDenom: (int) den {
_num = num;
_den = den;
}

-(void)dump {
printf("%d\t %d\n",_num,_den);

}

@end



[sandhya@localhost four]$ gcc -x objective-c -Wno-import MultiParam.m -lobjc
[sandhya@localhost four]$ ./a.out
5 6
[sandhya@localhost four]$

Objecitve C Programming Tutorial under Linux - Part 7

In this part , we will write a Linked List of double values. The class is a naive implementation to learn Objective C features...

////////////////////////////////////////////////
// List.m
// A Simple Objective C Program to demonstrate
// Linked List implementation
//
// gcc -x objective-c -Wno-import List.m -lobjc
//
//

#import <objc/Object.h> // for Object

///////////////////////////////////
//
// Interface of a Class
//
@interface TNode : Object
{
//----------- private acess specifier
@private
double lst;
//----------- public
@public
TNode *next;
//------------ protected
@protected
int test;
}
/////////////
//
//

//---------factory method...
+new;
//------------- ctor
-init;
//--------dtor..well almost..
-free;
//-- A static method to create a node
//unused..at this point of time
+(TNode *)Add:(double)val;

//////////////////
// Will return the pointer to the next
// node inside the chain...
-(TNode *)Next;
////////////////////////////
//
// Will help set the next value...
//
-(void)SetNext:(TNode *)rs;

-(double)Value;
-(void)setValue:(double)val;

-(void)Dump;

@end

/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation TNode

//////////////////////////////////
//
// default constructor...
//
-init {
printf("inside the TNode ctor ...\n");
lst = -1;
next = 0;
}
////////////////////////
//
// implementation of factory method..
//
+new {
self = [super new];
return self;
}
/////////////////////////
//
//

-free {
lst = -1;
[super free];
}
//////////////////////////
// Create a node...
//
+(TNode *)Add:(double)val {
TNode *tmp = [TNode new];
tmp->lst = val;
return tmp;
}
////////////////
//
// Dump the node..
//
-(void)Dump {
printf("%g\n", lst );
}

-(TNode *)Next {
return next;
}

-(void)SetNext:(TNode *)rs {
next = rs;
}

-(double)Value {
return lst;
}

-(void)setValue:(double)val {
lst = val;
}

@end

//////////////////////////////////////
// TList class
//
//
@interface TList : Object
{
TNode *root;

}
-init;
-(void)Add:(double)val;
-(void)DumpAll;
-(id) free;
@end

@implementation TList
///////////////////////
// ctor
//
-init {
printf("inside the TList ctor....\n");
root = 0;
}
/////////////////////
//
//
-(void)Add:(double)val
{
TNode *nd = [TNode new];

[nd setValue:val];

TNode *temp = root;

if ( temp == 0 ) {

root = nd;
return;
}

while ( ([temp Next]) != 0 ) {
temp = [ temp Next];
}

[temp SetNext:nd];

}
///////////////////////
//
//
-(void)DumpAll {

TNode *temp = root;

if ( temp == 0 ) {
printf("Nothing to Display...\n");
return;
}

while ( temp != 0 ) {
[temp Dump];
// temp = [temp Next];
temp = temp->next;
}


}

-free {
TNode *temp = root;

if ( temp == 0 ) {
return;
}

while ( temp != 0 ) {
TNode *todel = temp;
temp = [ temp Next];
[todel free];
}

return [super free];

}
@end
/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{
id lst = [TList new];

[lst Add:5];
[lst Add:15];
[lst Add:25];
[lst DumpAll];
[lst free];
}







[sandhya@localhost four]$ gcc -x objective-c -Wno-import List.m -lobjc
[sandhya@localhost four]$ ./a.out
inside the TList ctor....
inside the TNode ctor ...
inside the TNode ctor ...
inside the TNode ctor ...
5
15
25
[sandhya@localhost four]$

Thursday, April 15, 2010

Objecitve C Programming Tutorial under Linux - Part 6

In this part , we will explore how one can declare a static method in a Objective C class.

give + prefix method instead of (-) prefix.

////////////////////////////////////////////////
// static.m
// A Simple Objective C Program to demonstrate
// static methods
//
// gcc -x objective-c -Wno-import static.m -lobjc
//
//

#import <objc/Object.h> // for Object

///////////////////////////////////
//
// Interface of a Class
//
@interface Test : Object
{

}
////////////////////
// + will be prefixed for static methods
//
+ (void)stSay;


@end

/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation Test

+ (void)stSay {
printf("hello world...\n");
}


@end

/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{
[Test stSay];


}




Objecitve C Programming Tutorial under Linux - Part 5

In this part , we will learn about a generic pointer which can refer to any object. Since the Objective C language works with the help of a run time , we can resolve the call during the run time.

In some case , we might override a method. To refer to the base method , one can use [super methodname].

////////////////////////////////////////////////
// stack.m
// A Simple Objective C Program to demonstrate a stack of integers
//
// gcc -x objective-c -Wno-import stack.m -lobjc
//
//

#import <objc/Object.h> // for Object

///////////////////////////////////
//
// Interface of a Class
//
@interface Stack : Object
{
int x[100]; // instance data
int top;
}

//------------ constructor
- (id)init;
//------------- desctructor
- (void)free;
//-------------- Push function
-(void) Push:(int)val;
//--------------- Pop function
-(int) Pop;

@end

/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation Stack

///////////////////
//
// ctor initialize the top of the stack...
//
- (id)init {
top =-1;
printf("constructor ...\n");
return self;
}
/////////////////////////////////////
//
//
//
- (void)free
{
// call the parent.free
[super free];
printf("dtor....\n");

}
/////////////////////////////////
//
// Push method... not a robust one..
//
- (void)Push:(int) val {
x[++top]=val;
}
//////////////////////////////////
//
// Pop method...not a robust one..
//
-(int) Pop {
int xt = x[top--];
return xt;
}

@end

/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{
//------------- Create an instance of the class Test
// assign it to a generic Object Pointer.. id
id test = [Stack new];

// call Test::setX
[test Push:5];

int r = [test Pop];

printf("%d\n",r);
//--- Release the memory
[test free];


}




Objecitve C Programming Tutorial under Linux - Part 4

In this part , we will write a naive stack (of integers ) implementation. I am not doing any bounds checking in this code...

////////////////////////////////////////////////
// stack.m
// A Simple Objective C Program to demonstrate a stack of integers
//
// gcc -x objective-c -Wno-import stack.m -lobjc
//
//

#import <objc/Object.h> // for Object

///////////////////////////////////
//
// Interface of a Class
//
@interface Stack : Object
{
int x[100]; // instance data
int top;
}

//------------ constructor
- (id)init;
//------------- desctructor
- (void)free;
//-------------- Push function
-(void) Push:(int)val;
//--------------- Pop function
-(int) Pop;

@end

/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation Stack

///////////////////
//
// ctor initialize the top of the stack...
//
- (id)init {
top =-1;
printf("constructor ...\n");
return self;
}
/////////////////////////////////////
//
//
//
- (void)free
{


}
/////////////////////////////////
//
// Push method... not a robust one..
//
- (void)Push:(int) val {
x[++top]=val;
}
//////////////////////////////////
//
// Pop method...not a robust one..
//
-(int) Pop {
int xt = x[top--];
return xt;
}

@end

/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{
//------------- Create an instance of the class Test

Stack *test = [Stack new];

// call Test::setX
[test Push:5];

int r = [test Pop];


//--- Release the memory
[test free];

printf("%d\n",r);

}




Priests are also human beings

Indian priest confesses to sexually abusing girl child

Teramo (Italy): A jailed Indian priest Wednesday confessed to sexually abusing a 10-year-old girl in central Italy after offering her a Santa Claus doll as a gift.

The priest, identified as David, confessed to offering the girl a doll before placing her hand on his genital area when he visited her home Dec 19 last year, Prosecutor Bruno Auriemma said.

"He gave a full and clear confession," Auriemma told AKI in a telephone interview. "He said 'I did it'."

He made the confession in the Teramo prosecutors' office in front of Auriemma, his defence lawyer Giovanni Gebbia, and local priest Davide Pagnottella.

"He was really gutted and confused," Pagnotella said. He said he was there to offer "spiritual support" to the priest who communicated through an English interpreter.

The 40-year-old priest from south India was Tuesday charged with sexual violence in Teramo, 175 km northeast of Rome in the region of Abruzzo.



Priests are also individuals with temptation. Let the law (of the land ) take it's due course of action on this. I do not think forced celibacy is the only cause of this . Every man (given the "opportunity" ) has potential to misbehave with women.
So, next time when you see these stuff do not try to think only priests from certain groups
are vulnerable.

Why was it "delayed" this much ?

When news was on the air that another city was looking for a IPL team (Ahmedabad ) , I thought people will use Narendra Modi "corridor" to escape from the IPL "trouble" by splitting people into political and communal lines.

Lalit Modi , Narendra Modi ( I suspect he is the chairman of GCA as well ) , Adnani Group might be having their own vested interest in this affair.

Now , a dangerous communal game is played by Kochi franchise to split the public opinion by bringing in Narendra Modi angle to the story. Gaikwad surname is
a Gujarati surname . He is a congress leader as well.

When the Modi surname is uttered , most keralites think of Narendra Modi. This is understandable as state is well known for it's "Minority Politics" and news papers
to be "politically correct" picturize Modi as a murderer.

Let all facts come to the light.

As far as i am concerned , these are the unanswered questions

A) Sunanda Pushkar and Tecom (Smart city company) connection ?
B) Sasi Taroor & Sunanda Pushkar Connection ?
C) Will ownership of all teams be announced?
D) Is it true that Modi has other people behind him to pull Kochi team down ?
( Perhaps Narendra Modi might be behind this ...)
E) Did Sasi tharoor misused his office to influence the matter ?
F) Has some middle east "Hawala" money is being pumped to this Kochi consortium ?

Any way , good news is that ED has started a probe and let us hope facts will come out. All the cricket adminstration is full of Politicians ( from Congress,BJP and NCP). I am doubtful whether things will ever come out.

Any way , this controversy is good for the Public. There should be a limit for everything.

Wednesday, April 14, 2010

Masterminds of Programming

Today morning , i read interviews of Brad Cox and Tom Love , co-inventors of the Objective C Programming language from the book MasterMinds of Programming.

The book contains discussions with the inventors of popular and not so popular programming languages which has contributed significantly to the programming practice.

Perception Problem

Prem was critical of Tilak for quitting his posh job and going for a free lance consulting position.

Prem =>"Why did you quit your job ?"

Tilak =>"I was forced to quit...otherwise they would have sacked me .."

Prem =>"How did you know that ?"

Tilak =>"My instinct told me.."

Prem => "Let us go to the Guruji to take his opinion.."

Together they went and met Guruji...

Guruji pondered for a while....

Guruji =>"if you think past was great or future is going to be great...you
cannot take any decision...let us wait and see what is in store for Tilak..."

Tuesday, April 13, 2010

A Comparitive study of Functional Programming in C# and F#

The April 2010 issues of MSDN contains an exellent article on F#. Even though the title of the article is F# basics , the author has succeeded in conveying the essential Functional Programming ideas implemented by F# using C# constructs. Highly recommended.

Even C++ has thrown in the towel

I just finished reading this article. In my previous blogspot , I had commented about the addition of new features which does not add much to the productivity of the programmmer. The C++ language was a primary object oriented programming language of the world . Now , new programmers are prefering much easier and proudctive languages like Java and C#. To gain back some of the lost glory , it's designers are adding linguistic constructs which will make the life of most (remaining ) programmers miserable.

"Before you add a feature , think about a library solution" was the motto of ANSI standard languages. Now, they are also running after "Linguistic confusion".

Adding Parallelism at the language level ( when OpenMP is a doing a good job ...if you want more power.. use intel TBB ) is a source of confusion. The Lambda syntax is tedious as well.

No wonder , the venerable C subset of C++ is used in the System programming world.

What is new in Visual Basic.net 2010 and it's Afterthought

One of my erstwhile colleague sent a link which highlights new features available with VB.net 2010 language. ( http://msdn.microsoft.com/en-us/magazine/ee336123.aspx ).
Triggered by corporate pressures , Programming Languages have evolved in the recent years at
a pace faster than programmers are ready to accept (IMHO).

VB.net has a legacy of 47 years behind it. The syntax of VB.net is quirky because of the "compatibility" (mindset compatibility ! ) issues which MS has to adress. After the addition
of delgates , generics and LINQ , language has become ugly to use.

In my life , i have seen only one first class VB.net programmer ( Wait..Wait...do not pelt
stones at me .. I meant a Programmer who treats VB.net as a first class programming language )
till date. Most others think in C# ( read Sapir Whorf Hypothesis ) and code in VB.net. When i did some code reviews in the past , I saw subtle bugs creeping in to the code because of this programming technique. ( most often when you map A to B , there is potential for data loss from both sides !! [only exception being A be a subset of B ])

Now that MS has decided on a policy of co-evolution (to make VB.net a first class language ) of
C# and VB.net , C# will have feature creap from VB.net. This will destroy the syntatic coherence of C# ( i might be wrong as well..but..this is my suspicion )

Most new language features are Syntatic Sugar. Provide a Macro facility... , everything will be Ok!

Objecitve C Programming Tutorial under Linux - Part 3

In the previous part , we did not free the object once we are done with an Object. The following program shows , how one can use old style object construction and release of the object...

////////////////////////////////////////////////
// test.m
// A Simple Objective C Program to demonstrate classes
//
// gcc -x objective-c -Wno-import test.m -lobjc
//
//
// Objective C language segregates Interface
// and Implementation... They used to call Interface
// as protocol
//

#import <objc/Object.h> // for Object

///////////////////////////////////
//
// Interface of a Class
//
@interface Test : Object
{
int x; // instance data
}

-(int) getX; // getter
-(void) setX:(int) xs; // setter...

@end

/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation Test
- (int) getX {
return x;
}
-(void) setX:(int) xs {
x = xs;
}
@end

/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{
//------------- Create an instance of the class Test

#if 0
// Objective C 2.0
Test *test = [Test new];
#else
// This the way it used to be in 1.0
Test *test = [ [Test alloc ] init ];
#endif
// call Test::setX
[test setX:5];
// call Test::getX
int r = [test getX];

//--- Release the memory
[test free];

printf("%d\n",r);

}




Objecitve C Programming Tutorial under Linux - Part 2

In this part , we will learn how to create a class using the language constructs.

By default , all the classes derive from the class Object ( A Practice copied by Object Pascal [ TObject , TClass ] , Java ( Object ) and C# ( Object ) )

////////////////////////////////////////////////
// test.m
// A Simple Objective C Program to demonstrate classes
//
// gcc -x objective-c -Wno-import test.m -lobjc
//
//
// Objective C language segregates Interface
// and Implementation... They used to call Interface
// as protocol
//

#import <objc/Object.h> // for Object

///////////////////////////////////
//
// Interface of a Class
//
@interface Test : Object
{
int x; // instance data
}

-(int) getX; // getter
-(void) setX:(int) xs; // setter...

@end

/////////////////////////////////////
//
// Implementation of the class
//
//

@implementation Test
- (int) getX {
return x;
}
-(void) setX:(int) xs {
x = xs;
}
@end

/////////////////////////////////////////
//
// Entry Point....
//
//

int main( int argc , char **argv )
{
//------------- Create an instance of the class Test
Test *test = [Test new];
// call Test::setX
[test setX:5];
// call Test::getX
int r = [test getX];

printf("%d\n",r);

}






[sandhya@localhost two]$ gcc -x objective-c -Wno-import test.m -lobjc
[sandhya@localhost two]$ ./a.out
5
[sandhya@localhost two]$

Objecitve C Programming Tutorial under Linux - Part 1

I worked with Objective C Programming Language under Windows using a stepstone compiler. I found the language to be amusing back then.

For a change , i tried compiling a sample program from Wikipedia. It did not compile properly until , i issued

su -
yum install gcc-objc

All C Programs are valid Objective C Programs !

////////////////////////////////////
//
// A Simple Objective C Program....
// Look at the #import ( instead of #include )
//
// before compilation... install Objective C support
// In Fedora 10 , yum install gcc-objc
//
// gcc -x objective-c -Wno-import first.m
//
//
//

#import <stdio.h>

int main()
{
printf("hello world\n");
return 0;
}


[sandhya@localhost one]$ gcc -x objective-c -Wno-import first.m
[sandhya@localhost one]$ ./a.out
hello world
[sandhya@localhost one]$

Monday, April 12, 2010

Kochi - does it deserve a IPL team ?

When Lalit Modi released the composition of ownership of the Kochi team , lot of "shit"
beneath the pit came out. Even though the intention of Lalit Modi is questionable , thanks to him , people have started asking the question which lingered as a doubt in their mind.

So far , Kerala has produced only two international stature cricketers in the form of SreeSanth and Tinu Yohannan. SreeSanth has managed to stay in (and out of ) the team for five years and IMHO , he is India's best Test bowler at this point of time. Unfortunately, Tinu Yohannan managed to play only couple of matches as hecould not cope up to the pressure of internationalcricket matches. Most Keralites hate SreeSanth and I am doubtful whether he will be part of the Kochi team.

IMHO , Kochi or Kerala does not deserve a cricket team. Even if a team is granted , it should have gone to Trivandrum as Trivandrum league is much more compettitive than Eranakulam (Kochi) League.

The point I am trying to drive home here is do not exonerate a person just because he "engineered a back room revolution" in Kerala Cricket.

A Good PDF document for Windbg Debugger

Windbg debugger is a must for people who write system programs under windows. The debugger is more powerful than Visual C++ debugger. The following PDF document is
a good read to operate the debugger.

http://www.windbg.info/download/doc/pdf/WinDbg_A_to_Z_color.pdf

A good site for System Programmers , Testers

http://www.dumpanalysis.org/ is a cool site useful for Programmers

who are interested in Debugging , Testing and System Programming

on Windows.

Humans are desitned to be like Ants ?

Ant Colony seems to be a good metaphor for the future of our species. I am writing this shortly after a (early morning ) conversation with a friend of mine who was cribbing about the lack of useful "general knowledge" among most people. ( He was talking about Computer Programming.).

After giving some thoughts on this , I feel ( like lot of people before me ) that specialization is
necessary for a person to survive in a matured industry. ( The guy in question started his professional life when software engineering was in primitive state where he lives ) Rather than
blaming these youngsters and not so young people , we should learn a lesson.

Thanks to the internet , we have got enough Knowledge. The Knowledge acquired should be
transformed into skill and expertise. There "sweating it out" is the only way. Without specialization , one cannot acquire deep skill set.

I am seeing a pattern where the "Crowd" can take decisions easily (thanks to easier information retrieval facilities ) and the action item has to be implemented on the ground by all. We are becoming specialized like an Ant colony. Physical Effort , Procedural Knowledge is essential to survive in this modern world. ( Being a great fan
of Analytical Knowledge and reductionism,i find hard to adjust to this paradigm shift )

Is this the same Sunanda Pushkar ?

Shortly after the Lalit modi "Expose" about the ownership of Kochi IPL team , I got a mail forwarded by an ex-colleague (containing the image below).













The lady in the image is associated with TECOM company incorporated in the United Arab Emirates. In Kerala , there is a "non-existent" ( over hyped , real estate oriented ) infrastructure project called SmartCity. The TECOM company is negotiating hard for getting "exclusive" access of the land to be allocated by the Govt. This has got serious security implications.

I am seeing disturbing connections here. Is our "much hyped" minister under her spell ( engineered by the TECOM company ) ? or there is much to be known behind the Facade?.

Create Your Own Programming Language !

I happen to stumble upon an Interesting link @ http://createyourproglang.com/?hop=ax2503.

if you feel the above stuff is expensive ...try to learn from http://slangfordotnet.codeplex.com

Kerala GTUG Launch Event






The Kerala GTUG community launch meeting was held @ Technopark , Trivandrum on 10th April , 2010.The Venue was Zenith Hall, UST Global. The Total number of people attended the event might be between 150 and 200.










After Registration formalities , the meeting got a start around 10.10 am. The
Key note speaker was SreejuMon K.P. , Who is a prime force behind the setting up of this community in Kerala. Even though Google and Microsoft is at war elsewhere , the person who runs the biggest Microsoft User Group is also the brain behind Google Technology User Group.












He talked about the necessity of having a community for google technologies and all along his speech the experience of running a community could be seen in his approach. This will help the group to get bootstrapped much faster.













The first technical session was taken by Praseed Pai K.T. ( it's me ! ). The Session talked about the context in which the Google corporation was born. The Talk discussed about

a) Randomized Algorithms & it's Applications
( Area computation and 3D Rendering of Cornell Box )
b) PageRank Algorithm specifics
c) MapReduce Programming Model
d) How Open standards got a boost because of Google.
e) Some Google APIs (O3D API as a case study )
f) Google Summer of Code, Project hosting , AppEngine

There was a 15 minute cofee break.














The next session was taken by Anash Oomen , a development engineer from Google Coroporation. His session was very interesting as he did show how to develop Pluggins using JavaScript, HTML and CSS. The session covered the Execution model of Pluggins and Packaging as well. At Times , the session became very technical as there was questions regarding the internals of Pluggins and Native Plugin Development.

The Key Takeaways include

a) How to Write Pluggins using JavaScript.
b) Packaging semantics and role of Json
c) Pluggin Execution Model.
d) Role of IPC in Pluggin Execution
e) Native Plugins ( in C/C++)









Who said there is no Free Lunch. Free Lunch coupon was given for all the attendees and
we had a good vegetarian meals at the Canteen.








After the Lunch , SreejuMon took an interesting session on Google Search Techniques. He
did show how one can use a search mini-language available with Google search services.
The language can be easily learned , if you are familiar with boolean conditionals and
regular expressions.

The Key Takeaways include
a) We can do semantically valid search
b) Mini Language and it's use
c) How we can filter and set constraints
d) Boolean Search
e) Matching Synonyms




The Last session was taken by Rajesh Varghese , a SEO professional. His presentation
skill was exceptional. Unfortunately for me , i could not understand everything as
my SEO lingo was rather poor. Thanks to him , i understood some stuff about SEO.

The Key Takeaways include
a) SEO strategics
b) Multi Variate Analysis
c) SEO Internals
d) The Mind of a SEO specialist

Before winding up , Goodies were distributed to the participants and presenters ( T-shirts,
Pens and Labels ).

Sunday, April 11, 2010

Arranged Marriage Blues..!

Prem and Tilak were discussing issues regarding the arranged marriage system of Kerala.

Prem => "Are Yaar , Marriage is not a one time affair ...!"

Tilak => "Why did you say so ?"

Prem => "Chances for a divorce is high now a days.. Paradoxically,most youngsters assume that marriage is a one time affair. This is one of the causes for the delay of their marriages."

Tilak =>"Why cannot you marry Aparna tomorrow ?"

Prem => "I am not a Shoaib Malik to divorce her the next day citing incompatibility or obesity .... so..i have to be cautious..."

A Good Restaurant for Intellectual Discussion

We spent a good two hours @ Chefmaster Restaurant discussing lot of subjects ranging from Economics to Marital Woes. It is one of the best place to surf the net as Wi-fi zone is one of the fastest available in Kerala. The restaurant is situated opposite the Medical College Entrance Inside the TRIDA building @ Trivandrum.

Saturday, April 10, 2010

Map/Reduce in Scheme (Written for Kerala GTUG Event )

The inagural Kerala Google Technology User Group meeting was held on 10th April 201o @ Technopark , Trivandrum. I did give a presentation on Google and it's impact on Software Development.

I Wrote couple of scheme functions to demonstrate MapReduce Programming Model.

(define (sqr x ) ( * x x ))


(define (mymap fn lst )
(cond ((null? lst ) '())
(else (cons (fn (car lst))
(mymap fn (cdr lst ))))))

(define (myreduce fn lst init )
(cond ((null? lst ) init )
(else (fn (car lst )
(myreduce fn (cdr lst ) init )))))

(myreduce + (mymap sqr '( 1 2 3 4)) 0)
(myreduce * (mymap sqr '( 1 2 3 4 )) 1)
(map (lambda ( x ) (* x x )) '( 1 2 3 ))

> (myreduce + (mymap (lambda (x) (* x x )) '( 1 2 3 4)) 0)

30

>