>>Single Point of Failure >>

Calendar

May 2013
M T W T F S S
« Mar    
 12345
6789101112
13141516171819
20212223242526
2728293031  


Popular Tags

Blog Blogging Book Books C++ C/C++ Cartoon Complaints Daughter Definition Design Development Event Experiment Family Favorites Firefox Focus Fun Google Humor Introspection Life Linux Movie Movies Music Nature Organization Photo Photography Programming Python Reading Series Software Tips Tools Travel TV Ubuntu Vacations Video White Work

Recent Entries



Categories


Archives


Snippets…

Ξ February 3rd, 2013 | → 0 Comments |
Programming |, , , , |


Ever had a programming argument at the water cooler, one that couldn’t be solved without some coding to check what’s what? Or did you ever reached some dark corner of your favorite language that needed to be quickly enlightened by a few lines of code?

Most of the times, solving those technical difficulties would require an “environment” with an editor, with the right compiler and a sandbox for my experiments.

That is no longer the case since I discovered the help I could get from the several available online compilers. My favorite is the one provided by Live Work Space, that provides support for C, C++, Python, Ruby, D, Go, Fortran, and more… with several compilers for most of the supported languages.

There are others that also provide interesting features, such as Ideone. And if you need a more elaborate setup, Compilr provides the full development environment.

 


How to check for endianess?

Ξ March 11th, 2012 | → 0 Comments |
Programming |, |


bool platform_is_big_endian()
{
   long one = 1;
   return !(*((char *)(&one)));
}

So, what’s going on?

A long takes more that 1 byte (usually 4 bytes).
In big-endian 1 is represented by {0×00, 0×00, 0×00, 0×01}, which is reversed for little-endian {0×01, 0×00, 0×00, 0×00}. The code above takes the address of the most significant byte of the long, and depending on the value of that byte returns true if big-endian, false if little endian.

 


Map

Ξ January 28th, 2012 | → 0 Comments |
Programming |, , |


 


Going Concurrent

Ξ December 23rd, 2011 | → 0 Comments |
Programming |, , , , |


I had to implement a progress bar for a GUI application, and in order to keep the application “live” my focus during last couple of weeks shifted to multi-threaded concurrent programming. The solution was simple and it basically implied implementing a background thread to update the progress bar while filling a data structure by reading a file. It was simple enough to be implemented in a couple of days, but it became clear that some of the topics related to concurrent programing just weren’t as consolidated I would like.

Since the I’ve been skimming over some interesting articles on the subject. Also began to read “Concurrent Programming in Java, 2nd Edition” by Doug Lea and “The Art of Concurrency” by Clay Breshears .

The following is my attempt to solve the brain-number problem (addressed initially by Ari Sundaram).

#include <cmath>
#include <iostream>
#include <limits>
#include <cassert>

#include "omp.h"

/* ***
 * Count the digits in the number 
 * ***/
int count_digits(int number)
{
	return log10(static_cast<double>(number)) + 1;
}

/* ***
 * Calculate the brain-value of the number
 * 
 * The brain-value is the sum of each digit in number to the power of the
 * number of digits.
 * BV(d1d2d3...dn) = d1^n + d2^n + d2^n + ...  + dn^n,
 *                                              where dn is the nth digit
 * ***/
int
brain_value(int number)
{
	int sum = 0;
	int digits = count_digits(number);
	
	while(number > 0)
	{
		sum += ::pow(number % 10, digits);
		number = number / 10;
	}

	return sum;
}

/* ***
 * Checks if number is a brain-number
 * 
 * A number is a brain-number when it's brain-value equals the number itself
 * ***/
bool
is_brain_number(int number)
{
	return brain_value(number) == number;
}

/* ***
 * Prints the brain-numbers in the lower/upper range
 *                                 (Serial Version)
 * ***/
void
print_brain_numbers_in_range(int lower, int upper)
{
	assert(lower >= 0);
	assert(lower <= upper);
	
	for(int i = lower; i <=upper; i++)
		if(is_brain_number(i))
			std::cout << i << std::endl;
}

/* ***
 * Prints the brain-numbers in the lower/upper range
 *                                 (Parallel Version, using OpenMP)
 * ***/
void
print_brain_numbers_in_range_parallel(int lower, int upper)
{
	assert(lower >= 0);
	assert(lower <= upper);

	#pragma omp parallel
	{
		#pragma omp for
		for(int i = lower; i <=upper; i++)
			if(is_brain_number(i))
				#pragma omp critical
				{
					// Critical section ensures correct output
					std::cout << i << std::endl;
				}
	}
}

