Thursday, July 28, 2005

Today's song and gyan

Today's note: One of my photos on Dheepak's blog. Check it out! (29/07/2005 - 10:00AM)


Eagleheart - Stratovarius Posted by Picasa

All through the night he is lying awake
Wondering how much more can he take
Watching the walls where shadows dance
Drifting away into a trance.
And his eyes are blazing with fire

Dreams burnt to ashes so many times
Highest of mountains, still he climbs
Ready to fly because he just can't stay
Flame burning brighter with every day
And his eyes are blazing with fire
Longing for the deepest desire

Heart of an eagle
He flies through the rainbow
Into a new world and finds the sun
Spreading his wings above all the sorrows
The glory of Eagleheart

Fever is burning in his veins
Determined with courage breaking the chains
Back against the wall under blood red skies
Prepared to fight until he dies.

Gyan: (For guys only!) Single girlfriend is a SPOF(single point of failure). Always have an optimal number of girlfriends :)) (I hope Pooja does not read this!!)

Tuesday, July 26, 2005

A lot can happen over a coffee!


A lot can happen over a coffee! Posted by Picasa

The much talked and discussed about Blogger's meet - one which was seen being planned, planned, talked about, talked about more and more without anything to show forth! - IT FINALLY HAPPENED! It was the 24th of July, Sunday. All gods seemed to be against getting some like-minded people together! It was raining cats, dogs, may be even pigs!! Naren had an important covert mission to fulfil, Raju was peacefully asleep - may be a bit too peaceful! Keshav was stuck in the rain. This was looking bad. I just rang up everyone for one final time half hour before the scheduled meet. To my surprise, everyone said "Be there in 30 mins" - as if to defy all the odds of nature (remember the cats, dogs and pigs??)

Keshav lived up to his billing as the most punctual and was the first to arrive. I followed closely and to beat the rain, we went inside coffee day and helped ourselves to an irish coffee each. Naren was the next to arrive - he seemed distracted. Every now and then he'd look at his mobile phone with a "Why is'nt it ringing?!" look. Raju was the last heroic entry. Even after being offered a pick up and drop, he HAD to come on his war-horse completely drenched in rain! Kudos to Raju!! He even did a jig for the dull coffee day audience! Value for money - not only for us, but for the entire coffee day as well! "Btw - that was for drying my pants" he said! :))

There was no hesitation on anyone's part trying to think what to talk now that we've got together! That's the benefit of a few like-minded people - instantly gelling together and letting loose all the talk of the town. These were people who had known each other for a long time - known each other through blogs. Seriously, it makes sense to draw a mental picture of people by the way they write, by the topics they write about, etc. And it was great to know that (at least for me), I was correct in deducing about these people. Discussions, debates galore.

"Why is F1 such a craze?! Is it really worth the money invested?!"

"What about football or any other sport for that matter?!"

"I could say the same thing about metal music!" (BTW - This was Raju!)

Raju was not having anything. "I'm not hungry and I hate coffee. If I've to have anything, it'd be just for the sake of having something". Yes dude, we all are in the same boat. We don't meet at coffee day to eat and drink the whole day, that's unless someone's earning way too much!! And, abt the coffee - I LOVE COFFEE!! Reluctantly he ordered a strawberry frappy, frappee, frappe - "shit! How do you pronounce this thing?!" he blurted out! Discussion off to a tangent - Some of the items in the menu - how the hell to pronounce them "properly". How to say "Mocha" - mocha or moCha - jeez, this is'nt getting any easier to type!! :)) The waiter is standing amused + dazed! He sheepishly reminds us of his persistent existance near the table. We're all brought back to the context of ordering Raju's strawberry frappe! "Strawberry juice - this is just juice - and they call it some tongue twisting name" Raju says and we all have a hearty laugh!

I'd got 4 jukebox coupons hoping everyone of us could play a song of their own choice. Since, both Keshav and Raju were not so keen on playing music, I helped myself to some of my favorite music :D. Poor people they had not anticipated that they'd have to go thru the running commentary along with the playing songs, giving details about the song, artistes and the significance of the songs :D. Then the ace photographer (read Srini :D) set up his camera timer to take a picture of the illustrious 4 who made it to the first blogger meet! (That has not been published for copyright reasons!)

Time flew by so fast, and the rain also had stopped pouring. It was almost 3 hours! Making a wise decision to avoid getting stuck in the late evening rain, we called it a day at 6:30PM. It was a great experience and all of us were of the feeling that we must do this often. And also, get more people to come to these meets.

So, the next blogger meet will happen soon!

Friday, July 22, 2005

One lil' problem

