syntax highlight

Monday, 28 September 2009

Ubuntu Day

Spanish only: GNU/Linux, Guía de Supervivencia - Versión Ubuntu Day

Released under WTFPL if you care to know. Source code to be available soon too.

CM WTF

Seen on a cablemodem's configuration page:
<form action="http:/loginData.htm" method="GET">

Long version: The other day, while stranded on a CLI (using ssh) I did a wget $IP, to see a modem's status web page. I'd have thought an electronic device (which, obviously, is much more difficult to upgrade than a software product, and that's difficult enough as it is) is a little bit better tested than that. I should have known better by now.

Thursday, 24 September 2009

sed magic: a simple guide

The other day I had to create one of those "enum to string" functions. They really suck, always getting out of sync, so I made a script to auto-update the header file containing this function... just add a target to the makefile and you're done!

Anyway, this is the part of the script I came up with to get the enum elements:


cat enum_definition.h | sed -n '/enum OID/,/};/ s/(.*)/1/p'

Nice voodoo, isn't it? How the hell are you supposed to understand that? Well, you're not, sed is write-only-code, but you can try reading http://www.grymoire.com/Unix/Sed.html#toc-uh-25, a great sed introduction.

Have fun!

Tuesday, 22 September 2009

gdb: graphic (tui) mode

A little known fact about gdb is that you can use it in graphics mode, called TUI. Yes, you can obviously use DDD or a similar front end but that's not even nearly as cool as using a console based GUI (!), is it?

The easiest way is to start gdb like this:

gdb -tui

That will display the usual gdb console plus a code listing, similar to the code listing you get using the "list" command but shown in another window. Alternatively you can press C-X C-A (both, in that order) while in gdb to switch between TUI mode and back.

Don't know enough about gdb? Read http://beej.us/guide/bggdb/, a great gdb intro.

Monday, 21 September 2009

First Ubuntu Day in Buenos Aires

On sat. 26 of september, this saturday, I'll be on the first Ubuntu Day in Buenos Aires. Of course, I'll be a speaker there, it's time to undust the old GNU/Linux Survival Guide Again.

See you @ Ubuntu Day :)

Tuesday, 15 September 2009

Vim Tip: Rot 13

Are you still puzzled by last week's C++ question, yet you are too lazy to actually search for a Rot13 decoder OR use gcc to check if it works? Well, Vim can do the trick, just use g? to convert text to Rot13

You may combine it with block selection or you can just convert the whole damn thing using "ggg?G". gg goes to the beggining, g? converts to rot13, G goes to the end.

This is all very nice but I'm still trying to figure out a way to convert back from rot13 to normal text, can anyone provide a clue?

Console foo: Scheduling commands

You can easily schedule a command using "at", which recognizes a nicely formatted date string.

For example:

$ at today 3:00 AM

This will open a prompt. So, for example:

$ at today 3:30 PM
> wget foobar.com/a_huge_file
> C-D

Will schedule a download of a huge file, today at 3:00 AM. Nice, isn't it?
To check the whole list of accepted formats check the man for at.

One last note: at will "remember" the current environment variables, so PWD, USER, OLD_DIR and all that will be the same. This means if you schedule a command with a relative path it'll still work!

Thursday, 10 September 2009

C++: incredibly useless stuff

Would this compile? What does it do?

int main() { http://nicolasb.com.ar return 0; }

Answer in rot 13: Vg jbexf. uggc: vf n ynory, // vf n pbzzrag, gur erfg bs gur yvar vf vtaberq.

Monday, 7 September 2009

non-vacations

After some sick time, lots of work, prepearing my new blog (monosinfinitos.com.ar, go check it) and several other,personal stuff regular blog updates will resume tomorrow and continue at least for a week. That's about the buffer size I've left, after that I'll have to write something new or take a longer vacation... we'll see.

In the meantime, enjoy a pretty picture. [BROKENLINK]

Thursday, 27 August 2009

"Good Linux users don't talk about Microsoft"

I don't usually post links, I'd rather write something myself, but check out this quote:
You don’t see me calling Linux users tux turds, penguin poopers or GUI-challenged, do you?

http://www.pcmech.com/article/good-linux-users-dont-talk-about-microsoft/

Enjoy

Tuesday, 25 August 2009

More preprocessor wizardy: strings

No preprocesor wizard should go out of his house without the always useful string maker. Let's say you're trying to create a class with some sort of pseudo type-system (*):

class FooBar {
   public:
   const char* get_name(){ return "FooBar"; }
};

Why would you type ALL that when you can make a simple macro, MK_CLASS, like this:

MK_CLASS( FooBar )
   /* Other methods */
};