/* ***
 * Helper function to test the 
 * ***/
template<typename Printer>
void execute_print_brain_numbers(Printer& printer, int lower, int upper) {
	
	std::cout << "The brain numbers between "
	          << lower << " and " << upper << " are:" << std::endl;
	double start = omp_get_wtime();
	printer(lower, upper);
	double end = omp_get_wtime();
	std::cout << "Listed in " << (end - start) << " seconds" << std::endl;
}

int main(void)
{
	execute_print_brain_numbers(
		print_brain_numbers_in_range,
			0,
			std::numeric_limits<int>::max() / 100);

	execute_print_brain_numbers(
		print_brain_numbers_in_range_parallel,
			0,
			std::numeric_limits<int>::max() / 100);

	return 0;
}

 


Just had a nice time with volatile!

Ξ December 17th, 2011 | → 0 Comments |
Programming |, , , |


I’ve never had the chance (or in fact the need) to investigate the use of the volatile keyword in C/C++. Today I found some very interesting articles about the subject.

 - Andrei Alexandrescu’s article “volatile: The Multithreaded Programmer’s Best Friend” at Dr. Doobs’s.
Explains that using volatile prevents compiler optimizations that might render code incorrect in the presence of certain asynchronous events. And presents a technical discussion on how to use the volatile qualifier to create critical sections and avoid race conditions.

 - Arch Robison’s “Volatile: Almost Useless for Multi-Threaded Programming” at Intel Software Blogs.
Provides an example where volatile does not work, and defends that volatile does not provide a sound base to create correct multi-threaded programs. The discussion that follows is very interesting, spawning comments for several years, and including several very interesting references to how the C++ communities discussed/evolved volatile understanding.

 - Nigel Jones’ “Introduction to the Volatile Keyword” (here) and San Saks’ “Use voatile Judiciosly” (here).