I borrowed this idea from this friend of mine. Instead of me blurting out some C++ funda, this time I'll pose it as a question. Will post the solution on this very same post on monday.

How to simulate a 'final' class of Java in C++? A final class is one which cannot be extended by inheritance. There's no built-in language mechanism in C++ to disallow inheritance. So, the solution would involve using some other C++ constructs to make a class behave like a final class.

I have one solution for this. There might be other solutions too. If you arrive at a solution, please mail the solution to me at srinivasa.s@gmail.com

My solution would follow here...

template < typename T >
class MakeFinal
{
  private:
    // declare/define all ctors & = op here

  public:
    // nothing needed actually

  // This is the line that makes this solution!
  friend T;
};

Now - for any class that you'd want to make final, just inherit from the above class virtually!

class MyClass : virtual public MakeFinal< MyClass >
{
  // ...
};

Inheritance from MyClass would not work, because MakeFinal has only private ctors. MyClass is a friend of MakeFinal, so it can call the private ctors of MakeFinal. But since the class inheriting from MyClass is not a friend of MakeFinal and since MyClass inherits virtually from MakeFinal, the inheriting class cannot call MakeFinal's ctors.

Hope this was a good solution... Do let me know if I missed anything.

Wednesday, July 20, 2005

Replay: Real forwards! - Part 2

Absolutely hilarious!! :))

****
I enter the class and sit down in the 4th bench. The teacher is talking something about how packets are routed when a network is congested. Of course, this does not concern us in any way. We have other, more important things to do. The gang is discussing euthanasia, or mercy killing.

Sunny: "If that patient is so ill that he cannot live, and wants to die, just let him die no. What is your problem?"
Sridhar: "But someone simply cannot die. He owes a debt to society."
Sunny: “But he will get his insurance money. He can pay off all his debt.”
Sridhar: “Not that kind of debt. See ... He owes society his life”
Sunny: “He did not buy it did he?”
Sridhar: “Buy what?”
Sunny: “Wait… Listen… Life is free”
Me: “Mine was probably bought in a half-price sale”
Saurav: “I bought Nike floaters yesterday… Half price…”
Krishna: “Really? Where? ”

… And the discussion goes off on a tangent … But it brought back by the forceful Abishek

Abishek: “This is just like suicide. I don’t want to live, so I die.”
Sunny: “Yeah, It’s like me asking you to suicide me. It’s simply a callback function”
Karunanidhi: "Some things are beyond the normal. We have to transcend our consciousness and touch the spirit within to understand the "maya" that the world around us is. Why does GK wear that red jacket all the time? It is simply inexplicable."
Me: "Hey look... Let's not talk about my jacket ok..."
Raghu: "Yeeno nidhi... Thames nalli T*** T****** bandya? yeenu english hoditaidiya?"
Linus: "I hope they use Linux on all the hardware. 'cause if they are using windoze, it might crash and the hardware might malfunction and the patient might....err.. survive!!! We don't want that to happen. We have to ensure that the patient dies..."

(Anup is in the back bench... He makes an obscure reference about Sunny, which is overheard.)
Sunny: "One of these days, I am going to euthenize Anup..."
Me: "But what about moral issues? What about ethics?"
Kris: "Chicks? Someone say chicks?"

… And again off on another tangent …

After talking about euthanasia in general and nothing in particular, we reach no conclusion.

In the meanwhile, the teacher has noticed the sound levels rising in class. To bring it under control, he shouts:

Teacher: “What happens when this link is down. How is the congestion controlled in the
network?”

I take some time to realize that the question was addressed to me.

Me: “Err… Sir… If the node A is down and it’s link to the flanking nodes is handled by the transport layer entity which is at the peer level in the corresponding layer at the remote host, the congestion will be rerouted through alternate paths as calculated by the distributed system
either by Dijkstra’s algorithm or ad-hoc routing through peer-mobile networks, whichever has shorter turnaround times as determined by the local host trying to communicate through the
communication channel.”
Teacher: “Sit down…”

Let’s take a re-look at the above conversation, only this time, with a computer’s perspective.
Algorithm used by GK to determine answer to the asked question (in C++):

Question * q = getQuestion();
delete q;
Dictionary dict = getDictionary(COMPUTER_TERMS);
while ( ! target.isDazed() ) {
  Word w = dict.getRandomWord();
  cout << w;
}
cout << endl;

The corresponding messages ( output of the STDERR stream ) of teacher :

