syntax highlight

Tuesday 20 December 2011

Anonymous objects in C++

There are not many cases in which you can have an anonymous *anything* in your code, yet there's an idiom in C++ which lets you use an object with an anonymous type. Like this:

void foo()
{
   struct {
      int x;
   };
}

Why would this be useful, you may ask. That's a valid question. This idiom can be very useful to write callbacks, like this:

struct Interface {
   void callback() = 0;
};

void bar(Interface &c);

void foo()
{
   struct : public Interface {
      /* ... */
   } x;

   bar(x);
}

I am not aware of many other uses for an anonymous type. Even more considering this idiom can now be replaced with a much cleaner lambda. But hey, it looks cool!

Tuesday 13 December 2011

Fixing end of line styles between Linux and Windows with SVN

Quite a mouthful for such an easy thing. Don't you just hate when half the people in a project use CR/LF and the other half just LF?

Luckly this is easy to fix, assuming you are using svn. You can use something called auto-props to setup the eol style for different file types.

Set it once for the project, never worry again. Anyone knows its git counterpart?

Thursday 8 December 2011

C++: Checking if a method exists in a parent class

I like Google test and Google mock (C++ only) a lot. These are really great tools to ensure the quality of your code. They do have one problem however, especially when working with a legacy codebase: many times you need to change a signature for a function and your tests begin to fail. Those tests shouldn't really fail, they shouldn't compile at all because you're now trying to mock a function which doesn't exists anymore.

I worked on a patch to check if a class and its parent share the same methods, but I hit some major roadblocks which I believe cannot be saved:

  • You have no way of detecting if the parent's method is actually virtual. It may have the same signature, yet if it isn't virtual the mock serves no purpose
  • You have no (easy) way of detecting if the method is defined in your parent's parent

Even though this code will never be useful, I thought I might as well post this here, just in case anyone comes up with a solution for those problems.

// :!g++ foo.cpp -lgtest_main -lgmock && ./a.out
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace testing;

/**
 * "Real" application
 */
class Foo {
	public:
	virtual int bar(int) { return 1; }
	//virtual int bar(void) { return 1; }
};

class Do {
	public:
	int something(Foo &foo){ return foo.bar(1); }
};

/**
 * Class used to compare method ptrs. We need to inherit from class C
 * to forward the calls to the derived methods.
 */
template <class C, class D>
class Mocks_Must_Exist_In : public C {
	public:
	// We don't know in the derived class the typeof the parent class
	// so we define a common name using some template magic
	typedef C ParentClass;
	// Actually we don't know our own class either
	typedef D Self;

	// Function ptr definitions are ugly so we might as well use
	// a template to hide it under the rug
	template <class F, class G>
	void mock_created_for_unexisting_method(F f, G g){ f = g; }
};

#define METHOD_EXISTS(Method) 
	void defined_##Method() { 
		mock_created_for_unexisting_method(&Self::Method, &ParentClass::Method); 
	} 

/**
 * Checked mock, shouldn't compile if Foo's interface changes
 */
class FooMock : public Mocks_Must_Exist_In< Foo, FooMock > {
	public:
	MOCK_METHOD1(bar, int(int));
	METHOD_EXISTS(bar);
};

/**
 * Unchecked mock, should compile if Foo's interface changes
 */
class FooMock2 {
	public:
	MOCK_METHOD0(bar, int());
};

TEST(FooTest, ThisShouldCompile) {
	FooMock foo;
	EXPECT_CALL(foo, bar(_)).WillOnce(Return(42));
	EXPECT_EQ(42, Do().something(foo));
}

Thursday 24 November 2011

svn tip: branch stable version, then use externals

Even though the title says svn, this tip is applicable probably for any version control system. Imagine the following scenario: You have project BestAppEver. BestAppEver depends on BestLibEver. Both are using svn. How do you handle this on your version control system?

One way, the wrong way, that I have seen lots of times is to just include a copy of BestLibEver inside BestAppEver, like this:

This is horrible, whenever BestLibEver is updated you need to manually update BestAppEver. Thus, we come to the second (but not quite the best) solution: svn externals. They work like this:

Again, although I said svn externals, most version control systems have their own externals version. For a detailed explanation on how externals work you should read the link above, for the moment let's just say this is enough to setup the external:

$ svn pe svn:externals .
# This will open your default editor. Now write this:
LibName           LibURL

Now every time you run an svn update, it will fetch the latest version of BestLibEver. We have a problem though: BestLibEver may be a project with a lot of commits, and the head revision may be very unstable. Not only it may crash (being a development version, it wouldn't be a strange thing) but also its interfaces may be constantly changing. And we certainly don't want to spend all day just changing our wrappers to make the project compile again.

There is a solution for this, and we don't have to go back to the first method of just copying the trunk to our repository: we can ask the maintainer of BestLibEver to just create a branch (or a tag, for this case it's pretty much the same) for a stable version and then use an external to that branch. Like this:

Now the team developing BestLibEver can work without complaints from their users and BestAppEver can have a stable svn, with controlled lib upgrades whenever they want.

Tuesday 22 November 2011

Fixing some annoying GTK Warnings

So, new Buguntu upgrade, new problems. The usual deal. I don't like Unity so I installed the usual gnome desktop. Now when I start gVim I get a bunch of errors like this:

(gvim:7189): Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap"

OK, not errors, just warnings. I don't like them anyway, so I did this to fix it:

sudo apt-get install gtk2-engines-pixbuf
Now it works. One problem less, NaN to go... time to move back to Debian?

Thursday 17 November 2011

C++ name mangling

There is a topic I have referred to several times on this blog, yet in four years I still haven't explained what it is. I plan to correct this by explaining a little bit about C++ name mangling, and although I won't expect to write anything you couldn't learn by reading Wikipedia, I'll try to have a more practical approach.

Whenever you compile and link something, there is a lot of information the compiler deduces that you don't really care about. Things like calling conventions, overloads or namespaces. Yet this information is crucial for other stages of the compiler (or linker) to work. For this reason, the compiler will create a decorated version of any object's or function's name.

In its most simple case, it would be something like this:

void overloaded_function(int);
void overloaded_function(string);

Which would then be translated to something like:

void fastcall_int_overloaded_function(int);
void fastcall_string_overloaded_function(string);

Of course, for more complex functions (like class methods) the mangling is much more complicated. Also, remember that's just a mangling convention I just invented, and most likely not used by any compiler in existence.

Although for the most part we can just ignore name mangling, this has a couple of consequences of which we should be aware:

Creating a name for anonymous objects/functions

I will not explain much about this, it might be the topic of another post, but there are certain cases in which you can have a struct or a function defined inside another object anonymously. In these cases, the mangler will assign some sort of denomination for this anonymous object.

Linking with C symbols

C has no mangling. It just doesn't need it. This has a very important consequence, whenever you use C code in C++ you need to specify that your doing so, by using an extern "C" declaration.

Debugging

gdb already takes care of this so it may be transparent to you, but if you are using a debugger not aware of how your compiler mangles names, you may end up with a lot of very difficult to understand names.

Bonus: Demangling C++ names

If you find yourself in the last case, for example when running an nm to get the names defined in a (compiled) object, you can use c++ filt. Like this:

nm foo.o | c++filt

Tuesday 1 November 2011

New Buguntu, new GUI, new problems

I updated Ubuntu to 11.10 in one of three computers I regularely use. Lot's of problems and very little improvements. Granted, sound now works by default (finally) but dual screen suport is still less than what I would expect from Windows 98. On top of that, the biggest change is the GUi.

WTF! My computer is not a tablet, give me back my menu. While using my phone it's nice to have only a couple of icons to click. With two big monitors, I miss my launch bar, a propper clock, my custom applets and the applications menu... everything that makes the GUI usable.

Luckly Ubuntu provides a way to revert to the "classic" desktop, you just need to apt-get install gnome-session-fallback (WTF? I need to INSTALL it? If you plan to roll out a new experimental GUI, at least let me opt-out without downloading more stuff). Of course, since now Ubuntu comes with Gnome 3 even more fun ensues.

Did you plan to customize your toolbars? Well, good luck with that. Apparently now the applets that work for the old Gnome won't work for Gnome 3. Yes, they implemented a new cool applet system, whatever, I just want a port of the old ones I had.

Oh, if you plan to move things around you'll have to do some research first. See that hideous clock up there, in the top bar? How would you get it to the lower-right corner? Why, hold alt and then right click to see the move menu. Super intuitive. I wonder if they inspired themselves on ribbon.

I don't understand the tablet-interface-ftw fad, I was happy with my console multiplexer and I want to keep it unobtrusive, as gnome 2 was. Time to switch to XFCE?

Thursday 27 October 2011

Annoying "unable to find a medium containing a live file system" in Ubuntu

Sometimes you may get this message when installing Ubuntu. And it's not very helpful, the install just dies.

Assuming you created the installer appropriately (usb, live cd, whatever), once you reached that message it means that the BIOS already recognized your device as bootable, loaded the bootloader and started executing it. So it's the bootloader that can't find the image, yet that doesn't make sense if you think about it carefully: if the installer was properly created, that shouldn't happen.

Well, after fighting for a while I realized that some DVD drives connected to a high speed SATA port will give this kind of message error. From the message it's not very clear what causes it, so you can try with one of the crazy kernel options like noapic. If that doesn't work, you can try to change the SATA mode in the BIOS. ACHI worked for me.

Tuesday 25 October 2011

Passwordless ssh