Show interesting examples of what is and how to use the
volatile qualifier, providing examples of use in the scope of embedded systems development.

         


        Once virtual, always virtual…

        Ξ October 23rd, 2011 | → 0 Comments |
        Programming |, , , |


        What will be the output of the code below?

        #include <iostream>
        #include <memory>
        
        using namespace std;
        
        namespace abyss {
        
        class A {
        public:
          virtual ~A() {}
          virtual void f() { cout << "A::f" << endl; } // base is virtual
        };
        
        class B: public A {
        public:
          virtual ~B() {}
          void f() { cout << "B::f" << endl; } // this is also virtual
        };
        
        class C: public B {
        public:
          virtual ~C() {}
          void f() { cout << "C::f" << endl; } // continues to be virtual
        };
        
        }
        
        int main() {
          auto_ptr<abyss::A> base(new abyss::C);
          base->f();
           // method called using pointer to base gets dispatched to C::F
        
          return 0;
        }
        

        Take notice of the “once virtual always virtual” rule that states that once a method is qualified as virtual there is no way to turn off the dispatching mechanism provided by the language for virtual functions. Unlike Java, C++ does not have the notion of final (which interrupts the dispatching). This means that, even though neither B or C classes qualify f() as virtual, the call to base->f() shall be dispatched as if it was.

        I like to follow the convention to place an explicit virtual qualifier to make clear the expected behaviour. It would be nice to have some kind of warning from the compiler, but no issue is raised (at least when using g++ 4.5.1).

         


        abyss::round

        Ξ October 9th, 2011 | → 0 Comments |
        Programming |, , |


        From time-to-time the question re-emerges “How to round floating values?”. (I know its stupid, but after this post, I’m sure the mental note will stick!)

        Yes, there is a round function in C and C++ standards.
        It was introduced in the C99 standard, and it is also available in the C++98 standard. The round function is defined amongst others mathematical related function in math.h (cmath for C++ purposes).

        But, for purposes not worth mentioning, I was using a pre-round compiler and had to roll my own function. The standard defines that the round function shall return the nearest integer value in floating point format, rounding halfway cases away from zero. This means that negative values rounds up in absolute value (i.e. -1.7 rounds to -2.0, while -1.2 rounds to 1.0). Here is the result of my experiments (abyss is the namespace that stores my experiments, as in It is by going down into the abyss that we recover the treasures of life.).

        #include <cassert>
        #include <iostream>
        #include <cmath>
        
        typedef double(*round_function_t)(double);
        
        namespace abyss {
        double round(double x) {
          return (x > 0.0) ? std::floor(x + 0.5) : std::ceil(x - 0.5);
        }
        }
        
        void testRoundedValue(double value, double expected,
                              round_function_t round_function) {
        
          double rounded = round_function(value);
        
          std::cout << value << " rounds to " << rounded
                    << " obtains " << expected << std::endl;
          assert( rounded == expected );
        }
        
        int main(void) {
          round_function_t round_func = abyss::round;
                                        // use std::round for standard round
        
          testRoundedValue(-1.70, -2.0, round_func);
          testRoundedValue(-1.51, -2.0, round_func);
          testRoundedValue(-1.50, -2.0, round_func);
          testRoundedValue(-1.49, -1.0, round_func);
          testRoundedValue(-1.20, -1.0, round_func);
        
          testRoundedValue(-0.50, -1.0, round_func);
          testRoundedValue(-0.49, -0.0, round_func);
          testRoundedValue( 0.00,  0.0, round_func);
          testRoundedValue( 0.49,  0.0, round_func);
          testRoundedValue( 0.50,  1.0, round_func);
        
          testRoundedValue( 1.20,  1.0, round_func);
          testRoundedValue( 1.49,  1.0, round_func);
          testRoundedValue( 1.50,  2.0, round_func);
          testRoundedValue( 1.51,  2.0, round_func);
          testRoundedValue( 1.70,  2.0, round_func);
        
          return 0;
        }
        

         


        Curiouser and curiouser!

        Ξ October 2nd, 2011 | → 0 Comments |
        Languages, Programming |, , , , |


        … or, a “mental” note on how to do C++ Mixins using the Curiously Recurring Template Pattern [1].
        A way to separate the dumb domain object (containing essentially data) from functionality needed for a specific use case purpose – based on DCI concepts presented in Lean Architecture [2] .

        #include <iostream>
        
        template <typename Derived>
        class Mixin {
        public:
          virtual ~Mixin() {};
        
          void functionA() {
            dynamic_cast<Derived*>(this)->functionX();
            std::cout << "do something specific!" << std::endl;
          }
        
          virtual void functionX() = 0;
        };
        
        class DumbObject : public Mixin<DumbObject> {
        public:
          void functionX() {
            std::cout << "access dumb data!" << std::endl;
          }
        };
        
        int main(void) {
          DumbObject dumb;
          dumb.functionA();
        
          return 0;
        }
        

        References:
        [1] Coplien, James O. “Curiously Recurring Template Patterns”. C++ Report: 24–27. 1995, February
        [2] James O. Coplien, Gertrud Bjørnvig. “Lean Architecture: for Agile Software Development”. Wiley. August 17, 2010

         


        Best Reading

        Ξ April 8th, 2011 | → 0 Comments |
        Programming |, , , , |


        Today I finished one of the best C++ books that I’ve ever read. “Modern C++ Design” by Andrei Alexandrescu is amazing. The techniques presented are ground breaking, and I must admit the joy of learning about the described techniques was immense. This is certainly a must-read book for all C++ afficionados, like myself.

        Reading this book made me believe (I was sure of it from the start, even before starting) that there’s still much to learn about C++. This book is certainly not for the faint of heart. In order to keep up with the huge amount of new concepts, techniques and approach, I had to “build” a mind-map. Check it out to have just a glimpse of the books contents, as “seen” by me. 

         


        A Puzzle…

        Ξ November 6th, 2010 | → 0 Comments |
        Programming |, , , |


        The Exceptional C++ book series by Herb Sutter are amazing. The three books* provide (sometimes not so easy but) very interesting puzzles related to the possible uses of modern C++ programming. Its perfect to the passionate programmer, and you can be sure to learn and enjoy the time spent reading these books.
        Here is an excerpt from Item 4 of More Exceptional C++, which intends to find a mechanism to check, at compile time, that a given class D is derived from a base class B.

        template<typename D, typename B>
        class IsDerivedFrom
        {
          class No { };
          class Yes { No no[2]; };

          static Yes Test( B* ); // declared, but not defined
          static No Test( … ); // declared, but not defined

        public:
          enum{ Is = sizeof(Test(static_cast(0))) == sizeof(Yes) };
        };

        I have to admit that it took me a while to understand what the hell was going on in this piece of code. Can you see how this solved the issue? Very clever, right!?

         


        * Exceptional C++, More Exceptional C++ and Exceptional C++ Style

         


        On the nightstand...



        Random snapshots...

        DSC_0062.JPG DSC_0077.JPG DSC_0177.JPG DSC_0228.JPG DSC_0908.JPG DSC_0128.JPG DSC_0050.JPG DSC_0744.JPG DSC_0273.JPG DSC_0186.JPG


        Entries | Comments
        «« Previous Entries