brain@teacher : Input error… encoding of stream could not be determined!!
brain@teacher : Parse Error… Un-understood term:flanking
brain@teacher : Parse Error… Unrecognized tokens in input stream
brain@teacher : Parse Error…
brain@teacher : Page fault… Restarting listening daemon…
brain@teacher : Listening daemon… Could not bind to ear…Too much noise in class
brain@teacher : Retrying… Connection Established…
brain@teacher : Parse Error… Could not determine the question to which answer is been given…
brain@teacher : Warning!!! Flow control error… Some or all packets may be lost
brain@teacher : Error… Unknown error!!!
brain@teacher : Error… Too many errors…
brain@teacher : Confused by earlier errors… bailing out…
brain@teacher : Throwing exception “Sit Down”.
Expected to stop input stream. Raise error “DazedLook” to display_module

So now you know… The “sit down” command is really an exception thrown to make the student stop talking.

Friday, July 15, 2005

Fore-warned is fore-armed

Many of the networking or related applications have to marshal/unmarshal packets to/from structures. And its not uncommon to have more than one field within a byte of a packet. So, what's the best way to construct a packet before sending it over the wire? Say, a SCSI CDB (command descriptor block - similar to an SNMP packet) has to be sent to a device target. Lets simplify the whole thing and say that just 1 byte consisting of 8 1-bit flags is to be sent over the wire. What's the best way to represent such a byte? The first solution that comes to anyone's mind would be bitfields. So, let's go ahead with that.

typedef struct CDB_Byte {
  unsigned char a:1;
  unsigned char b:1;
  unsigned char c:1;
  unsigned char d:1;
  unsigned char e:1;
  unsigned char f:1;
  unsigned char g:1;
  unsigned char h:1;
} CDB_Byte;

Now I want to set only the LSB(least significant bit) and the one next to it. Okay, that's simple.

CDB_Byte byte;
byte.h = 1;
byte.g = 1;

But, I have a question. Is this the correct way to do it? The answer is NO. Let me illustrate why this is'nt the correct way with a simple example.

unsigned char c = 0x01;    // LSB set
CDB_Byte byte;
std::memcpy(&byte, &c, 1);    //copy the bits
// to change the value of 'c' to 0x03
byte.g = 1;    // set the bit next to the LSB
std::memcpy(&c, &byte, 1);     // copy the bits back
std::cout << (unsigned)c;

Will this print '3'? The answer is 'depends'. The language standard does not say anything about the allocation of bitfields. The compilers are free to implement them as they deem fit. On linux, the gcc compiler allocates the bitfields starting from the LSB. This can be verified - the above piece of code prints '65'.

hgfedcba

However on HP-UX, the aCC compiler allocates bitfields starting from the MSB. The above piece of code prints '3' (as one might have expected in the first place).

abcdefgh

Moral of the story is this: Never use bitfields to construct structures containing sub-byte fields. Always use a void * chunk of memory, extract a byte, and use masks and bitwise operators to set/extract sub-byte fields. At least, if you expect your application to be portable, don't use bitfields! I would say that bitfields should never be used anyway, 'cos there's no guarantee that the same application will run on the same platform if the compiler vendor rolls out a newer version.

Fore-warned is fore-armed!

Wednesday, July 13, 2005

Replay: Real forwards!

This is a part of the "Real forwards" series that was so rampant in our college days. Read on this marvellous "creation" :))

****

There is a project going on to write a poem for one of [X]'s RGFs (RGF = Remote Girl Friend as described in RFC 27342). These RGFs are all outside Bangalore. There is a lot to tell about [X]’s good luck. He seems to get all the RGFs he wants. Girls mysteriously call him and message him. He meets these girls “quite by accident” he says. Serendipity, he calls it. Bullshit I say. Anyway, here is the beta-1 release of the poem for RGF #1, who is sitting somewhere in Mumbai.

“The Fluttering candle”

Ooo my dear rosy
You make me all woozy
I am here, sitting in IP class
You are there, hope you don’t have SARS

What is life: Love and friendship?
Woe is me, with all my hardship
Our meeting, it cannot be incidental,
Nothing else rhymes, so I’ll say environmental

You came in my life like a tornado
And left my little soul like a tomato
My kidney, liver and heart, have formed a group
Swimming like a bread crumb, in tomato soup.

All of us look over our marvelous achievement in poetry. If poetry had a modern-art edition, it
would be along similar lines.

****

How was it?!

Tuesday, July 12, 2005

This ain't no movie!

A social gathering - party to be precise... A sea of people (well almost) - some known faces, some unknown, some enjoying, some pretending to be enjoying, some absolutely lost without a clue as to what's going on. Such variety of people around - he looked at the crowd once more, for the topology of people had changed. Everytime he looked around, he was almost amused to see people doing things they were doing. Presently he could see a lady walking towards him.