This is one of those things that are terribly easy nowadays, but since I only do it every once in a while I never remember how it's done: setting up a passwordless ssh. I won't write any explanation, just the command to set it up so I can keep it as reference for the next time I have to do it:

ssh-keygen -t rsa && ssh-copy-id USR@HOST

You might also want to specify that HOST requires USR, instead of $(whoami), so you won't have to type ssh USR@HOST next time you want a passwordless loggin. This can be done in /etc/ssh/ssh_config, like this:


Host $HOST
	User $USER

Replace as needed.

Thursday 20 October 2011

Dell and Ubuntu CPU Scaling

Hi, my name is Nicolás Brailovsky and you may remember me from movies like fixing keyboard problems in Ubuntu JJ, removing the annoying terminal warning, random complaints about dual screen in Buguntu and Ubuntu: sound still fubard. This time, I would like to add a new Ubuntu problem to the list of things which make me want to jump off a cliff, though I must warn you that this is a very old article that got forgotten on the stack of posts to review, so it might be dated. Being an old post means that this problem may be fixed by now, but since I don't have a Dell laptop anymore I cannot try it. Anyway, I'll post it as a reference to anyone who may experience something similar.

To be completely fair, this is a dual fuckup between Dell and Ubuntu: after an upgrade I started noticing that sometimes the CPU slows to a crawl, for no apparent reason. The only fix for this is a complete shutdown, as not even a reboot would make this problem go away. WTF?

A lot of time after I had given up on trying to solve this problem and decided that submitting to the gods seemingly random will was the best option, a coworker told me what this was about: apparently when you have a 3D GUI (say, a screensaver) and a double monitor the graphics card has to "work too much", drawing too much power. When the power consumption reaches 90 watts, the power supply's limit, the CPU enables something called CPU scaling, bringing the CPU clock speed to about the speed of a wristwatch. (No, really: "Even setting aside the negative performance effect of FSB downshifting in II above, the effective processing power is reduced to 1/8 of 798 Mhz = 100 MHz. This is a reduction to less than 5% of full capacity, from http://www.sigmirror.com/files/44490_iweoz/throttlegate.pdf).

Solution? None, thanks. Just shut it down and reboot.

Tuesday 18 October 2011

Cool C++0X features XV: Initializer lists for custom (non-std) objects

Last time we saw how you can use C style array-initialization for C++ objects, like this:

	std::vector<int> v = {1,2,3,4};

We also saw this works for may types of objects, like maps and pairs. How about custom developed objects? Yes, that's right, you can have initilizer lists for your own objects too, and it's quite easy. C++0x offers initializer_lists which you can use on your constructors (or any other methods, for that mater) to have C-style initialization. Let's see an example. We already know how to sum a list of numbers using template lists and variadic templates, so let's try adding an initializer consisting of numbers:

Let's start by creating a class which can accept an initializer list:

#include <initializer_list>
using namespace std;

struct Add_List {
	Add_List(initializer_list<int> lst) {
	}
};

int main() {
	Add_List x = {1, 2, 3};
	return 0;
}

That's interesting, as you can see an initializer list is actualy a template class, meaning that nested initializers can easily be defined too. Now, we have the interface, how can we access each element of the list? Let's do the same thing I did when I found out about initilizers, let's search for the header file.

  template<class _E>
    class initializer_list
    {
    public:
      typedef _E 		value_type;
      typedef const _E& 	reference;
      typedef const _E& 	const_reference;
      typedef size_t 		size_type;
      typedef const _E* 	iterator;
      typedef const _E* 	const_iterator;

    private:
      iterator			_M_array;
      size_type			_M_len;

      // The compiler can call a private constructor.
      initializer_list(const_iterator __a, size_type __l)
      : _M_array(__a), _M_len(__l) { }

    public:
      initializer_list() : _M_array(NULL), _M_len(0) { }

      // Number of elements.
      size_type
      size() const { return _M_len; }

      // First element.
      const_iterator
      begin() const { return _M_array; }

      // One past the last element.
      const_iterator
      end() const { return begin() + size(); }
  };

Looks surprisingly easy (note that this is for G++ 4.something only). And it is, most of the magic happens in the compiler, so the userland code is quite straight forward. According to that header file, we could build something like this:

#include <iostream>
#include <initializer_list>
using namespace std;

struct Add_List {
	Add_List(initializer_list<int> lst) {
		int sum = 0;
		for (auto i = lst.begin(); i != lst.end(); ++i)
			sum += *i;

		cout << sum << "n";
	}
};

int main() {
	Add_List x = {1, 2, 3};
	return 0;
}

As you can see, the initializer lists can be used in any place an iterable container is required, as long as it's const. There's not much more magic to it, but we can use some more C++0x devices to make our list-adding device much more cool, for example to support different actions and not only addition. Next time, though.

PS: An important lesson from this article: don't be afraid to look into the system headers, they won't bite. You should never ever change them, but taking a peek can only improve your C++ knowledge.

Thursday 13 October 2011

Dennis Ritchie > /dev/null

UNIX is very simple, it just needs a genius to understand its simplicity.

-- Dennis Ritchie

Starting Ubuntu in console mode

Like it or not, Ubuntu is so easy to install that even for servers is very comfortable to just mount the iso and create as many virtual machines as you may need. Sometimes you already have an iso for Ubuntu, but are too lazy to download the server version. For those occasions you can either decide to waste precious RAM running a GUI for a server that will never need it, or you can remove all traces of the graphical login. Like this:
sudo update-rc.d -f gdm remove

This will remove GDM from the startup scripts, meaning you can still fire up the graphical interface (*) if you want, but it will start Ubuntu without loading any graphics stuff. This is very useful to save on RAM, startup time and processing power, which even if not that useful for a desktop machine is incredible beneficial when you have several virtual machines running in a single physical server.

(*) More precisely, if you have users that need it. Remember though, if it can't be done in console mode, it ain't worth doing.

Tuesday 11 October 2011

Cool C++0X features XIV: Initializer lists

We talked last time about ranged fors and how they can simplify our life in C++0x. Now we are going to take a trip back to old C land. Remember when you could initialize your arrays like this:

int v[] = {1, 2, 3, 4};

C++0X brought a lot of changes to the world, and suddenly instead of int[] you were supposed to use vector, and with it your initializer didn't work anymore. Though luck. Try to compile this:

#include <vector>
int main() {
	std::vector<int> v = {1,2,3,4};
	return 0;
}

If you did compile it with g++, you may have noticed an interesting error message:

error: in C++98 ‘v’ must be initialized by constructor, not by ‘{...}’
warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x

That's interesting. Try to compile it with g++ again, but using C++0x instead of plain C++. Magic, now it works!

Initializers lists bring the best of C to C++ world (?) by letting you use initialize any object with an initializer. And I mean *any* object, not just vectors. For example, say you have a map (a map and a bunch of other stuff):

int main() {
	map<string, vector<int>> v = {
			{ "a", {1,2,3} },
			{ "b", {4,5,6} },
			{ "c", {7,8,9} }
		};

	cout << v["b"][1] << "n";
	return 0;
}

Yes, that works! Maps, vectors, pairs, and even your own custom objects, but we'll see that next time.

Thursday 6 October 2011

Open Office, master documents and headless

I have been writing some documentation lately (crazy, I know) and needed due to some bizarre business requirements all the documentation for the application was supposed to be in a single .doc file. That's write, a single file for user manual, technical manual, administration manual and so on. And I had no LaTeX either (damn those MS Office files, I hate them) so using multiple tex files and including them together wasn't an option.

Choosing the least of all evils, I decided to use Open Office and master documents. With them you can create several different .doc files and then join them together in a single .odm file, which can then be exported to pdf (or .doc, if your boss says so). It's a nice feature, but for such a simple thing as having multiple documents #included in a single one you would expect it to work better. From OO manual:

Yes, master documents do work in OOoWriter. However, their use is full of traps for inexperienced users[...]
Oh, thanks a lot OO.org (?). BTW, exporting an odm to pdf with a headless set == FAIL (i.e. don't even try to use this if you intend to autogenerate some documentation with your makefile).

Tuesday 4 October 2011

Cool C++0X features XII: type inference with auto

In the last four entries we worked on a simple example, like the one I'm pasting below, of type inference with decltype, which led us to learn about delayed type declaration and decltypes with auto. This time I want to focus just on the auto keyword instead.

template <class... Args>
auto wrap(Args... a) -> decltype( do_something(a...) ) {
	std::cout << __PRETTY_FUNCTION__ << "n";
	return do_something(a...);
}

We saw last time how decltype can be used in a contrived way to create a local variable without specifying its type, only how to deduce the type for this variable. Luckily, that verbose method of type declaration can be summed up in the following way:

	int x = 2;
	int y = 3;
	decltype(x*y) z = x*y;
Should be written as:
	int x = 2;
	int y = 3;
	auto z = x*y;

That's right, when you are declaring local variables it's easier and cleaner to just use auto. This feature isn't even "in the wild" yet, so you can't really predict what will people do with it, but it seems to me that limiting its use to local variables with a very short lived scope is the best strategy. We are yet to see what monstrosities the abuse of this feature will produce, and I'm sure there will be many. Regardless of their potential to drive insane any maintainers, its best use probably comes in loops.

In any C++ application, you'll find code like this:

for (FooContainer<Bar>::const_iterator i = foobar.begin(); i != foobar.end(); ++i)

This ugly code can be eliminated with something much more elegant:

for (auto i = foobar.begin(); i != foobar.end(); ++i)

Looks nicer indeed, but we can improve it much further with other tools. We'll see how the next time. For the time being, let's see for what auto is not to be used.

When using auto, keep in mind it was designed to simplify the declaration of a variable with a complex or difficult to reason type, not as a replacement for other language features like templates. This is a common mistake:

Wrong:

void f(auto x) {
	cout << x;
}

Less wrong:

template <T>
void f(T x) {
	cout << x;
}

It makes no sense to use auto in the place of a template, since a template means that the type will be completed later whereas auto means it should be deduced from an initializer.

Thursday 29 September 2011

DIY gnome applets

We all know Gnome, and similar GUIs, are there only as a fancy console multiplexer, but even so it's useful to have widgets in your menus or dockbars to display useful data, like the release date of DNF (*). Gnome has a limited amount of applets from which you can choose, and most of them are crap or limited in their customization. You can always create your own widgets, but that's a pain in the ass for lazy people like me. Fortunately we lazy people can now use something an order of magnitude more useful than widgets in Gnome : we can use console commands!

Using something called Compa you can add a meta-widget, that will display the output of any CLI program. This means, of course, that you have all the power of the console to use in your custom made widgets. Need to check your laptop's battery? No need to search for a widget anymore, just cat /proc/acpi/battery/BAT0/state. Need to check the weather? Just wget your favorite forecast page and parse it with grep, sed an awk. OK, maybe that's a little bit too much.

Once more this proves that anything can be done in console mode - and whatever you can't isn't worth doing anyway.

(*) Wow, this article has been written a LONG time ago!

Tuesday 27 September 2011

Cool C++0X features XI: decltype and disappearing constness

After a long, long hiatus, the C++0x series are back. You may want to check where we left by reading the last posts of this series.

In the last few entries we saw how to use decltype for type inference. Object types is a problem that seems easy but gets complicated very quickly, for example when you start dealing with constness. Constness is difficult in many ways but this time I want to review how constness works with type inference. This topic is not C++0x specific as it's present for template type deduction too, but decltype adds a new level of complexity to it.

Let's start with an example. Would this compile?

struct Foo {
	int bar;
};

void f(const Foo foo)
{
	foo.bar = 42;
}

Clearly not, having a const Foo means you can't touch foo.bar. How about this?

struct Foo {
	int bar;
};

void f(const Foo foo)
{
	int& x = foo.bar;
}

That won't compile either, you can't initialize an int reference from a const int, yet we can do this:

void f(const Foo foo)
{
	const int& x = foo.bar;
}

If we know that works it must mean that s.result's type is const int. Right? Depends.

Just as the name implies decltype yields the declared type of a variable, and what's the declared type for Foo.bar?

struct Foo {
	int bar;
};

void f(const Foo foo)
{
	// This won't compile
	int& x = foo.bar;
	// This will
	decltype(foo.bar) x = 42;
}

That's an interesting difference, but it makes sense once you are used to it. To make things more interesting, what happens if you start adding parenthesis (almost) randomly? Try to deduce the type of x:

void f(const Foo foo)
{
	decltype((foo.bar)) x
}

If decltype(x) is the type of x then decltype((foo.bar)) is the type of (foo.bar). Between foo.bar and (foo.bar) there's a very important difference; the first refers to a variable whilst the last refers to an expression. Even though foo.bar was declared as int, the expression (foo.bar) will yield a const int&, since that's the type (though implicit and not declared, since the expression is not declared).

This is how we would complete the example then:

void f(const Foo foo)
{
	// These two statements are equivalent
	decltype((foo.bar)) x = 42;
	const int& y = 42;
	// It's very easy to confirm that the typeof x is now const int&
	// This won't compile:
	x = 24;
}

As I said, disappearing constness is not a C++0x specific problem as it may occur on template type deduction, but that's besides the point of this post. Next time we'll continue working with type deduction, but with the new auto feature this time.

Thursday 22 September 2011

Running commands on Windows from Linux, through ssh

Running Windows is something I don't usually like (running of Windows is a different story) but having to run something on Windows command line interface is something I wouldn't wish even to my worst enemies. I was stuck in that situation, don't remember why, but I needed to run a command in a Windows machine, automatically, and I only had ssh (is there a better way of automating scripted tasks in Windows, remotely and without a GUI?). Well, this is what I came up with:
ssh host cmd /c dir

Running that in a bash shell will show the directory listing of C: in machine "host". Ugly as hell, but it's a good way of kickstarting a batch script.

Tuesday 20 September 2011

Throwing destructors

We already know what happens when you throw from a constructor. Ending up with a half built object is not good, but suppose we do manage to build one correctly. What happens if we throw in a destructor instead? The results are usually much worse, with a very real possibility of having your program terminated. Read on for a brief explanation on the perils of throwing constructors.

So, according to RAII pattern, resource deallocation should occur during the destructor, yet resource freeing is not exempt of possible errors. How would you notify of an error condition?

  • First error handling choice, you notify /dev/null of the error condition. Best case, you may log the error somewhere, but you can't do anything about it, you end up ignoring it. Not good, usually you'll want to do something about the error condition, even more if it's transient.
  • Second choice, throw. The user (of the class) will know something has gone horribly wrong. This option seems better, yet it has some disadvantages too (just as it happened with throwing destructors; when is an object completely deleted? is it ever deleted if an exception is thrown whilst running?)

Yet the worst part is not resource leaking through half destroyed objects, the worst part is having your program call std::abort.

Think of it this way: when an exception is active, the stack is unwind, i.e. the call stack is traversed backwards until a function which can handle the exception is found. And you just can't unwind the stack while unwinding the stack (you'd need a stack of stacks) so the reasonable thing to do is call std::abort.

So, what can you do about it? Go to your favorite jobs posting site and start searching for a PHP position, you'll sleep better at nights.

Thursday 15 September 2011

Zero padding for Bash scripts

Lately I found myself trying to generate a video from a series of images generated by a program. Doesn't sound difficult, until you start running into a stupid issue: your 1000th frame will come before your 2nd frame!

Luckily there's a very easy fix for this problem, just add zero padding in a bash script. How?

for i in `seq 1 10`; do echo $i; done

That will print all the numbers between 1 and 10. This one will do the same, with zero padding:

for i in `seq 1 10`; do printf "%02dn" $i; done

Wednesday 14 September 2011

200th post!

