Skip to main content

Posts

Quiz: Beauty of Numbers

Sriram asked: Imagine there is a queue of people for getting a ticket for a movie or somehing. Where should be standing in the queue to last until the manager or some guy keeps removing people at odd indices. For instance, if the queue has 5 people given a token A to E, first we remove the first set of odd numbered positions in the queue, so A, C and E are gone. Now B and D remain. Again we remove the odd numbered positions. This time B alone is gone, and D is the winner. So in a queue like that, what is the lucky position you should hold so that you survive the wave of removals? I could give you the solution right here in front of your eyes. But that would not give you time to think to solve it on your own. So solve it and\or read the solution here .

To Hold or Not to Hold – A story on Thread references !!!

void SomeMethod(int x, double y) { // some code .... new Thread(ThreadFunc).Start(); } What do you think about the code above? Some may say nothing seems to be wrong. Some may say there is not enough information to comment. A few may say that it is awful to spin off a thread like that (the last line of the method), and that there is a probability for the thread to be garbage collected at an unexpected point of execution. That is something interesting to discuss about. Before presenting my thoughts and supporting facts, the short answer is NO. A thread spun off like that will not be garbage collected as we expect, although one should be morally insane to write such code. Alright, let us discuss. The Thread class is like any other reference type in the BCL. When an instance of a reference type holds no more outstanding references, it is a candidate to be garbage collected. Even worse, it could become a candidate even while it is executing an instance method, while there ar...

Crazy Brackets - [](){}();

What does this cryptic bracket sequence mean? What programming language is it? Is it valid syntax? If there is even a weak chance of this syntax being valid, then what does it mean? Alright, alright, alright.....It is C++. That would calm most people; with all their love (pun) for C++. Specifically, it is C++0x. Amongst many other features that we have been waiting for, C++0x gives us the power of lambdas. The formal definition of a lambda in C++0x is as follows:- [capture_mode] (parameters) mutable throw() -> return_type { body } So a lambda may capture one or more variables in scope by value or by reference, or it may capture none. Specifying return_type is not necessary if the type can be inferred or is void. For instance, a std::for_each 's functor based code could be inlined with a lambda as follows:- std::for_each(v.begin(), v.end(), [](int x) { cout << x << std::endl; }); A lambda definition could be assigned to a variable and then used or in...

Wetting my feet in Android - Seinfeld Calendar

A couple of my colleagues and I huddled up to learn a bit of Android. I think I told you about that a short while back. We developed a very simple application - The Seinfeld Calendar . Seinfeld calendar, or otherwise called the habit calendar, is Seinfeld's productivity secret . The secret of achieving your goal is practising something, whatever your goal is, everyday and make it a habit. And mark it in your calendar each day you practice, and make sure you do not break the chain. Our application helps you keep track of your everyday tasks. Our application does not jog or meditate or quit smoking for you. You have to do your tasks. Our application provides the facility to create tasks for the habits you wish to pursue, which in certain cases like smoking means quitting. And then you mark each day in the calendar if you pursued your task, else you don't mark and break the chain. And no cheating! The application is in very nascent stage and does not provide you (fancy) s...

Anonymous Classes vs Delegates !!!

I am not a java programmer. By that, I do not mean I am against Java. As a programmer by profession and passion, I try to learn things along the way. That includes a little of bit of Java. I should say that my proper encounter, so to say, with Java is a simple application that I am trying out with Android. There might be some hard core differences and/or limitations in the Android version of Java. But I am almost certain that I am using only primary level features of Java. In android, there is this OnClickListener interface, which is used as a callback interface for a button click. So, it is used something like this:- // Create an anonymous implementation of OnClickListener private OnClickListener mCorkyListener = new OnClickListener() { public void onClick(View v) { // do something when the button is clicked } }; protected void onCreate(Bundle bundle) { ... Button button = (Button)findViewById(R.id.someButton); button.setOnClickListener( new OnClick...

Quiz - Where am I?

The question is, in C++, how do detect if an object is allocated on the stack or heap. On Windows, the stack address is in the range of 0x80000000. If the address of the variable is in this range, then you could say that the object is allocated on the stack; else it is allocated on the heap. This technique of detecting is not preferrable since it may not work on other operating systems (such as linux), and deals with the platform specific information making it a non-portable solution. Let us try to use standard C++ stuff to solve the problem. Ok, we want to know where an object is allocated. In C++, new operator is responsible for allocating an object. It was very thoughtful of Stroustoup to keep the object allocation and initialization\construction separate. new operator is responsible only for allocation. The compiler is responsible for woving up the code for allocation and calling the constructor. It was also very thoughtful of being able to specify the location where the ...

Guess Who?

You may not know the guy in black; but you sure should be knowing the guy in green. Don't know him ? I am not a patron of his philosophies against planned design. But he sure is a great guy with lots of good ideas. It was nice having an hour long chat with him.

Invoking methods with out and ref - Finale !!!

Alright, it is a long wait. And I am going to keep it short. Recap of the problem: Why did the ref variable in SomeMethod not get the expected result ( DayOfWeek.Friday ) when called from a different thread? Boxing. Yes, that is the culprit. Sometimes, it is subtle to note. DayOfWeek is an enum - a value type. When the method is called from a different thread, we put the argument (arg3) in an object array, and that's where the value gets boxed. So we happen to assign the resultant value to the boxed value. So how do resolve the issue? Simple.......assign the value back from the object array to the ref variable. int SomeMethod(string arg1, string arg2, ref DayOfWeek arg3) { if (Dispatcher.CheckAccess()) { var funcDelegate = (Func<string, string, DayOfWeek, int>)SomeMethod; var args = new object[] { arg1, arg2, arg3 }; int retVal = Dispatcher.Invoke(funcDelegate, args); arg3 = ...

Invoking methods with Out and Ref !!!

Straight to code..... int SomeMethod(string arg1, string arg2, ref DayOfWeek arg3) { // Wildest implementation! } The above method had to be executed on its dispatcher thread. So let unravel a bit of the wildest implementation above. int SomeMethod(string arg1, string arg2, ref DayOfWeek arg3) { if (Disptacher.CheckAccess()) { var funcDelegate = (Func<string, string, DayOfWeek, int>)SomeMthod; return Dispatcher.Invoke(funcDelegate, arg1, arg2, ref arg3); } // Wilder implementation!! } Before you say anything, yes, the compiler spat the following errors:- Error 1 No overload for 'SomeMethod' matches delegate 'System.Func<string,string,DayOfWeek,int> Error 2 The best overloaded method match for 'System.Windows.Threading.Dispatcher.Invoke(System.Delegate, params object[])' has some invalid arguments Error 3 Argument '4': cannot convert from 'ref System....

Thinking Currying !!!

Currying is a mathematical concept based on lambda calculus. It is a technique of operating on a function (taking multiple arguments) by splitting and capable of chaining into a series of single argument functions. It is very similar to what a human would attempt to do on paper. For example, if you have to add numbers 1 through 10, what would you do? Class II mathematics....zero in hand, one in the mind, add 0 and 1, so 1 in the mind, then 2 in the hand, ...up to 10. So we compute the addition with one argument at a time. In the programming world, it is realized by transforming a n-arguments function into a (n-1) arguments function, which takes the remaining one argument. This transformation when applied recursively on each of the single argument functions is the chaining of single argument functions that I discussed earlier. Needless to say, currying is a gift of the functional programming world. In simple words, functional programming is about building functions from other functio...

Quiz - (Journey through templates, SFINAE and specialization) !!!

template<typename A, typename B> class TClass { public: TClass() { } // Overload #1 public: std::string SomeMethod(A a, B b) { std::ostringstream ostr; ostr << a << "-" << b; return ostr.str(); } // Overload #2 public: std::string SomeMethod(B b, A a) { std::ostringstream ostr; ostr << b << "-" << a; return ostr.str(); } }; So that is a template class with SomeMethod overloads. Why would somebody write such a class? Imagine it is an adder class, and the method overloads could used to add with parameters specified in either order. Following is the way one could use the above (based on the adder example):- int i = 45; double d = 12.3f; TClass<int, float> t1; const std::string idText = t1.SomeMethod(i, d); // This calls Overload #1 const std::string diText = t2.SomeMethod(d, i); // T...

Missing MI !!!

We all know C# does not offer multiple inheritance but offers arguments that programmers can live without it. It is true in almost all cases, especially all cat and animal or employee and manager projects. I have seen a few cases where if C# offered multiple inheritance, the solution would have been natural, elegant and succinct. Imagine that I have a component (UI, non-UI, doesn't matter). You can make calls into the component, which does some interesting work for you. Imagine that the component takes an interface IComponentCallback to notify its parent. So I would do is have my parent class derive from IComponentCallback interface and pass this to the component. The code would look something like this:- interface IComponentCallback { void Callback1(); bool Callback2(); void Callback3(int old, int new); } class SomeComponent { // The parent on whom callbacks are made private IComponentCallback _parent = null; public SomeCompoent(IComponentCallback cmpCal...

sizeof vs Marshal.SizeOf !!!

There are two facilities in C# to determine the size of a type - sizeof operator and Marshal.SizeOf method. Let me discuss what they offer and how they differ. Pardon me if I happen to ramble a bit. Before we settle the difference between sizeof and Marshal.SizeOf , let us discuss why would we want to compute the size of a variable or type. Other than academic, one typical reason to know the size of a type (in a production code) would be allocate memory for an array of items; typically done while using malloc . Unlike in C++ (or unmanaged world), computing the size of a type definitely has no such use in C# (managed world). Within the managed application, size does not matter; since there are types provided by the CLR for creating\managing fixed size and variable size (typed) arrays. And as per MSDN, the size cannot be computed accurately. Does that mean we don't need to compute the size of a type at all when working in the CLR world? Obviously no, else I would ...

Curious Case Of Anonymous Delegates !!!

Senthil has left us thrilled in his new post , and also inspired me to write about the topic . Although, anonymous delegates have become a mundane stuff amongst programmers, there is still these subtle stuff left unexplored. Alright, let us try to answer Senthil's question before he unravels the mystery in his next post. A delegate is identified by its target. The target is the method to be executed on a delegate invocation and its associated instance or type. If the target is an instance method, the delegate preserves the target method pointer and the object instance. If the target is a static method, the delegate preserves the target method pointer and the type to which it belongs. So when a code like the one below to register a method to an event (or multicast delegate) is executed, a delegate object (EventHandler here) with the target information embedded is created and added to the invocation list of the event (or multicast delegate, KeyPressed here). class SomeForm { pr...

finally and Return Values !!!

Let us read some code:- int SomeMethod() { int num = 1; try { num = 5; return num; } finally { num += 5; } } What is the return value of SomeMethod? Some anonymous guy asked that question in the code project forum, and it has been answered. I am writing about it here because it is interesting and subtle. One should not be surprised when people misinterpret finally. So let us take a guess, 10 (i = 5, then incremented by 5 in the finally block). It is not the right answer; rather SomeMethod returns 5. Agreed that finally is called in all cases of returning from SomeMethod but the return value is calculated when it is time to return from SomeMethod, normally or abnormally. The subtlety lies not in the way finally is executed but in the return value is calculated. So the return value (5) is decided when a return is encountered in the try block. The finally is just called for cleanup; and the num modified there is local to SomeMetho...

Type Safe Logger

Sanjeev and I have published an article - Type Safe Logger For C++ - at CodeProject. Every bit of work is tiresome or little ugly in C++. So is logging - writing application diagnostics to console, file etc. The printf style of outputting diagnostics is primitive and not type safe. The std::cout is type safe but does not have a format specification. Besides that, printf and std::cout know to write only to the console. So we need a logging mechanism that provides a format specification, is type safe and log destination transparent. So we came up with this new Logger to make C++ programmers happy. Following is a short introduction excerpt of the article:- Every application logs a whole bunch of diagnostic messages, primarily for (production) debugging, to the console or the standard error device or to files. There are so many other destinations where the logs can be written to. Irrespective of the destination that each application must be able to configure, the diagnostic log message a...

Simple Array Class For C++

This is a simple array like class for C++, which can be used as a safe wrapper for accessing a block of memory pointed by a bare pointer. #pragma once template<typename T> class Array { private: T* _tPtr; private: size_t _length; private: bool _isOwner; public: Array(size_t length, bool isOwner = true) : _isOwner(isOwner) { _length = length; _tPtr = new T[length]; } public: Array(T* tPtr, size_t numItems, bool isOwner = true) : _isOwner(isOwner) { if (NULL == tPtr) { throw std::exception("Specified T* pointer is NULL."); } this->_length = numItems; this->_tPtr = tPtr; } public: template<typename TSTLContainerType> Array(const TSTLContainerType& stlContainer, bool isOwner) : _isOwner(isOwner) { _length = stlContainer.size(); _tPtr = new T[_length]; int ind...

Passing CComPtr By Value !!!

This is about a killer bug identified by our chief software engineer in our software. What was devised for ease of use and write smart code ended up in this killer defect due to improper perception. Ok, let us go! CComPtr is a template class in ATL designed to wrap the discrete functionality of COM object management - AddRef and Release. Technically it is a smart pointer for a COM object. void SomeMethod() { CComPtr siPtr; HRESULT hr = siPtr.CoCreateInstance(CLSID_SomeComponent); siPtr->MethodOne(20, L"Hello"); } Without CComPtr, the code wouldn't be as elegant as above. The code would be spilled with AddRef and Release. Besides, writing code to Release after use under any circumstance is either hard or ugly. CComPtr automatically takes care of releasing in its destructor just like std::auto_ptr . As a C++ programmer, we must be able to appreciate the inevitability of the destructor and its immense use in writing smart code. However there is a difference...

OrderedThreadPool - Task Execution In Queued Order !!!

I would not want to write chunks of code to spawns threads and perform many of my background tasks such as firing events, UI update etc. Instead I would use the System.Threading.ThreadPool class which serves this purpose. And a programmer who knows to use this class for such cases would also be aware that the tasks queued to the thread pool are NOT dispatched in the order they are queued. They get dispatched for execution in a haphazard fashion. In some situations, it is required that the tasks queued to the thread pool are dispatched (and executed) in the order they were queued. For instance, in my (and most?) applications, a series of events are fired to notify the clients with what is happening inside the (server) application. Although the events may be fired from any thread (asynchronous), I would want them or rather the client would be expecting that the events are received in a certain order, which aligns with the sequence of steps carried out inside the server application for th...

Settling Casting Restrictions !!!

Remember the Casting Restrictions we discussed a while back, let us settle that now. So we have some code like this: int i = 100; object obj = i; long l = (long)obj; And an invalid cast exception while casting 'obj' to long. It is obvious that we are not changing the value held by obj, but just reading it. Then why restrict such casting. Let us disassemble and see what we got. .locals init ( [0] int32 i, [1] object obj, [2] int64 l) L_0000: nop L_0001: ldc.i4.s 100 L_0003: stloc.0 L_0004: ldloc.0 L_0005: box int32 L_000a: stloc.1 L_000b: ldloc.1 L_000c: unbox.any int64 L_0011: stloc.2 L_0012: ret Oh, there we see something interesting - unbox. So the C# compiler uses the unbox instruction to retrieve the value from obj while casting; it does not use Convert . ToInt64 or similar mechanism. That is why the exception was thrown. From MSDN: Unboxing is an explicit conversion from the type object to a value type o...