"Hello beta! Do you remember me?", she asked him
He pretended to concentrate hard and suddenly said "Ya! Yes, yes - I do remember..."
"So, I heard now you're earning since a year. Very good beta. I'm so proud of you" she continued.
"Ya, just completed a year. Thanks" He had to say this. Suddenly she turned away from him and called out to someone in the crowd.
"Pooja, come here..." - He could see a girl coming towards them.
"This is my daughter, Pooja" She introduced her to him.
"Hi!" she said.
"Hello". He somehow did not like this.
"You two be talking, I'll be back shortly" she said, and disappeared into the crowd.
"Just like in the movies eh?!" he asked
"Like what?" She asked
"You know, parents introduce a boy to a girl and conviniently leave the scene" he said
"Oh ya. Always happens na?" she chuckled.
"How lame I must say! By the way, I still don't know who she was and who you are - please pardon my ignorance" he said matter of factly.
"Oh that's alright. As long as you know my name, that's enough for a conversation. And yes, that's a very lame trick and I hate it!" she said.
Oh great, someone who seems to think similarly, he thought to himself.
"I don't know about you, but I'm hungry. How about having something to eat?" he asked her.
"I'm hungry too. Sure" she said.

THE END

Hey, hey - what were you ppl expecting?? This ain't no movie!!!! :))

Friday, July 08, 2005

Strange lookup rule

This post is purely technical and uninterested people can hit the back button immediately.

This is something I never knew and read about it recently in "Exceptional C++". Let me start with a code example...

namespace A {
  class S { };
  void foo(S& parm) { }
}

namespace B {
  void foo(A::S& parm) { }
  void bar(A::S& parm) {
    foo(parm); // Which "foo" does this call?
  }
}

Try this out and to your surprise you'll find that this gives a "call to foo is ambiguous" error. But why?? The only foo visible at the place of call is in namespace B. Why should this result in an error? Okay, now try this out - comment out the "foo" definition in namespace B.

namespace A {
  class S { };
  void foo(S& parm) { }
}

namespace B {
  // void foo(A::S& parm) { }
  void bar(A::S& parm) {
    foo(parm); // Which "foo" does this call?
  }
}

This compiles without errors! Surprised again? When you run the program, it'd have called A::foo. What happened here? Does this not appear to be a namespace violation. Apparently not! This strange behavior is explained by "Koenig lookup".

If you supply a function argument of class type (here parm, of type A::S), then to find the function name the compiler considers matching names in the namespace (here A) containing the argument's type.

But still, is'nt this a namespace violation?? NO. Just consider this piece of code...

std::string str("Hello");
std::cout << str ;

This works fine right? How? This works because of Koenig lookup. The function in question here is "operator <<" which is found in "namespace std". But we have'nt used any "using" declaration to bring that function into the current scope. Since std::string is going as an argument into that function, the compiler will automatically look into the std namespace and will find that function. Without this kind of lookup, the same function call would have to be written as...

std::operator <<( std::cout, str) ; // ugly! ain't it??

This is the great value that Koenig lookup gets us and we tend to use it every now and then without realising it. Interesting - is'nt it??

Wednesday, July 06, 2005

Phone hang!

Wow! I thought I could stress-test just my comp! Turns out that even my mobile phone is susceptible to my usage. I'd call this my newest stress-testing benchmark for mobile phones. Okay - what I have is a rather old nokia 3530. Yesterday while I was in the lab, busy doing something, I received a message which warranted a quick reply. I went on the replying path very rapidly. I've got delivery reports set to "on". So, while checking up and deleting the report, my cell phone "hung". YES, it hung bloody! And what more?? I've been able to "reproduce" the hang quite consistently - now I know the exact sequence of operations that leads to a hang.

Since I work on firmware, I can guess that even mobile phones have their own OS (what nokia calls as "nokia OS"). These wont be a full fledged OS but a minimal implementation of job scheduling and dispatch and may be some trivial memory management. And some sort of firmware that runs over this OS service is responsible for all the activities that the user expects. This hang could well be the result of some sort of deadlock within the phone firmware. Err - now can I report this somewhere?? :D

Friday, July 01, 2005

Song for the weekend


Posted by Picasa

Cold winter nights

Summers gone a while ago
The daylight dims away
I'm watching here
how the snow begins to fall

Yesterdays like a dream
A memory in my head
Like the lifes gone behind the winter wall

I'm lighting up the candles
and lock the door
Sitting by the fire
Its time to dream some more

I have to find a way how to survive
I am surrounded by the starlight
I have to find the path and to
escape from the Cold Winter Nights

And in the morning there's no trace of the sun
Just gray fog hanging above my head
All the birds are quiet hiding in the woods
Cant see no movement are they all dead?

From the new album of Stratovarius - "Destiny"
Happy weekend :)