Yes, this is the post number 200 on this blog. Considering we are a month away of starting the fourth year, I guess that gives me quite a lousy periodicity, but I am still surprised I post somewhat regularly here after such a long time (hey, in programmer years that's like a whole life!).

Since the beginning this blog has mutated from being  my public notepad to being a place where I research new topics, or write about things that are generally interesting to me. I lost many readers for posting crazy metaprogramming stuff and for constantly babbling about Vim and Linux, but hey, I'm proud of if. Let's see what the next 200 posts bring here.

Tuesday 13 September 2011

Automagic document conversion for your makefiles

So, now you have a common makefile, ready to be used for a TDD project and for code coverage report automagic generation. Not only that, but it even speaks to endlessly annoy your team. What else can we add to this makefile? Well, automatic documentation generation, clearly.
You want to batch convert .doc to .pdf using the command line on a server without a GUI? Or you need automated .ppt to .swf conversion through cron, a sysvinit service, or a remote web server? Online conversion services such as Zamzar.com and Media-convert.com not working for you? Whichever formats you need to batch convert, PyODConverter is a simple Python script for just this purpose.
-- http://www.oooninja.com/2008/02/batch-command-line-file-conversion-with.html

Thursday 8 September 2011

Activating tildes and accents for a USA keyboard layout in Ubuntu

Wow. This time the title of the post may actually be longer than its contents. How do you enable accents and tildes in Ubuntu? You need it to type cool characters like á, Ó or ñ (hey, my name has one of these!).

If you are on Windows I think you have to install a new map, and then guess where the key would be. Or use an alt+something magic spell. In Ubuntu, it works by default you just need to add a compose key, Go to System > Preferences > Keyboard > Options > compose key position, select right alt (or whatever you fancy), there you go, now it works. Try it by typing alt + ' + a.

Tuesday 6 September 2011

A talking makefile

So, after learning how to use makefiles, then how to use makefiles for TDD and for code coverage report, now you need to annoy your whole team with a talking makefile. What could be better to notify everyone on your team when a test fails than a synthesized voice commanding you to fix your program?

test: $(TEST_SRCS)
	@for TEST in $(TEST_BINS); do 
		make "$$TEST"; 
		echo "Execute $(TEST)"; 
		if ! ./$$TEST; then 
			echo "Oh noes! I detected a failed test from $$TEST. Go and fix your program!" | festival --tts ; 
	done
Try it. You'll love it.

Bonus chatter: when Valgrind detects over $MUCHOS errors it'll print "Too many errors detected. Go and fix your program", then it won't print so much detail in the next backtraces.

Thursday 1 September 2011

Edit pdf files in Ubuntu

Well, for some reason my LaTeX py-pygments stopped compiling. Thanks for breaking backwards compatibility, you pig-ments.

I had two options, either spend hours trying to fix this by altering the preamble, or just edit the pdf file. Yeah, I know, editing the pdf sounds ugly as hell, but hey at 2 am in the morning I'll take anything. And pdfedit was there to save the day (night). Just apt-get install pdfedit, it's in the repo.

Tuesday 30 August 2011

A Makefile for code coverage report with C++

So far you should know how to use makefiles and you should have a nice testable project. Then you have everything ready to get a coverage report. Yeah, using makefiles, you guessed!

This time we'll depend on two tools, gcov and gtest. These are in Ubuntu's repositories, so you should have no problem getting them. I won't even bother to explain this makefile (not because it's obvious but because I don't really remember how it works. I wrote this over a year ago).

.PHONY: clean coverage_report
coverage_report:
	# Reset code coverage counters and clean up previous reports
	rm -rf coverage_report
	lcov --zerocounters --directory .
	$(MAKE) COMPILE_TYPE=code_coverage &&
	$(MAKE) COMPILE_TYPE=code_coverage test
	lcov --capture --directory $(BIN_DIR)/$(OBJ_DIR)/code_coverage --base-directory . -o salida.out &&
	lcov --remove salida.out "*usr/include*" -o salida.out &&
	genhtml -o coverage_report salida.out
	rm salida.out

Bonus makefile target: make your code pretty:

.PHONY: pretty
pretty:
	find -L|egrep '.(cpp|h|hh)$$'|egrep -v 'svn|_Test.cpp$$' | xargs astyle --options=none

Remember to change your astyle options as needed.

Bonus II: Example project using gcov and gtest: gcov_gtest_sample.tar. The irony? It doesn't use my common makefile, it predates it.

Thursday 25 August 2011

Link: ASCII graphs, 2.0 style

Every once in a while you need to draw a graph to quickly convey some information, and you don't want all the hassle of opening paint, drawing whatever you want, exporting it as png, and all that stuff. Sometimes it's just easier to do it as ASCII art, only you don't want to spend hours carefully aligning pipes and dashes. For these times Asciiflow exists.

Give it a try, it's a great way to quickly generate a diagram. Just remember to use monospace fonts.

Monday 22 August 2011

A Makefile for TDD with C++

So, after reading my post about makefiles you decided that you like them but would like to add some TDD to be buzzword compliant? No problem, that's easy to do.

Assuming you use a naming convention such as this one:

path/to/src/Object.h
path/to/src/Object.cpp
path/to/src/Object_Test.cpp

then it's easy to auto detect which tests should be built:

TEST_SRCS := $(patsubst ./%, %, $(shell find -L|grep -v svn|egrep "_Test.cpp$$" ) )
TEST_BINS := $(addprefix ./$(BIN_DIR)/, $(patsubst %.cpp, %, $(TEST_SRCS)) )

Then we have to define a special rule with pattern matching to compile the tests:

$(BIN_DIR)/%_Test: $(patsubst $(BIN_DIR)/%, %, %_Test.cpp ) %.cpp %.h
	@echo "Making $@"
	@mkdir -p $(shell dirname $@)
	g++ $(CXXFLAGS) -g3 -O0 $< -o $@ -lpthread -lgtest_main -lgmock $(OBJECTS) $(LDFLAGS)

and some magic to auto execute every test when we "make test":

test: $(TEST_SRCS)
	@for TEST in $(TEST_BINS); do 
		make "$$TEST"; 
		echo "Execute $(TEST)"; 
		./$$TEST; 
	done

Everything nice and tidy for a copy & paste session:

TEST_SRCS := $(patsubst ./%, %, $(shell find -L|grep -v svn|egrep "_Test.cpp$$" ) )
TEST_BINS := $(addprefix ./$(BIN_DIR)/, $(patsubst %.cpp, %, $(TEST_SRCS)) )

$(BIN_DIR)/%_Test: $(patsubst $(BIN_DIR)/%, %, %_Test.cpp ) %.cpp %.h
	@echo "Making $@"
	@mkdir -p $(shell dirname $@)
	g++ $(CXXFLAGS) -g3 -O0 $< -o $@ -lpthread -lgtest_main -lgmock $(OBJECTS) $(LDFLAGS)

.PHONY: test
test: $(TEST_SRCS)
	@for TEST in $(TEST_BINS); do 
		make "$$TEST"; 
		echo "Execute $(TEST)"; 
		./$$TEST; 
	done

Now you just need to run make test. Remember to add the proper Vim's mapping.

Thursday 18 August 2011

Makefiles

For open source projects, makefiles are a must. All C++ projects need them, even though cmake is strong nowadays, and even though Java has its own version (actually, several of them, but that's not important now) a makefile could be used.

Even if it is an ubiquitous build system, it is pretty much outdated nowadays, and although using its basic features is easy, mastering it is a complex task. Worst still, mastering makefiles means you'll probably produce write-only-code, and as makefiles are code themselves, and must therefore be maintained, this can be a nuisance to a newcomer to your project.

There's an upside to makefiles being code: they can be reused. Once you find a configuration that suits your development process, you don't need to write it again. I'll post here some of the main targets I ussually include in a common.mk. As I mentioned, it's mostly write-only-code, yet you may find it useful:

# Dependency directoy
df=$(BUILD_DIR)/$(*D)/$(*F)

$(OBJECTS): $(BUILD_DIR)/%.o: %.cpp
	@mkdir -p $(BUILD_DIR)/$(*D)
	$(COMPILE.cpp) -MD -o $@ $<
	@cp $(df).d $(df).P; 
	sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\$$//' 
		-e '/^$$/ d' -e 's/$$/ :/' < $(df).d >> $(df).P; 
	rm -f $(df).d

$(MAIN_OBJ): $(MAIN_SRC)
	$(COMPILE.cpp) -MD -o $@ $< 

# Binary name depends on BIN_DIR/BIN_NAME, so the call to create BIN can
# be forwarded to BIN_DIR/BIN_NAME
$(BINARY): $(BIN_DIR)/$(BINARY)
$(BIN_DIR)/$(BINARY): $(OBJECTS) $(DEPS_OBJECTS) $(MAIN_OBJ)
	@mkdir -p $(BIN_DIR)
	@# Workaround for a linker bug: if the libs are not
	@# at the end it won't link (something to do with how the linker
	@# lists the dependencies... too long for a comment, rtfm
	g++ $(CXXFLAGS) $^ -o $(BIN_DIR)/$@ $(LDFLAGS)
	@#$(LINK.cpp) $^ -o $@

-include $(DEPENDS)

How is this used? Well, don't even try to understand the dependency autogeneration, it'll make your head explode.

$(OBJECTS): $(BUILD_DIR)/%.o: %.cpp

This defines a rule for building .o objects; a variable named OBJECTS should be present when including this file.

$(MAIN_OBJ): $(MAIN_SRC)

A special rule is defined for a main object (actually this is needed to compile the tests, which we'll do next time, since you may have a different main function).

$(BINARY): $(BIN_DIR)/$(BINARY)
$(BIN_DIR)/$(BINARY): $(OBJECTS) $(DEPS_OBJECTS) $(MAIN_OBJ)

And finally, a rule for to create the real binary. Next time I'll add some cool features for TDD to this makefile.

Tuesday 16 August 2011

Living on a null object

Check this out:

struct S {
   int f(){ return 42; }
};

int main() {
   S *x = (S*) NULL;
   return x->f();
}

What does this do? Does it compile? Does it crash? I'll give you a second.

Ready? It does compile, OK
But it doesn't crash.
Why, you may ask
Think about it, you must.

The compiler will mangle S::f and translate this into something like:

struct S {};

int mangled_S_f(struct S *this){
   return 42;
}

int main() {
   S *x = (S*) NULL;
   mangled_S_f(x);
}

Now, in this new "translated" code, what do you think? Will it crash? It won't, since no one is going to dereference "this". Crazy, huh? This crazy idiom also allows even crazier things, like C++ objects committing sepuku

Monday 15 August 2011

Vacations are over

Long time without updates. I guess I needed vacations from the blog. It was not the first time and it probably won't be the last one I take, but I'm back now with another truckload of C++ ramblings and misc stuff. Like this one:

Tuesday 12 July 2011

Funny queries: What Google thinks of me

It's been a long time since I used the metapost category. I've been taking a look at the queries received by Google for which this blogs shows up. Some of them are quite peculiar, some of them may give us an insight of what the search engine things of me. For example:

Query Impressions
grumpy old man 2,000
grumpy 400
grumpy man 400
ugly old man 250
grouchy old man 110
grumpy old 35
old grumpy man 70
grumpy gnome 12

There was a long list of variations to these phrases, but I didn't want such a long post. Anyway, if you thought that grumpy is all Google considers me to be, brace yourself for a surprise:

Query Impressions
trained monkey 90
no life 90
funny troll
monkey using computer
tool monkey
congratulations monkey
monkey using tools

Basically, a computer using trained-troll monkey, with no life. Pretty accurate, some people may say.

Query Impressions
señal de muerte 12

Literally signal of death in Spanish. Tip: Lack of pulse.

Another common search:

hang yourself 200
how to hang yourself 90
rope to hang yourself 12

I guess those searches have a very low returning rate.

This is a query which sincerely surprised me:

Query Impressions
eliphant
eiephant
elehant
elepant
eephant
elephanth

I'll do a public service here: it's written 'elephant', buddy.

Tuesday 5 July 2011

Final classes in C++

Have you ever wondered what's the best way of having a class from which you can't inherit, say, like Java's final? Without any doubt, the best way is having a team capable of not doing things like inheriting from 'class NeverEverEverInheritFromThis'. The second best way involves some magic and lots of beer:

class Final {
    protected:
    Final() {}
};

So, what the hell does that evil device do? Easy, it defines a protected constructor, meaning only derived classes will be able to access it (i.e. no public construction of this object). How does this stop other classes from inheriting? It doesn't, unless we add one more keyword:

class Final {
    protected:
    Final() {}
};

class X : virtual Final {
};
The virtual inheritance is meant to be used to avoid the dreaded diamond in multiple inheritance designs. It does a lot of magic with the constructors and the memory layout of the object; amongst other things, it'll make any class which derives from X have only a single base class for Final and it'll also make this hypothetical class call Final's constructor without going through X first.

A complete explanation of virtual inheritance is beyond the scope of this article, but it's enough for our Final device to know that it forces the virtual base's constructors to be called first, thus now we can write this:

class Final {
    protected:
    Final() {}
};

class X : virtual Final {
};

class Y : public X {
};

int main() {
    X x;
    Y y;
    return 0;
}
Try it and watch it fail!

Update 2011-07-08: Amazing how time flies. This article has been written about a year before its publishing, and, believe it or not, it's already showing its age. What I would update on this article is the first paragraph: the best way of not having a problem with final classes is creating a design which doesn't have artificial restrictions to the growth and extensibility of the system (i.e: don't use final classes, they are usually a bad idea). I like that idea, I may write another article about it.

Tuesday 28 June 2011

LD magic in Linux

The linker is a magical beast which does all sort of crazy stuff with your binaries, without you even knowing it. Every Linux install has a linker living in the shadows, though seeing it in action is a rare supernatural event. There is an ancient tradition to communicate with the spirit of your linker. Not many know about this secret dark path and it's powers to annoy even the most experienced (L)user.

You may begin your journey with the following enchanting:

export LD_DEBUG=help
If everything went fine nothing will seem to happen, yet if the gods of the console have heard you, the next time you try to run any binary at all you'll start to see the real magic. Try it, a simple "ls" will do the trick (don't use commands which are not binaries, like echo or export, these are "hardcoded" in bash, so to speak, and won't work since no runtime linking is necessary: they have already been linked when bash started!).

Read the help you just found. There is a lot of useful information there. Knowing the libs will give you an insight on the dependencies and the loading process of a binary. I have no idea what would be the use of knowing the files for each lib. The symbols and bindings are quite interesting, they remind me of an strace.

"all" is probably the best option to annoy a fellow programmer. Just set the env var and watch him go crazy.

Friday 10 June 2011

Cool C++0X features X: type inference with decltype

After creating a wrapper object on the last entries, we were left with three syntax changes two analyze:

We already saw the first, and we'll be talking about the other two this time. This was the original wrapper function which led us here:

template <class... Args>
auto wrap(Args... a) -> decltype( do_something(a...) ) { 
	std::cout << __PRETTY_FUNCTION__ << "n";
	return do_something(a...);
}

Back on topic: decltype

This operator (yes, decltype is an operator) is a cousin of sizeof which will yield the type of an expression. Why do I say it's a cousin of sizeof? Because it's been in the compilers for a long time, only in disguise. This is because you can't get the size of an expression without knowing it's type, so even though it's implementation has existed for a long time only now it's available to the programmer.

One of it's interesting features is that the expression with which you call decltype won't be evaluated, so you can safely use a function call within a decltype, like this:

auto foo(int x) -> decltype( bar(x) ) { 
	return bar(x);
}

Doing this with, say, a macro, would get bar(x) evaluated twice, yet with decltype it will be evaluated only once. Any valid C++ expression can go within a decltype operator, so for example this is valid too:

template <typename A, typename B>
auto multiply(A x, B y) -> decltype( x*y )
{ 
	return x*y;
}

What's the type of A and B? What's the type of A*B? We don't care, the compiler will take care of that for us. Let's look again at that example, more closely:

-> (delayed declaration) and decltype

Why bother creating a delayed type declaration at all and not just use the decltype in place of the auto? That's because of a scope problem, see this:

// Declare a template function receiving two types as param
template <typename A, typename B>
// If we are declaring a multiplication operation, what's the return type of A*B?
// We can't multiply classes, and we don't know any instances of them
auto multiply(A x, B y)
// Luckily, the method signature now defined both parameters, meaning
// we don't need to expressly know the type of A*B, we just evaluate
// x*y and use whatever type that yields
	-> decltype( x*y )
{ 
	return x*y;
}

decltype

As you see, decltype can be a very powerful tool if the return type of a function is not known for the programmer when writing the code, but you can use it to declare any type, anywhere, if you are too lazy to type. If you, for example, are very bad at math and don't remember that the integers group is closed for multiplication, you could write this:

	int x = 2;
	int y = 3;
	decltype(x*y) z = x*y;

Yes, you can use it as VB's dim! (kidding, just kidding, please don't hit me). Even though this works and it's perfectly legal, auto is a better option for this. We'll see that on the next entry.

Thursday 9 June 2011

sshfs, quick remote mount

When all you have is ssh access to a machine you have enough to mount a remote disk to your work station. How? easy:
sshfs user@host:/path/to/remote/dir /path/to/local/dir

Remember you need permission for both local and remote directories.

Tuesday 7 June 2011

Cool C++0X features IX: delayed type declaration

In the last two entries we worked on a wrapper object which allows us to decorate a method before or after calling (hello aspects!), or at least that's what it should do when g++ fully implements decltypes and variadic templates. Our wrapper function looks something like this (check out the previous entry for the wrapper object):

#include <iostream>

void do_something() { std::cout << __PRETTY_FUNCTION__ << "n"; }
void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "n"; }
int do_something(int) { std::cout << __PRETTY_FUNCTION__ << "n"; return 123; }

template <class... Args>
auto wrap(Args... a) -> decltype( do_something(a...) ) { 
	std::cout << __PRETTY_FUNCTION__ << "n";
	return do_something(a...);
}

int main() {
	wrap();
	wrap("nice");
	int x = wrap(42);
	std::cout << x << "n";
	return 0;
}

After the example, we were left with three new syntax changes to analyze:

  • -> (delayed declaration)
  • decltype
  • auto

Let's study the -> operator this time: -> (delayed declaration)

This is the easiest one. When a method is declared auto (I've left this one for the end because auto is used for other things too) it means its return type will be defined somewhere else. Note that in this regard the final implementation differs from Stroustroup's FAQ.

The -> operator in a method's definition says "Here's the return type". I'll paste the same simple example we had last time, the following two snippets of code are equivalent:

void foo() {}

Is the same as:

auto foo() -> void {}

Thursday 2 June 2011

Vim: Ni! Ni! Ni! Ni!

Even though I have vim a Vim fan for a long time there still is a lot of stuff which amazes me about this little editor, and this thing I last learned about it is in the "ZOMG that's so cool I'm about to pee my pants" category. Unfortunately, if I were to draw a Venn diagram of the people who may find it cool I'd have to intersect the group of people reading my blog (yes, very small) with the group of people who like Vim and Monty Python. So, here's to the null group:

Type :Ni! in Vim and be amazed, it'll reply back: Do you demand a shrubbery?

Just how cool is that?

Tuesday 31 May 2011

Cool C++0X features VIII: Variadic wrapper and type inference with decltype

The wrapper function we built last time looks something like this now:

#include <iostream>

void do_something() { std::cout << __PRETTY_FUNCTION__ << "n"; }
void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "n"; }

template <class... Args>
void wrap(Args... a) {
	std::cout << __PRETTY_FUNCTION__ << "n";
	do_something(a...);
}

int main() {
	wrap();
	wrap("nice");
	return 0;
}

But, as we saw last time, this approach has the problem of requiring the return type of do_something to be known before hand. What can we do to remove this dependency? In C++, not much. You can't really declare a type based on the return type of another function. You do have the option of using lots of metaprogramming wizardy, but this is both error prone and ugly (see Stroustroup's C++0x FAQ).

C++0x lets you do some magic with type inference using decltype; decltype(expr) will yield the type of that expression. It works quite similarly as sizeof does; decltype is resolved at compile time and the expression with which it's being called is not evaluated (more on this later).

How would this work on our example?

#include <iostream>

void do_something() { std::cout << __PRETTY_FUNCTION__ << "n"; }
void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "n"; }
int do_something(int) { std::cout << __PRETTY_FUNCTION__ << "n"; return 123; }