Problem is, this will only print "Name":

#define MK_CLASS( Name ) 
      class Name { public: 
            const char *get_name(){ return "Name"; }

Well, it's an easy fix, just prepend # to your string, like this:

#define MK_CLASS( Name ) 
      class Name { public: 
            const char *get_name(){ return #Name; }

Or use this nice string maker:

#define MK_STR(str) #str

As usual, use the preprocesor at your own risk.

(*) Yeah, I know, OO purists will try to beat me to death for this, but it actually has some uses. I've found it to be a specially good solution when working with low level protocols.

Monday, 24 August 2009

Tech Support

Two comics this month, but I'm sure it's worth it:



This advice would have saved me a couple years of life. Normal post tomorrow.

Tuesday, 18 August 2009

C++ oddities: Self initialization

I get it, C++ is a complex language, but man, I'd like a little warning (lol) when this happens:

class Foo {
  int bar;
  Foo() : bar(bar) {}
};

Yeah, it bit me in the ass the other day. Why? A method's signature was awfully long, I wanted to delete a parameter and ended up deleting two. Luckly my unit tests where there to save the day, but regardless, WTF?

Tuesday, 11 August 2009

Ubuntu: Dual monitors

There's nothing better than feeling like a super villain by having a dual monitor setup. OK, three may be better, you probably couldn't hold back the evil laughter, but my laptop won't support three screens.

Fortunately, in Ubuntu JJ having a dual screen setup is a breeze. Just plug the two monitors and hope it works. Of course, it may not. If that's the case you can go to System > Preferences > Screen for a nice GUI, which will let you select each screen's resolution and position. Nothing better for productivity than having your monitors swapped, or even better, flipped upside down.

Well, sometimes "Screen Preferences" won't work either, too bad. In that' case you'll have to get dirty with xrandr. It's not too difficult but it's console based (you're not scared of the console, are you?).

Though the man page for xrandr is a little bit intimidating at first you'll just have to do it once, so I won't write about using it, I will just copy & paste a script I keep in my desktop to fix the screen whenever it brakes (my lapop tends to foobar my screen when being docked or undocked, not sure why)

xrandr --output HDMI-2 --right-of HDMI-1 --mode 1680x1050 --rotate normal

I am sure you can figure out the rest on your own - enjoy the dual screen setup!

Thursday, 6 August 2009

Ubuntu: Annoying terminal warning

Although I'm quite happy with Ubuntu 9.04, I find a couple of new features quite annoying. The warning message it pops up whenever you try to close a console with a running program in it falls in this category. Fortunately it's not difficult to disable:

  1. Open up gconf-editor
  2. goto /apps/gnome-terminal/global/
  3. Untick confirm_window_close

All set. As a bonus side effect now closing a terminal with multiple tabs won't pop up a message either.

Monday, 3 August 2009

C++: Magic callbacks solved

Long post this time - and lots of code too. How fun iz that? Anyway, remember where we left last time? We're supposed to make this work:

class Callee {
 Callback notify;
 public:
  Callee(Callback notify) : notify(notify) {}
  void finish(){ notify(this); }
};

class Caller {
  Callee c;
  public:
  Caller() : c(Callback(this, &Caller::im_done)) {}
  void im_done(Callee*) { }
};

I'll write about the different solutions I've tried and the problem each of these solutions had:

Experiment 1: Templates

We could to this the easy way, with a template:

template <class Callback>
class Callee {
  ...
};

class Caller {
 template <class T>
 void operator() (T p){ this->im_done(p); }
  ...
};
This has some drawbacks:
  1. We need to change the definition of the Callee
  2. The Caller can only have one callback (or overloaded one callback)
  3. It's boring

Experiment 2: Template virtual method

So, lets try another approach: the naive one is an interface:

class iCallback {
  public:
  template <class T> void operator () (T o) = 0;
};
Looks great, doesn't it? Too bad it's not valid C++, you can't have a virtual template method (what would the vtable size be?). If we can't have a template method let's make a template class:
template <class T>
class iCallback {
  public:
  virtual void operator () (T o) = 0;
};

class Callee {
 iCallback<Callee*> *notify;
  public:
  Callee(iCallback<Callee*> *notify) : notify(notify) {}
 void finish(){ (*notify)(this); }
};

class Caller : public iCallback<Callee*> {
 Callee c;
  public:
  Caller() : c(this) {}
  void im_done(Callee*) {}
 void operator ()(Callee *o){ im_done(o); }
};

It may not be pretty but it works. Also, adding a callback means adding a new operator (). Lets try to improve it a little by removing the nasty inheritance (remember, always prefer composition over inheritance):

Experiment 3: Callback Object

template <class P>
class iCallback {
 public:
  void operator () (P o) = 0;
};

template <class T, class P>
class Callback : public iCallback<P> {
 // Notice this typedef: we have an object of type T and a
  // function accepting a parameter P
  typedef void (T::*member_func) (P);
  T *cb_obj; member_func f;

 public:
  Callback(T* cb_obj, member_func f)
     : cb_obj(cb_obj), f(f) {}

 inline void operator() (P o){
    (cb_obj->*f)(o); // ->* is the best voodoo operator
  }
};

This new object should help us to:

  1. Implement different callback functions (not tied to an operator() nor a type overload) while staying type-safe
  2. Delete the inheritance
  3. Use the arrow-asterisk operator (!) which is way cool

How would this change leave our code?

class Caller;
class Callee {
 Callback<Caller, Callee*> *notify;
 public:
  Callee(Callback<Caller, Callee*> *notify) : notify(notify) {}
  void finish(){ (*notify)(this); }
};

class Caller {
 Callback<Caller, Callee*> cb;
  Callee c;
  public:
  Caller() : cb(this, &Caller::im_done), c(&cb){}
  void im_done(Callee*) {}
};

Oops, looks like we took one step back: now Callee MUST know the type of Caller. Not nice. Luckily it is an easy fix:

Experiment 4: Callback interface

class Callee {
  iCallback<Callee*> *notify;
  public:
  Callee(iCallback<Callee*> *notify) : notify(notify) {}
 void finish(){ (*notify)(this); }
};

OK, we're back on track. We will solve that weird looking (*notify)(this) later, don't worry.

We're almost there, but specifying the callback as is ugly, Caller should be automagically inferred from the context by some template voodoo. Let's do it by implementing a wrapper:

template <class R>
class WraperCallback {
  iCallback<R> *cb;
  public:
    template <class T, class F>
    WraperCallback(T* cb_obj, F f)
       : cb( new Callback<T, R>(cb_obj, f) ) {}

    ~WraperCallback() {
      delete cb;
   }

   inline void operator()(R o){
     (*cb)(o);
    }
};

Now we no longer need to specify the Caller type. There's still a nasty issue about pointer-vs-object passing. Using (*notify)(this) is very ugly so let's do it like this:

Experiment 5: Callback object bis

class Callee {
  WraperCallback<Callee*> notify;
  public:
  Callee(WraperCallback<Callee*> notify) : notify(notify) {}
 void finish(){ notify(this); }
};

class Caller {
  Callee c;
  public:
  Caller() : c(WraperCallback<Callee*>(this, &Caller::im_done)) {}
 void do_it(){ c.finish(); }
  void im_done(Callee*) { }
};

Nice, this time it should work as expected. Only it does not, there is something horribly wrong about it. Can you see what it is? Take a second, I'll wait... OK, back? Right, it segfaults! Why? Easy, take a look at this:

  Callee(Callback<Callee*> notify) : notify(notify) {}

We are using a copy constructor here, and what does our wrapper store?

    WraperCallback(T* cb_obj, F f)
       : cb( new Callback<T, R>(cb_obj, f) ) {}

Indeed, the copied WrapperCallback ends up pointing to a deleted Callback when the cb field of the original object gets copied and then destructed. We should have all the pieces to fix it now: we just need to implement the copy operator to make it work. How does the final version looks like?

Solution

template <class P> class iCallback {
  public:
    virtual void operator()(P) = 0;
    virtual iCallback<P>* clone() const = 0;
};

template <class T, class P>
class RealCallback : public iCallback<P> {
  typedef void (T::*member_func) (P);
  T *cb_obj; member_func f;

 public:
  RealCallback(T* cb_obj, member_func f)
     : cb_obj(cb_obj), f(f) {}

 /**
   * The clone operator is needed for the copy ctr of
   * the Callback object
  */
  inline iCallback<P>* clone() const {
   return new RealCallback<T, P>(cb_obj, f);
  }

 inline void operator() (P o){
    (cb_obj->*f)(o); // ->* is the best vodoo operator
 }
};

template <class R>
class Callback {
  iCallback<R> *cb;
  public:
    template <class T, class F>
    Callback(T* cb_obj, F f)
       : cb( new RealCallback<T, R>(cb_obj, f) ) {}

    Callback(const Callback& cpy)
        : cb( cpy.cb->clone()) {}

    ~Callback() {
      delete cb;
   }

   inline void operator()(R o){
     (*cb)(o);
    }
};

Conclusion

Now we have a nice callback object which can link two objects without them knowing each other. There is room for future improvement, of course:

  1. Got any ideas to implement a generic callback to a function with an unknown number of params? I don't (variadic templates == cheating!)
  2. I'm quite sure the param type for the callback could be inferred in some magical template way, but I don't know how.
  3. Think of anything else to add? Let me know in the comments!

Thursday, 23 July 2009

mocp rand

I'm quite sure everyone reading this must have a respectable, if not massive, music collection. In this days and age is difficult finding someone who doesn't. It's also difficult to choose one, and only one, disk to listen at any given moment. Until we're upgraded to support concurrent music listening we're better of with a random disk selector, which is exactly what this little script does:

#!/bin/bash

SEARCH_DIR="/home/nico/MĆŗsica"
START_RANDOM=1
RAND_MAX=32767

while (( 1 )); do
  NUM_DISCS=$(find $SEARCH_DIR -type d | wc -l)
  RAND=$(($NUM_DISCS * $RANDOM / $RAND_MAX))
  RAND_DISC=$(find $SEARCH_DIR -type d | head -n $RAND | tail -n 1)

  # Wake up moc
  mocp -FS 2>/dev/null >/dev/null &
  mocp -pca "$RAND_DISC" &
  echo "Playing $RAND_DISC"

  # Start from a random file?
  if (( $START_RANDOM )); then
    mocp --on shuffle &
    mocp -f &
    mocp --off shuffle &
  fi

  read
done

Of course, it requires mocp, my favorite music (on console) player. And obviously, you'll have to configure SEARCH_DIR but I'm sure some bash hacking is not that hard.

Beware though, using this + cron may have the undesired effect of awakening to the pleasant music of Cannibal Corpse.

Tuesday, 21 July 2009

C++: Magic member callbacks

Short post about C++ this time - though calling it a request would be more appropiate. I'm trying to create some kind of magic callback to do this:

class Caller {
 Callback c;
  public:
  Caller(Callback c) : c(c) {}
 void doit(){ c(this); }
};

Shouldn't be too difficult, right?

There are some hidden complexities, of course, mostly regarding the callback parameter type, but the idea is simple, keep the caller dependant only in the callback, not in the callee.

Templates are not a valid solution as the callee may have more than one callback (i.e. expect more than a single object to finish and call the callback) so the whole idea of this is having the callback "bind" to a member method when created, doesn't matter which one.

I have a solution, tough I'm not too happy about it for now. I'll post it next week, unless someone comes up with a better idea (you know how to submit it if you do, right?).

Tuesday, 14 July 2009

GNU/Linux: Emergency Restart

It happens: we're happily hacking on some code and out of nowhere X server freezes. It may be the latest Compiz whose at fault, or perhaps a stray program that decided it should start consuming all available CPU. Anyway, it's easier to reboot than trying to fix whatever got broken but Ctrl - Alt - Backspace is unresponsive and we can't drop to a console. It's not ussual but it happens. What can we do about it?

There's a cool shortcut to help us when shit happens, it'll reboot the computer and it's a little bit nicer than yanking out the power cord. You just need to remember REISUB and have some keyboard dexitry - holding down Ctrl - Alt - SysRQ/PrintScreen is required while typing REISUB (don't do it now, it'll reboot your computer!).

So, what's REISUB all about? It's a little bit better than a forced hard reboot because it'll:

  1. R: Restore console
  2. E: Send SIGTERM to all processes
  3. I: Send SIGKILL to all processes
  4. S: Emergency sync of all filesystems (commit any changes to the phisical media)
  5. U: Read only remount of all filesystems
  6. B: Reboot now

So, off course, you'll have to wait a little bit between every keystroke. Press Ctrl + Alt + PrntScreen + H on a console to get some help on every command.

Why does it work?

There's a lot of magic involved to make this secret incantation work. It involves kernels, vectors and other mythical beasts. There's a crazy thing called interruption vector; it's the place where every (hardware) event gets dispatched to a handling function. There lives a function call to handle keyboard input, amongst other things. This function call will be executed always, though the SO may just decide to queue the keyboard input if it's too busy handling something else.

Well, this key combination can't be delayed 'till later, it must be handled NOW, therefore, even if there's a stray process or a driver gone mad, it'll always be caught and the computer will be rebooted.

What's the catch? You won't be saving that precious code you we're hacking away when it all started, but at least you'll save some fscking time on the next start up.