template <class... Args>
auto wrap(Args... a) -> decltype( do_something(a...) ) {
	std::cout << __PRETTY_FUNCTION__ << "n";
	return do_something(a...);
}

int main() {
	wrap();
	wrap("nice");
	int x = wrap(42);
	std::cout << x << "n";
	return 0;
}

Try it (remember to add -std=c++0x) it works great! The syntax is not so terribly difficult to grasp as it was with variadic templates. The auto keywords says "hey, compiler, the return type for this method will be defined later", and then the -> actually declares the return type. This means that the auto-gt idiom isn't part of typedecl but a helper, which in turns means that even if not useful, this is valid C++0x code:

auto wrap() -> void {
}

This means that we have three interesting components to analyze in this scenario:

  • -> (delayed declaration)
  • auto
  • decltype

We'll go over each one the next time.

Closing remark: At first I choose the following example to introduce delayed return types and decltype (warning, untested code ahead):

#include <iostream>

struct Foo {
	void do_something() { std::cout << __PRETTY_FUNCTION__ << "n"; }
	void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "n"; }
	int do_something(int) { std::cout << __PRETTY_FUNCTION__ << "n"; return 123; }
};

// Untested code ahead
// This makes g++ coredump (v 4.4.5)
template <class T>
struct Wrap : public T {
	template <class... Args>
	auto wrap(Args... a) -> decltype( T::do_something(a...) ) {
		std::cout << __PRETTY_FUNCTION__ << "n";
		return T::do_something(a...);
	}
};

int main() {
	Wrap<Foo> w;
	w.wrap();
	w.wrap("nice");
	std::cout << w.wrap(42) << "n";
	return 0;
}

Though this looks MUCH better (and useful), at the time of writing this article mixing variadic templates with decltypes in a template class makes g++ segfault. It should be valid C++, but I can't assure it's correct code since I've never tried it.

Thursday 26 May 2011

Repeat (and fix) last command

How many times have you run a command but forgot to add sudo at the beginning? How many times did you open vim instead of gvim? All that has an easy fix, instead of pressing up-left-left-left-left-left... (almost like a Konami code, isn't it?) just use

!!
.

!!
expands to the previous command, so for example
vim foo
, then
g!!
will execute "gvim foo".

Another common problem, you mistype vim for vmi (hey, it may be a common problem if you're dyslexic). Just type fc, short for fix command, to open the last command in your configured editor. Fix it (lxp, bonus points if anyone understand this :D) then write and save. The fixed command will be executed.

Tuesday 24 May 2011

Cool C++0X features VII: A variadic wrapper solution

Last time we were trying to build a wrapper function, in which we don't control the class being wrapped nor the user of the wrapper (meaning we can't change either of those but they could change without warning).

This was the first approach:

#include <iostream>

void do_something() { std::cout << __PRETTY_FUNCTION__ << "n"; }

void wrap() {
	std::cout << __PRETTY_FUNCTION__ << "n";
	do_something();
}

int main() {
	wrap();
	return 0;
}

Yet, as we saw, it's not scalable, when either part changes the whole things break. We proposed then a variadic template solution, which, if you tried it yourself, should look something like this:

#include <iostream>

void do_something() { std::cout << __PRETTY_FUNCTION__ << "n"; }
void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "n"; }

template <class... Args>
void wrap(Args... a) {
	std::cout << __PRETTY_FUNCTION__ << "n";
	do_something(a...);
}

int main() {
	wrap();
	wrap("nice");
	return 0;
}

That's better. Now we don't care about which parameters do_something should get, nor how many of them are there supposed to be, just how it's called. If you read the previous entries on variadic templates this should be a walk in the park. It still has a flaw though: we need to know the return type of do_something!

Is there a way to write a wrapper without knowing the return type of a function you are wrapping? Yes, in Ruby you can. But now you can do it in C++0x too, and we'll see how to do it next time.

A closing remark: You could do something like this wrapping everything in a class:

#include <iostream>

struct Foo {
	void do_something() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
	void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "\n"; }
};

template 
struct Wrapper : public Base {
	template <class... Args>
	void wrap(Args... a) {
		std::cout << __PRETTY_FUNCTION__ << "n";
		Base::do_something(a...);
	}
};

int main() {
	Wrapper w;
	w.wrap();
	w.wrap("nice");
	return 0;
}

The above works just fine, but due to some limitations in the current (stable) version of gcc we will use the former version (the problem with this form will be clear later, I promise).

Thursday 19 May 2011

Go home

It really bothers me when people type "cd $HOME" or even worse, "cd /home/username". Why? Just type cd alone, it'll go home by itself.

Another useful cd tip, use "cd -" as an alias for "cd $OLDPWD" (oldpwd is the previous directory).

Tuesday 17 May 2011

Cool C++0X features VI: A variadic wrapper

Let's work on the last variadic exercise, a wrapper. Say you have something like this:

#include <iostream>

void do_something() { std::cout << __PRETTY_FUNCTION__ << "n"; }

int main() {
	do_something();
	return 0;
}

And you want to wrap do_something with something else (Remember __PRETTY_FUNCTION__?). This is a solution, the worst one though (or, to be accurate, the most boring one):

#include <iostream>

void do_something() { std::cout << __PRETTY_FUNCTION__ << "n"; }

void wrap() { 
	std::cout << __PRETTY_FUNCTION__ << "n";
	do_something();
}

int main() {
	wrap();
	return 0;
}

Why is it so bad? Let's say you don't control do_something, you just control the wrapper. You may not even control main(), it may be beyond your scope. That means each time do_something changes, or adds an overload, you have to change your code. That's ugly and you should already know how to set up a variadic function to forward the arguments to do_something. Give it a try, next time the solution.

Thursday 12 May 2011

Tuesday 10 May 2011

Cool C++0X features V: Templates and angle brackets, a short interlude

In the heart of C++ template metaprogramming and code obfuscation, lies the (ab)use of angle brackets. This seemingly innocent token can turn the most clean looking code into the mess that template-detractors like so much to complain about.

C++0x doesn't do much to clean up this mess, it's probably impossible, but it does offer a subtle feature to improve the legibility of C++ template code, a nifty little feature we have (inadvertently) used.

Up to C++0x, having two angle brackets together (>>) was parsed as the shift operator (like the one cout uses), meaning that if you had nested templates a lot of compiler errors ensued. C++0x corrects this, meaning that code which in C++ would be like this:

Reduce<Sum, Lst<Num<2>, Lst<Num<4>, Lst<Num<6>, Lst< Num<8> > > > > >

Can now be written like this:

Reduce<Sum, Lst<Num<2>, Lst<Num<4>, Lst<Num<6>, Lst< Num<8>>>>>>

Aaand, back to the normal schedule...

Thursday 5 May 2011

Eclipse watch expresion

So, now that I'm working for the dark side: did you know Eclipse had watch expressions which shows a variable's value on real time? I bet you did, gdb has that too. Did you know a watch expression can evaluate a method call too? Neat, huh? Well, gdb has that too.

Anyway, someone on the team was having weird issues. A switch would jump to unexpected places. The state of an object would change between method calls. WTF?

After some debugging then it downed on me: I once (a long time before this strange behavior) saw this person using watch expressions to evaluate a method's return value. You now have enough information to troubleshoot this problem.

Ready? It's easy. A watch expression of a method call has the ability to alter an object's status. So, if you have something like this:


class Foo {
   int a;
   public:
   Foo() : a(0) {}
   void sumar(){ a++; }
};

int main() {
   Foo bar;
   /* do something */
   return 42;
}

and then add a watch expression over bar.sumar(), then bar.a's value will be undefined for the execution of this program. Nice!

Tuesday 3 May 2011

Cool C++0X features IV: Variadic templates again

Last time we finally solved the varargs problem. Let's review what we learned:

  • Variadic templates let us create something receiving a variable set of arguments
  • We can process the head of that set, then recursively process the tail
  • It adds weird new syntax
    • When declaring typename... T you are saying "here goes a list of types"
    • When declaring T... t you are saying t is a list of objects with different type
    • When you write t..., you are saying "expand the list of arguments"
  • It's type safe
  • It's very neat to confuse your coworkers

So, what can we do with it besides implementing our own version of printf? Let's do something better, let's try adding up a list of numbers to start flexing our variadic templatefooness (?).

What's the usual way of adding a list of numbers? In templates, that is. We need something like this:

sum (H:T) <- H + sum(T)
sum () <- 0

Of course, in C++ templates you don't have values, you just have types. We could implement it like this (if this looks like a new language you may want to check my template metaprogramming series):

#include <iostream>

struct Nil{};
template <typename H, typename T=Nil> struct Lst {
	typedef H Head;
	typedef T Tail;
};

template <
		template<typename A, typename B> class Op,
		typename Head,
		typename Lst>
struct intForeach
{
	typedef typename intForeach
		< Op, typename Lst::Head, typename Lst::Tail >::result Next;
	typedef typename Op< Head, Next >::result result;
};

template <
		template<typename A, typename B> class Op,
		typename Head>
struct intForeach <Op, Head, Nil>
{
	typedef Head result;
};

template <
		typename Lst,
		template<typename A,
		typename B>
		class Op>
struct Reduce
{
	typedef typename intForeach
		< Op, typename Lst::Head, typename Lst::Tail >::result result;
};

template <int N> struct Num {
	const static int value = N;
};

template <typename A, typename B> struct Sum {
	static const int r = A::value + B::value;
	typedef Num<r> result;
};

int main() {
	std::cout << Reduce<
		Lst<Num<2>, Lst<Num<4>, Lst<Num<6>, Lst< Num<8> > > > >,
		Sum >::result::value << "n";
	return 0;
}

Nothing too fancy, plain old recursion with a sum. Yet it's quite verbose, can we make this a little bit more terse and, hopefully, more clear? Yes, we can. Take a look at that Lst, Lst<...> It sucks. And it's the perfect place to use variadic templates, we just need to construct a structure getting a list of ints, like this:

template <
	// The operation we wish to apply
	template<typename A, typename B> class Op,
	// Current element to process
	class H,
	// All the rest
	class... T>
struct Reduce_V
{
	// TODO
}

That one should look familiar from last time article. Now, to implement a reduce operation we need to operate the current element with the result of reducing the tail, so we have to do something like this:

// Remember how T... means to expand T for the next instance
	typedef typename Reduce_V<Op, T...>::result Tail_Result

There's something missing. Can you see what? The ending condition, of course. Let's add it and we'll get something like this:

template <
        // The operation we wish to apply
        template<typename A, typename B> class Op,
        // All the rest
        class... T>
struct Reduce_V
{
};

template <
        // The operation we wish to apply
        template<typename A, typename B> class Op,
        // All the rest
        class H>
struct Reduce_V<Op, H>
{
	typedef H result;
};
 
template <
        // The operation we wish to apply
        template<typename A, typename B> class Op,
        // Current element to process
        class H,
        // All the rest
        class... T>
struct Reduce_V<Op, H, T...>
{
        // Remember how T… means to expand T for the next instance
   typedef typename Reduce_V<Op, T...>::result Tail_Result;
 
   // Reduce current value with the next in line
   typedef typename Op<H, Tail_Result>::result result;
};
And using it is very simple too:
std::cout << Reduce_V< Sum, Num<1>, Num<2>, Num<3>, Num<4>>::result::value << "n";
Next time we'll see another example for variadic templates and a new C++0x feature.

Thursday 28 April 2011

Know your history (at least in bash)

I always wonder why do you see so many people pressing up a bazillion times when trying to bring a command they recently typed. Just use ctrl+r and type part of the previous command, it'll save you many hours of pressing up.

Tuesday 26 April 2011

Cool C++0X features III: Variadic templates, a fix for varargs

Last time we saw why a function with varargs may bring lots of problems. Then we saw how to solve it, but never explained why that last solution doesn't have the problems the varargs solution had, nor how does it work. Let's start by copying the solution here:

// Stop condition
void println() {}

// General case
template <typename H, typename... T>
void println(H p, T... t)
{
   std::cout << p;
   println(t...);
}

int main() {
   println("Hola", " mundo ", 42, 'n';);
   return 0;
}

It certainly looks much better than the varargs function, even though some new strange syntax has been introduced. Keep in mind some template-foo is required, not only because of the syntax but because we'll be talking about functional programming too.

With all that intro (the last 2 articles were just an intro!) now we are in a good shape to ask what a variadic template really is. In its easiest form, it's just a list of template arguments, like this:

template <typename... T> void foo(T... t) {}

That simple template can accept as many parameters as you need, of any type. This is much safer than a vararg because:

  • Doesn't require the user to specify the number of args passed to foo, so it just can't get out of sync
  • It's typesafe; since C++ templates are type-safe, variadic templates are type safe too. You won't be able to request an int where a char is required, you'll just get a compiler error.
  • Compile time check: you get type safety just because this is all compiled code. If it doesn't compile, you get an error (albeit a little cryptic).
  • POD types support
  • Better performance; small gain, but a gain indeed. Since this is all done in compile time there's no need to handle the stack dynamically, nor of having a loop getting the args. It's all known when you compile, thus the compiler can just optimize the hell out of everything

Pretty neat, huh? But how does it work? Variadic templates are actually very similar to how Haskell handles lists, you get all the arguments as a list of types in which you can either get the head or the tail. To do something useful, get the head and continue processing the tail recursively.

template <typename H, typename... T>
void do_something(H h, T... t)
{
	// Do something useful with h
	really_do_something(h);
	// Continue processing the tail
	do_something(t...);
}

Of course, you'll eventually need a condition to stop processing: (we'll explain the new syntax later)

void do_something()
{
	// Do nothing :)
}

When the list is completely processed the empty do_something function will be called. Easy, right? But it does have a lot of weird syntax. Let's see what each of those ellipses mean:

  • When declaring typename... T you are saying "here goes a list of types". That is, when you use ellipses after the typename (or class) declaration but before the name of the type, then you are expecting a list of types there.
  • When declaring T... t you are saying t is a list of objects with different type. That is, you declared T... as a type which holds a list of types, therefore t, of type T, is an instance of a list of objects, each of different type
  • When you write t..., you are saying "expand the list of arguments". You declared t as a list of objects, but you have no way of accessing each of those objects, just to the list as a whole. When you write the name of the object followed by ellipses, you are saying expand these types and their instance for the called function

With all that in mind, let's put together our typesafe printf:

// Condition to stop processing
void println() {}

// Println receives a list of arguments. We don't know it's type nor
// how many there are, so we just get the head and expand the rest
template <typename H, typename... T>
void println(H p, T... t)
{
	// Do something useful with the head
	std::cout << p;
	// Expand the rest (pass it recursively to println)
	println(t...);
}

int main() {
	// See how it works even better than varargs?
   println("Hola", " mundo ", 42, 'n');
   return 0;
}

Next time, we'll see a more complex (and fun) example of variadic templates.

Thursday 21 April 2011

echo "Hola mundo" > /dev/full

I'd write something witty but there's not a lot to talk about /dev/full. Anyway, it is a cool tip, so I'll share it:
Everyone knows /dev/null, and most will know /dev/zero. But /dev/full was unknown to me until some time ago. This device will respond to any write request with ENOSPC, No space left on device. Handy if you want to test if your program catches "disk full" - just let it write there

From Myon's Blog

Tuesday 19 April 2011

Cool C++0X features II, Variadic templates: What's wrong with varargs

Last time we explained what variadic templates are. We'll see what they can do now. We mentioned that solving the problem of having a type-safe varargs is one of the best ways of applying variadic templates, but what's varargs?

Varargs functions (from C world, not even from C++!) are functions which have a variable number of arguments, just like printf. These are usually very dangerous functions, since they are not typesafe. Let's see how they are implemented with an example:

#include <stdarg.h>
#include <iostream>

// My god, it's full of bugs
void va_println(int args_left, ...) {
   va_list arg_lst;
   va_start(arg_lst, args_left);

   while(args_left--) {
      const char *p = va_arg(arg_lst, const char*);
      std::cout << p;
   }

   va_end(arg_lst);
}

int main() {
   va_println(3, "Hola ", "mundo", "n");
   return 0;
}

This implementation of a function with variable arguments is, more or less, the best C can give us, yet it riddled with bugs and hidden problems. Let's go one by one:

  • Arg num will get out of sync: You need to specify the list of args as well as how many you have. That WILL get out of sync. Trust me, it's just a mater of time. And when it does, you'll have a coredump.
  • Type-unsafe: You just tell varargs "Hey, get me an int". And it will give you an int, no warranties included. If it was supposed to be a short instead, though luck, you end up with a coredump.
  • No, really, coredump: Where are so many coredumps coming from, you may ask. Easy, varargs it's just a way of handling the stack. Calling va_arg just moves the stack pointer by the sizeof the datatype you requested. That means no compile-time checks are included.
  • No pod types: Remember POD types? Try running this code:
#include <stdarg.h>

struct X { virtual ~X(){} };

void va_println(int args_left, ...) {
   va_list arg_lst;
   va_start(arg_lst, args_left);

   while(args_left--) {
      X *p = va_arg(arg_lst, X*);
   }

   va_end(arg_lst);
}

int main() {
   X x, y, z;
   va_println(3, x, y, z);
   return 0;
}

And how do we fix it?

The fix is easy. Too easy. You just need C++0X. We will discuss why this is better next time, but just as a sneak peak:

void println() {}
template <typename H, typename... T> void println(H p, T... t) {
   std::cout << p;
   println(t...);
}

int main() {
   println("Hola", " mundo ", 42, 'n');
   return 0;
}

Remember to compile using -std=c++0x in gcc. (Thanks Hugo Arregui for correcting the POD example)

Monday 18 April 2011

Cool C++0X features I: Intro

C++0X brings some very cool changes, and I wanted to start a series of posts regarding some of these changes, with a small explanation of each new feature (that I currently understand, at least), an example of its usage and why I think it's a cool thing. Notice these two may be mutually exclusive, some of these may just be cool but I wouldn't recommend using them on a day to day basis. An example of a very cool feature which I wouldn't normally use in a project is the one I want to write about today: variadic templates.

What's not to love about variadic templates? Its name implies (correctly) that it uses templates, and it also has a "variadic" thingy, which you can use to look smart since no one really knows what it means.

Templates themselves can quickly get complicated if used by unexperienced padawans in the art of martial C++, yet their hypnotic beauty draws every programmer to use them just like flies are drawn to fire. When used correctly they can produce very elegant code; if not for the template programmer, at least for the end user. Yet in all their power, templates in C++ have been lacking a fundamental aspect: a variable number of arguments.

There are ways to work around this limitation, like using a list of types paired with a template-paramlist-object. Sounds familiar? (I know it doesn't, don't worry). You could also generate N constructors, one overload for each parameter count. The drawback, exponential compile time (say, TR1). These are all hacks, which are in place only because there wasn't a safe way of passing a list of types associated with a list of arguments. This is over now with variadic templates in C++0X.

So, what kind of problem would variadic templates solve? Let's name a few:

  • A typesafe varargs function (a function with a variable number of arguments)
  • Easily create a template object which acts as a tuple
  • An easier implementation of a reduce (inject) function

This entry is getting quite long so we'll start seeing these examples on the next post.

Thursday 7 April 2011

Hex dump in C++

If you need to work with low level stuff (say communications protocols, compression algorithms, stuff like that) you'll be needing an hex dump function sooner or later. Alex, from Alex on Linux, has a great hex dump function for Python and C.

I added an =NULL for caption, I don't use it.

void hex_dump(char *data, int size, char *caption=NULL)
{
	int i; // index in data...
	int j; // index in line...
	char temp[8];
	char buffer[128];
	char *ascii;

	memset(buffer, 0, 128);

	printf("---------> %s <--------- (%d bytes from %p)n", caption, size, data);

	// Printing the ruler...
	printf("        +0          +4          +8          +c            0   4   8   c   n");

	// Hex portion of the line is 8 (the padding) + 3 * 16 = 52 chars long
	// We add another four bytes padding and place the ASCII version...
	ascii = buffer + 58;
	memset(buffer, ' ', 58 + 16);
	buffer[58 + 16] = 'n';
	buffer[58 + 17] = '';
	buffer[0] = '+';
	buffer[1] = '0';
	buffer[2] = '0';
	buffer[3] = '0';
	buffer[4] = '0';
	for (i = 0, j = 0; i < size; i++, j++)
	{
		if (j == 16)
		{
			printf("%s", buffer);
			memset(buffer, ' ', 58 + 16);

			sprintf(temp, "+%04x", i);
			memcpy(buffer, temp, 5);

			j = 0;
		}

		sprintf(temp, "%02x", 0xff & data[i]);
		memcpy(buffer + 8 + (j * 3), temp, 2);
		if ((data[i] > 31) && (data[i] < 127))
			ascii[j] = data[i];
		else
			ascii[j] = '.';
	}

	if (j != 0)
		printf("%s", buffer);
}

Monday 4 April 2011

Newsflash: C++ object commits sepuku

Check this out. Is it valid C++?

class X {
  void dispose() {
    delete this;
  }
};

Strange pattern, isn't it?. What happens if you try to dispose a heap object?

void f() {
   X x;
   x.dispose();
}

Indeed, nasal demons FTW, you're trying to free an invalid pointer. Yet if we change that a little bit...

void f() {
   (new X)->dispose();
}

Zomg now it works. It's weird, but it works. Why would anybody on earth do something like this? Can you guess when would this be useful?

Some times you launch a background job, and you don't really care when it's done. You may use a callback to be notified when the job is done, but if you don't really care then having an object which deletes itself is an option. You'll have to be very careful about it, though, because this is legal C++ too:

class X {
  void dispose() {
    delete this;
    std::cout << "Hello worldn";
  }
};

Though "Hello world" will be printed, it will be running in a dead object. Which is fine, as far as the compiler cares, but if you do try to reference the this pointer, you'll be in a lot of trouble.

Bonus reading For a much more interesting note than mine, go and check When does an object become available for garbage collection? in The Old New Thing.

Thursday 31 March 2011

CRTP for static dispatching

So, virtual dispatching is just too much overhead for you? I bet you do need every femtosecond from your CPU. Even if you don't, who doesn't like weird C++ constructs? Take CRTP, for example, a Curiously recurring template pattern:

template <class Derived> struct CRTP {
    const char* greeting() const {
        const Derived* self = static_cast<const Derived*>(this);
        return self->greeting();
    }
};

struct Hello : public CRTP<Hello> {
    const char* greeting() const { return "Hello world"; }
};

struct Bye : public CRTP<Bye> {
    const char* greeting() const { return "Bye world"; }
};

#include <iostream>
template <class T> void print(const CRTP<T> &x) {
    std::cout << x.greeting() << "n";
}

int main() {
    print(Hello());
    print(Bye());
    return 0;
}

Using this weird looking (ain't them all?) template device you can have static dispatching with most of the flexibility of dynamic dispatching. As a bonus, you'll drive all your cow-orkers insane! Bonus non useful information: In C++ 0X you could use variadic templates and have a proxy object with static dispatching. How cool is that?

Tuesday 29 March 2011

Time your time

"time" is a useful command line utility to measure how long it takes for your super optimized algorithm to run, but it's useful as a timer too: just write "time read" and press enter when you get tired of waiting. Instant timer on your console!

Thursday 24 March 2011

Moving away from DB IPC

Last time I wrote about why DB IPC is bad. Now I intend to write about the way to start moving away from it, towards a better architecture.

As I mentioned, this pattern is deeply rooted across all the enterprise platform, so removing it is not an easy task, and it can only be done in small steps. Small steps means a compromise solution, you won't be going from IPC DB to a restful application in a week, so having an ugly-but-not-so-much-as-ipc-db solution is the way to go.

The first step to move from DB IPC to a services oriented architecture is moving from data driven applications to event driven applications. That means, instead of polling the database for changes, receive a notification that the data has changed and act upon the event.

A way to implement notifications without polling is having the DB notify you of any changes occurred. A way of doing this is using something like otl_subscriber, a wrapper to Oracle's notifications features. Postgres has its own notification schema, MySQL AFAIK doesn't.

Once you have managed to separate the responsibility of processing the event and the data of the event itself, it's easy to go one step beyond and implement a messaging platform, like CORBA or something like AMQP.

Conclusion: the architecture may not be nice with DB notifications either, but you have taken the first step towards decoupling two different components. From this schema to a real queue there's only one step, and once there you can finally begin to have a db-schema for each application.

Tuesday 22 March 2011

DB IPC: Communicating processes the wrong way

A common pattern in enterprisy applications is DB IPC, probably one of the worst kind of coupling you can have. If you tell me you never saw it I won't believe you, but in any case: DB IPC is an architecture antipattern, in which you have several semi-independent components which must share some kind of information, and do so through a database. The producer writes into a table, the consumer polls the table for changes.

For an otherwise perfectly designed application, DB IPC may seem like a bad thing but not the worst kind of architecture possible. Clearly a god object may look uglier than an IPC DB. Yet this kind of architecture leads to a tight coupling between the component's inner data structures, making any change in them very unlikely, if not impossible.

Inhouse applications tend to rely a lot on this pattern, albeit unknowingly, for historical reasons: components which are now different applications were once part of a single process, in which no IPC was needed. After these components start growing, instead of a careful and planned change IPC DB gets implemented. It is the path of less resistance, after all.

Steering away from this pattern is very difficult, as it requires a lot of changes to every single application on the enterprise platform, and the introduction of new technologies like CORBA or web services. Seeing this is maintenance job and not productive (i.e. money making) development, it tends to get delayed.

Not everything is lost. An intermediate solution, not as ugly as IPC DB but not so nice as CORBA, is implementing a queue using the DB itself. We'll see a way of doing just that next time.

Thursday 17 March 2011

Truth be told

I bet 90% of enterprisey architecture diagrams are more or less like this one.



From Geek and Poke

Tuesday 22 February 2011

I thought we had deprecated regedit

Guys, I thought we had already agreed on this a long time ago. Windows registry sucks. It's a pain in the ass.

Why TF is regedit still used in Gnome? I'd switch to KDE, if only I wasn't so lazy.

Thursday 17 February 2011

Using BoUML as a case tool

I don't really fancy CASE tools a lot, they are mostly fads, but I must admit it, using BoUML to work on a design the other day was a nice surprise. Not only the generated code didn't seem to be written by an trained monkey [1], it almost seemed to be usable with some tweaking. It even generated nice javadocs!

For this article I'll asume you have some experience with BoUML. If you don't, apt-get it (it's available for Linux and Windows) then come back later, I'll wait. BoUML's manual is quite good and includes a lot of screenshots, but if you're already experienced using it you may find this short checklist quicker to create a new project and use the code generation tools:

  • Languages > C++ [...]; this will tell BoUML what language should generate. I haven't tried other than C++ but I've heard they work fine.
  • Draw some nice UML to create a couple of classes (i.e. create a class view and a class diagram, then add some classes). Don't forget to add some relationships, so the generated code can be something more than "class Foobar{};"
  • Create a deployment view. Something like "Foobar_deploy"
  • Edit the class view, it should open a class view dialog. Select your new deployment view
  • Right click on each class and click "Create source artifact". This'll create a new artifact under your deployment view
  • Almost done. In project > Edit > Edit Generation Settings go to "Directory" tab and select a root directory
  • You're now ready to right click on your class view and select "Generate > C++". Congratulations.

Generating namespaces in C++ wasn't easy at first, and the manual may not be so clear about this one:

  • Create a package. Move everything there (your deployment view, class view, etc).
  • Edit the package. Under C++ complete each path and namespace name (?). For example, Foo, Foo Foo would generate your sources and headers under ./Foo, with namespace Foo.
  • Repeat for as many namespaces as you want. You can have nested namespaces but you'll have to specify the full path and namespace name, i.e. Foo/Bar, Foo/Bar_CPP, Foo::Bar
If you're going to use BoUML as a case tool, you'll want to name associations, use the multiplicity, create setters and getters and all the stuff you probably never did when documenting in UML to reach a minimum user-documentation wheight. It seems these CASE tools haven't developed telepathy yet. Too bad.

Source: $ man BoUML

[1] Regardless of the fact that some may say that about my own code.

Tuesday 15 February 2011

Vim Tip: Vigor

Oh man. Just do a search on google images for Vim + Vigor. There are so many WTF images to choose from, I just can't decide. Apparently since Vim is the name of sexual enhancement drug or something like that, combining Vim and Vigor is a formula for fun.

Well, Vim and Vigor have a different meaning in Linux. Just do an apt-get install vigor, then run it. You'll have lots of fun with Vim's evil cousing, I promise.

Thursday 10 February 2011

BoUML: A usable UML editor for Linux

I bet you've heard it before, some people actually document their projects. Crazy, I know. UML is the tool of choice this days, and a lot of bad applications exist to make your life misserable with half implementations of a half standard language, and random crashes sprinkled here and there to keep you alert and saving at all times (I'm looking at you, Umbrello).

In Linux finding a decent UML application has been quite a difficult task, but after working with BoUML for quite some time I can say this tool, although not without its quircks, certainly meets my acceptance criteria [1].

BoUML, though a little bit unintuitive at first, is quite easy to use. Unlike most UML applications, this one workes closer to a CASE tool, so everything will have to be organized in packages. As a quickstart, create a class view and a class diagram inside that one, but you should really check the official manual. It'll save you a lot of grief, trust me.

On the downside, BoUML is not quite so good for free-style UML, so making a collaboration diagram with network symbols is impossible. I can live with that, Dia is a nice complement for free-style diagrams (it does work... though the result is uglier than an the dog at the end of this post).

[1] WTF after so many years of really bad applications my "acceptance criteria" has fallen so low that "stable" almost equals "good"...