syntax highlight

Monday 30 November 2009

Console Ninja

My latest presentation is now online: "Console ninja". Spanish only, at least for now.

On a related note: I'm taking some time off, in a week or so I'll be back to my (un)regular schedule.

Monday 2 November 2009

New talk on the way

I'm polishing my latest talk, "Ninja console" which will be made available to the public soon. More news to come.

Tuesday 27 October 2009

D.A.T.A.E

Damn Acronyms, They Are Everywhere. I'm working on a project which is named as an acronym (IWC) of acronyms (IW CWMP) of acronyms (IW CPE WAN Management Protocol). You need a parser just to understand the project's name. Gotta love it.

Friday 23 October 2009

Retrofitting unit tests for legacy code

Some time ago I saw a discussion at google test mailing list which made me ask myself how would I go about implementing TDD for a legacy codebase project, based from previous experiences. I came up with a list, open to discussion, which may be useful as a guideline for someone in this situation.

Start with integration tests

Integration tests are ugly and won't give you a lot of information about what went wrong when something does, but you have no chance of running real unit tests in non-injectable code.

Use the integration tests as a safenet to refactor the critical methods, those which will be changed the most during the projects lifetime, which leads me to the next point;

Test as you refactor (or implement new functionality)

If you plan to stop the business and write a kabillion tests for your legacy codebase you're out of luck. Not only you'll fail because the lack of value but you'll spend weeks writing tests and never see the ROI - you'll quickly grow tired.

With integration tests in place take your time to write real unit tests as needed, that is when you implement new functionality or when you plan to refactor something - which should be to implement new functionality or to fix a bug.

KISS

Can't stress this enough: keep your tests simple. You'll notice you end up with 80% boilerplate code, setting up mocks, creating test objects, etc. When that test fails you'll have no clue why was it there in the first place.

This happens a lot with legacy codebases, where stagnant code tends to get quite coupled and messy. If you plan to write a big mega test to cover every use case with a single test, the day it fail you'll quickly know it's not production ready but you'll have no clue why is that.

Mock layers

If you have a project divided in components (even the ugliest legacy code tends have some sort of layers separation, even if coupled with other components) try to create mocks for a whole layer of the application (I ended up with a complete mock of a DB, for example). This will help you in the long run to isolate troublesome modules.

Have a team commitment

If you're working on your own or with a team, make it mandatory to run the tests for each commit. Even better if you can implement a continuous integration server.

Wednesday 21 October 2009

Vim Tip: Open file in new tab

How many times have you been on a project which #includes another file and wanted to see what that file was? Well you can navigate the source code tree in a gui if you use eclipse. You can go to File > Open and, again, fight with a nice gui in Notepad. Or you can open up that file with four keystrokes in a real editor, THE real editor. Just use "C-W g f" with the cursor over the filename and it'll open in a new tab, ready for you to hack away more code.

Monday 19 October 2009

Methods and instance variables: should there be a difference?

Many times I find myself forgetting the parenthesis for a method with no arguments and a nasty compiler error. This reminds me of my Rubyst times. There's no difference between methods and instance variables in Ruby, so this:

class Foo
  @bar
end

foo.bar = 1

Could be changed to

class Foo
  @bar
  def bar=(val) @bar = val end
end

foo.bar = 1

and the dependant objects using the property would use the new behaviour without ever needing a change in the way bar is accessed.

In languages like C++ the parentheses are mandatory so you can have a clear difference between instance variables and methods, and between a method call and a function pointer (which should be referenced as &Foo::bar and not Foo::bar anyway).

All of this always leads to the same conclusion: closing parenthesis should not be needed!

Friday 16 October 2009

Zomg! happy (late) birthday

Can't believe it... a whole year has gone by and I didn't even notice. The frist psot was over a year ago and now with over a hundred posts in the archives, a second blog [spanish only] starting, many changes in the directions of the articles and a timidly and ever quiet growing reader base, I can say I didn't learn anything at all from the experience.

I bet that's not the kind of speech you were expecting but the message I would like to transmit today is this: to all the people trying to start a blog, do it for fun, nothing more nothing less. Don't expect any kind of epiphany (not even in a web browser form) nor a sudden burst in online popularity (what for anyway?). You may get those as a byproduct of the experience but starting a blog only for that is a recipe for boredom and frustration.

Write, for a whole year, just because it's fun

Thursday 15 October 2009

Write in C

From http://www.youtube.com/watch?v=J5LNTTGDKYo&feature=related Write in C
When I find my code in tons of trouble,
Friends and colleagues come to me,
Speaking words of wisdom:
"Write in C."

As the deadline fast approaches,
And bugs are all that I can see,
Somewhere, someone whispers:
"Write in C."

Write in C, write in C,
Write in C, oh, write in C.
LISP is dead and buried,
Write in C.

I used to write a lot of FORTRAN,
For science it worked flawlessly.
Try using it for graphics!
Write in C.

If you've just spent nearly 30 hours
Debugging some assembly,
Soon you will be glad to
Write in C.

Write in C, write in C,
Write in C, yeah, write in C.
BASIC is for wimps.
Write in C.

Write in C, write in C,
Write in C, oh, write in C.
Pascal won't quite cut it.
Write in C.

Write in C, write in C,
Write in C, yeah, write in C.
Don't even mention COBOL.
Write in C.

And when the screen is fuzzy,
And the editor is bugging me.
I'm sick of ones and zeros,
Write in C.

A thousand people swear that T.P.
Seven is the one for me.
I hate the word PROCEDURE,
Write in C.

Write in C, write in C,
Write in C, yeah, write in C.
PL1 is '80s,
Write in C.

Write in C, write in C,
Write in C, yeah, write in C.
The government loves ADA,
Write in C.

Write in C, write in C,
Write in C, yeah, write in C.
Java's not quite there yet,
Write in C.

Wednesday 14 October 2009

Lighty WTF

Seen @ Lighttpd

242:	srv->srvconf.reject_expect_100_with_417 = 1;

That line should totally be "= 42"

Monday 12 October 2009

What I like about Linux and C++

Some time ago I worked in a team with a guy who liked programming in Java. Really like it, to the point where the weaknesess of the language were all in his blindspot. I did the only sensible thing a guy like me can do, sent him a mail stating that the lack of closures in Java would doom the language as soon as C++0X comes out.

That is not really my opinion but it sure served my pourpose. Trolling. Obviously I recieved a three page email back, explaining why adopting closures as part of the Java specification was irrelevant due the use of inner classes (?) or something like that, I don't remember now.

I must admit this was not my first time trolling around a language zealot (and it IS fun, let me say it) may this post serve as a public apollogy for those who have suffered it.

What was that long introduction for? There are lots of religious wars amongst programmers. Vim vs emacs, Windows vs Linux, tabs vs spaces. We all know (Vim, Linux, tabs) what are the best options, but fighting is still fun and with due respect for each other quite healthy.

It's difficult to distinguish when "religious fantatism" for a tecnology overcomes pragmatism, making a task much more difficult than it should, instead of simplifing it, because of the use of a specific tool. Take for example watching a movie in console mode. Kudos to whoever can do it, I have better things to do in my spare time.

How does all this relate to Linux, C++ and programming in my twisted mind? What I've noticed about (most) people using C++ and GNU/Linux as a working platform is that we are always complaining. No, I don't mean we're grumpy old dinosaurs (altought you can certainly find a fair share of those too) but you tend to meet people who are much more aware of the limitations they platform of choice has.

In my years as a programmer I've worked with PHP, Java, .NET, Ruby, Linux, Windows, etc. From all these platforms I could say I found people truly offended when told their platform sucks. Most, if not all, C+++Linux (lol, ain't I smart?) programmers I've found so far have one thing in common: they (we) all know both Linux AND C++ suck. They suck hard, C++ syntax is messy, Linux has configuration and portability problems, pointers will screw you at any chance. But we know this.

Far more important than actually choosing the perfect OS, the perfect language, the perfect whatever, choose what better fits your skills and your team, then know your limitations by hearth. It'll save you lots of trouble.

PS: I like the new category, "Grumpy". Here I'll post all kind of rants and subjective opinions I feel like posting.

Friday 9 October 2009

Grumpy Old Man: What I Hate About SQL

SQL is ugly by itself, it may rightfuly be considered so by its pseudo standarization, the ugly syntax and many other things which don't matter here, but there's something really really stupid, one bit of its syntax which drives me crazy.

Why, why oh why, doesn't the standard allows "SELECT Foo, FROM TABLE" to be valid syntax? I always forget to remove the last comma when there are lots of fields and don't tell me you don't, I know that is a lie!

</rant mode off>

Tuesday 6 October 2009

Vim Tip: Folding FTW

I always say methods should have two levels of indentation at most, but even if your code is perfect like mine you may still have to dwell with other people's code (which, obviously, is ugly code), people how may have lots of fun shaping the program like a pyramid.

Not all is lost, you don't have to commit sepuku (at least not for this one). Just use Vim's indent method like this:

:set foldmethod=indent

That should give you a better view of the code flow. As always, use '%' to navigate all those pesky { and }.

Thursday 1 October 2009

gdb: debugging multithreaded applications

Few things look cooler than debugging a multithreaded application using TUI through ssh on a client, halfway across the world. There you are, felling the geek of the century when all of the sudden gdb starts jumping from one thread to the other. OMFGBBQ! What are you going to do now?

The scheduler locking policy defines when will thread context swtiches occur. If you are debuging a thead and don't want to be bothered by another then just lock the scheduler.

gdb has a default scheduling locking which defaults to "most annoying", but fortunately you can easily change it: set scheduler-locking

The possible values are:

  • off: Disable locking, switches threads whenever gdb damn pleases
  • on: Enable locking, won't (ever) switch threads. Beware of deadlocks!
  • step: Disable locking while running only

Hopefully this will save you some time.

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.

Saturday 11 July 2009

Vim Tip: Select everything

There's an easy way to select the whole contents of the document: "ggVG". May seem like a lot at first glance but let's review it part by part:
  1. gg: Go to the beggining of the document
  2. V: Enter visual mode
  3. G: Go to the end of the document

Easy, isn't it? Now you can press any other command to copy, delete or whatever you like.

Thursday 9 July 2009

LaTeX: Including Source Code

I'm sure every programmer has had to include source code in a document at least once, an architecture documentation for example, or perhaps as part of a presentation (beamer FTW, coming soon!). With most document formats including source code usually means writing the code and use some kind of manual syntax higlighting. Of course, any time you change the source you'll need to manualy update the document.

In LaTeX there's an easy way to handle source code. Though it was difficult to figure out, once in place this requires no maintenance at all - no need to manually syntax highlight your code nor update any files other than the source code itself. Even more, you can even change the source code language and it won't even matter in the presentation.

Preliminars

You'll need "pygmentyze" which is provided by the package python-pygments:

apt-cache search pygment
python-pygments - syntax highlighting package written in Python
sudo apt-get install python-pygments

Using it is really easy, check the manpage. Anyway, I'm too lazy to generate the syntax highlighted document by hand, let's add it to the makefile.

Automating the source code generation

Let's beging by adding a "code" folder inside our project. We'll store there all the source code files, and having them in a separated folder will enable us to add a target in the makefile to automatically update the source code in the LaTeX file.

Remember the makefile from a couple of posts back? Let's add a target:

# Hack to make it work when foo.code => foo.code.tex
code/%.tex: code/%.* code/%.aux code/%.tex
  @rm code/*.aux
 $(MAKE) -C .

code/%.tex: code/%.*
 pygmentize -f latex -O style='border=#000000,colorful,linenos=1' $< > $@

# Search each code file to format and include
CODE_FILES:=$(shell ls code/|egrep -v '.tex$ |.aux$ ' )
CODE_FILES_DEP:=$(addprefix code/, $(CODE_FILES))
CODE_FILES_TGT:=$(addsuffix .tex, $(basename $(CODE_FILES_DEP)))

main.pdf: $(shell ls *.tex) $(CODE_FILES_TGT)
  pdflatex main.tex > /dev/null

OK, maybe a couple more than one. It may seem like a lot of makefile code but all it does is define a code directory and a target to run pygmentize on each source file found there. We'll have to add a dependency in the document's target so it'll be automatically generated with each build:

main.pdf: code_frames *.tex
  pdflatex main.tex && pdflatex main.tex
and then, we'll need to clean up the new temp files:
code_clean:
 @rm -f $(CODE_FILES_TGT) code/*.aux

Don't worry, there's a link to the full makefile.

At last!

It shouldn't have been too much work and we're done anyway. To include a source code file in your document now use the include command (like include{code/foobar.cpp) and re build. I'm attaching a complete example in a zip file, with my latest implementation of a bogosort algorithm (now 50% faster).

Tuesday 7 July 2009

LaTeX: including documents

This is a post from my LaTeX series - check the others too!

So far we've seen some of LaTeX advantages, and a few basic commands to get you started. Let's see a trick to be more proficient with it:

Including other tex files

You should be able to write some simple documents now, some in LyX, some in LaTeX, but you'll soon start to notice that using a single text file to create a large document becomes cumbersome. Even more so if you need to split the work between several people in a team.

There's an easy way to keep a main file and then several, smaller, files in which you can work more comfortably:

include{file.tex}

Easy, right?

Beware, you can't use an include inside an include. Why? No idea, but there's a way around this:

input{file.tex}

Quick preview

Using includes has another advantage: you can have a quick preview while working with a chapter at a time. I usually keep the following structure within my projects:

% Header declarations
% Include packages
% Document preamble
% ...

%input{chapter1.tex}
%input{chapter2.tex}
input{chapter3.tex}
% input{chapter4.tex}

Just uncomment the chapter you're working with. In big documents this has a very noticeable effect, as compiling a large LaTeX file into an enormous pdf document (several MBs) may be quite slow.

Of course, I use "input" in my main file so I can use include in the chapters themselves. I won't usually need to include other documents inside the chapters, it'd get quite messy, but it's necessary to work with embedded documents, as we'll see in another post.

Saturday 4 July 2009

Thursday 2 July 2009

LaTeX: Makefile

Remember I said that being a programmer would make you a lot more comfortable around LaTeX? The reason is quite simple, tex is just source code for a document. As with any source code in Linux (Windows too, but that is besides the point) you can use a Makefile to compile it and make your life easier.

I have already posted this Makefile in another entry but it's time to explain how it works.


all: main.pdf

main.pdf: code_frames *.tex
  pdflatex main.tex && pdflatex main.tex 

.PHONY: run clean edit
edit:
  gvim -S vim.sess

run: main.pdf
 evince main.pdf &

clean:
 @# for each .tex file, remove the extension
 @#    and delete its generated files
 @for PART in $(shell ls *.tex| sed 's:.tex::g'); do
   echo "*.out *.nav *.aux *.toc *.log *.snm *.pdf *.vrb" | \
      sed "s:*:$$PART:g" | xargs rm -f;
 done

It's rather easy, let's check it target by target:

  • all: create the main document - used as default target
  • main.pdf: document's target - no need to call it main.pdf, I just do it because the entry point in C programs is called "main" so I'm used to it. Also, it looks better than foo.pdf. As a side note, it runs twice "pdflatex" because it first creates the document and the second time updates the document's index.
  • edit: I usually have a single document split in many files, so keeping a line to quickly open up your editor with all this files is handy. I just keep it as a Vim session, no need for more
  • run: target to open up the document in a pdf viewer. I call it run so I can use it with my default mapping in Vim
  • clean: clean up the files created while compiling a document. Some times it's needed if there's an error you can track - it may be a corrupted .aux file

Short entry this time - next: using source code from within LaTeX.

Monday 29 June 2009

LaTeX: LyX Revisited

Seeing I'm publishing a new LaTeX series it seems appropiate to review my old LyX article. This is just a copy & paste from http://debaday.debian.net/2008/01/20/lyx-a-text-editor-that-stays-out-of-the-way/

Did you ever get to struggle against your text editor’s random format feature while trying to write a document? Open Office may be a great project, but when you want to focus on the content, it can be annoying to have your editor format or unformat your text, seemingly at random.

Well there are good news for those of us using Vim to create content and then Abiword to format it: LyX is a text editor that produces beautiful documents, without the need of being a designer, and yet manages to stay out of the way. From the tutorial and the homepage (www.lyx.org):

LyX is the first WYSIWYM (What You See Is What You Mean) document processor. The basic idea of LyX is that you do not need to handle style, or actually, you use a set of predefined styles and concentrate on your document content, This makes sure that your resulting document will be typographically correct and good looking visually. […] LyX uses Latex as its back end typesetting mechanism.

Sounds great already, doesn’t it?

A first look into LyX

Upon start LyX looks more or less like any other graphical text editor in the universe:
[MISSING IMAGE]

Well, it’s logo may look nicer, but that’s about it. Anyway, the magic starts just as you start writing: you’ll notice most of the common format options seems missing, but you can define what you’re writing instead:
[MISSING IMAGE]

Note that we don’t tell it to center it or to make the font larger and bold. LyX takes care of all that automatically. Simply click on the format menu (below File, and it has the default value of “Standard”).

So instead of defining Times New Roman 12px bold centered, you say «Title». WYSIWYM, remember? In the homepage there is a «Graphical Tour» with all the basic functions, it’s quick and it’s great: www.lyx.org/LGT

Some useful features

LyX also provides a great support for math formulas (and all the weird symbols you can think off). Just click the button «Insert Equation» and a box to enter math symbols will appear. No more struggle to align the dividend and the divisor!

Of course, LyX provides the usual features such as tables, spell checking, footnotes and many more. The tutorial of the application is more than complete, and easy to follow.

LyX documents formats

LyX documents can be exported to a wide variety of formats, mainly because being based on Latex it takes advantage of the already existing conversion programs. Some of the possible export plugins installed by default are PS, PDF, DVI, Latex, HTML and Plain text, but custom ones may be defined.
What LyX isn’t for

Although LyX may be a valuable piece in anyone toolkit it’s worth noticing it isn’t exactly the Swiss army knife of the text editors. If you need to define a very customized layout or format, like slides for a presentation, this is the wrong tool for the job.

Availability

According to it’s homepage, LyX 1.5.3 was released the 16 th of December, 2007. It’s available in Debian since Sarge (packages.debian.org/LyX). Lyx Version 1.5.1, released 4 th of August, 2007, is available in the repository of Ubuntu 7.10. Development is still active. There’s also a Windows version for those of us stuck with primitive a OS at work.

Saturday 27 June 2009

Welcome!

A good friend of mine (a programming junkie just like me) just started his blog, so this is kind of a welcome. Actually there's already a link somewhere in this page so this post is just an excuse to post this recommendation about writing articles for a blog:

Remember you didn't like books without pictures as a child? Well, Internet's mental age isn't a day over four years old, use pretty pictures whenever you can.

Thursday 25 June 2009

Unique var name with C/C++ macros

So, you're working on some macro magic incantation and you need a unique variable name in you C program? Though it may seem simple at first, using __LINE__ for a variable name, the ## operator (concatenation in the preprocesor) won't let you. There's a secret spell to do it anyway:

// Do magic! Creates a unique name using the line number
#define LINE_NAME( prefix ) JOIN( prefix, __LINE__ )
#define JOIN( symbol1, symbol2 ) _DO_JOIN( symbol1, symbol2 )
#define _DO_JOIN( symbol1, symbol2 ) symbol1##symbol2
Great, now you can keep obscuring your programs even more - have fun!

Monday 22 June 2009

LaTeX: format basics

Basic structure

So, what's the most basic structural elements for any document you write? Paragraphs, of course. I ussualy use LyX for writing paragraph-based documents (i.e. most of them) and presentations don't have many, so perhaps this is the structural element I use the least. Oh, wait, there's no element, just a "nn". Point for LaTeX (take that, HTML).

You'll also need to put titles, sections, subtitles and all that stuff to give your document a nice structure. Well, that's easy too, just use

  • section{name}
  • subsection{name}
  • subsubsection{name}
Easy, right? Check the example at the end of the post.

There are some other commands you'll use in any LaTeX document:

  • Footnotes:
    footnote{ Footnote text }

    Just write your text, it'll be there when you compile the document
  • Vertical skip:
    bigskip

    Because, some times, LaTeX default formatting won't be enough.
  • Align text Center:
    begin{center}TEXTend{center}

    Right:
    begin{flushright}TEXTend{flushright}

    Again, some times you may need it. Not too often, though.

You should now be able to write your first LaTeX document, starting from a template (always start with a template... it's easier). I'm attaching to this post an example document in LyX, LaTeX and its compiled pdf, in case you're wondering what does it look like in the end. For the next entry: some "advanced" tips and tricks, now let's see an example LaTeX document:

documentstyle[11pt]{article}
title{LaTeX Example}
author{Nicol'as Brailovsky}
setlength{topmargin}{-.5in}
setlength{oddsidemargin}{.125in}
setlength{textwidth}{6.25in}

begin{document}

maketitle
This is just a LaTeX kick off, with some basic commands.

section {Section one}
For example, this is a paragraph.
begin{quotation}
{ em Lorem ipsum dolor sit amet, consectetur adipiscing elit.}
Donec porta, enim eget tempus tempor, eros sem dapibus diam, vitae lacinia mauris metus id nulla.
end{quotation}

subsection{Subsection}
You can have subsections too ldots

subsection{Subsection'}
ldots as many as you want

subsection{Random stuff}
You can even create a shopping list in LaTeX, if you wish
begin{center}
begin{itemize}
item Beer
item Beer
  begin{itemize}
    item (Another brand of beer)
  end{itemize}
item Pizza
item Beer
end{itemize}
end{center}

Or even better, use it to do the homework. \
Math is a breeze in LaTeX: $x_n = sqrt{a + b}$ can be typeset inline.
end{document}

You can download the compiled document from this link. May be it doesn't look too useful (I'd use LyX instead) but soon we'll start doing some cool stuff LyX can't handle. Keep tuned for the next LaTeX article.

Sunday 14 June 2009

Vim Tip: Easy Indent

Editing source code means you'll be doing a lot of indenting and reindenting. There's an easy way to indent or de-indent a block, using just "<" and ">".

Using ">" without anyother command will indent that line by itself; use visual mode (Shift + V) to select several lines and indent them in one keystroke. You could also press "v%>" while sitting at the beggining of a block to indent it. The same applies to "<".

 

Thursday 11 June 2009

vimrc: Vim startup file

I usually create a partition for /home, so whenever I decide to foobar my OS (i.e. do a kernel update on Ubuntu, or start playing with compiz too much) there's no need to copy my home folder to another disk and back again. Regardless of this, there are some essential files which I'd be dead without. One of these is my .vimrc, the startup file for Vim.

My .vimrc file has been organically growing since I started using this editor, a couple of years ago, so I've decided to clean it up a little bit and post it here, just to be sure I won't be loosing it. It's got some tweaks to use Vim as an IDE, feel free to download it and change it or use it anyway you want.

colorscheme torte
set nocompatible
syntax on
set ruler
set number
set hls     " Highlight search results
set showmatch " Show matching () {} []
set wildmode=list:longest,full  " Use tab-completition
set mouse=a       " Always use the mouse
" Set the working directory to the directory of the current file.
autocmd BufEnter * lcd %:p:h

" Allow movement to another buffer without saving the current one
set hidden

" *********** Text formatting *************
set nowrap
set beautify
set shiftwidth=3
set tabstop=3

filetype on
filetype plugin indent on
" *********** Search & replace *************
set ignorecase " case insensitive
set smartcase " case insensitive only if there is no uppercase
set incsearch " incremental seach
set gdefault " default to /g on replace

" Load matchit (% to bounce from do to end, etc.)
runtime! macros/matchit.vim

augroup myfiletypes
 " Clear old autocmds in group
 autocmd!
 " autoindent with two spaces, always expand tabs
  autocmd FileType ruby,eruby,yaml set ai sw=2 sts=2 et
augroup END

" display the current mode and partially-typed commands in the status line:
set showmode
set showcmd

set autoindent
set smartindent
" Show an error window (if there are errors)
cwindow

" *********** Mappings *************
" Ctrl-t: Write tabnew (wait for filename and )
map  :tabnew
" Alt-R: Exec current file as script
map  :!.%
" Ctrl-Alt-R
map  :tabnew:make
" Spellcheck
map  :!ispell -x %:e!
" Comment a line
map  0i//
map  0xxx

" Build for a LaTeX file (assumes correct path and makefile)
autocmd filetype tex map  :w:make

" Automatic closing
kets
inoremap do{ do{}while();O
inoremap do{ do{}while();O
inoremap { {}O

Tuesday 9 June 2009

apt-get install new computer IV: round up

Quick post this time - just a roundup of the "apt-get install new computer" series. This is a one liner I use in any new install I'm planning to work with, hope it's useful for you too.


sudo apt-get install lyx mozilla-thunderbird tilda mmv \
   unclutter gnome-do moc ffmpeg shntool cuetools flac \
   wavpack vlc deluge bittornado-gui build-essential \
   gcc g++ valgrind latex-beamer ssh sshfs openssh-server \
   vim vim-gtk sun-java5-bin sun-java5-jdk sun-java5-jre \
   sun-java6-jdk antiword ifstat php5 php5-mysql php5-pgsql \
   php5-cli php5-gd php5-curl ruby1.9 irb1.9 rails rake valgrind

New package: antiword - read office documents on console

Friday 5 June 2009

Vim Tip: Know your blocks!

Vim is the best editor for programmers and as such it has some neat "programmer commands", which make editing source code a lot easier. Take for example a block with code, or a function definition: how many times did you have to copy the code between parenthesis from one place to the other?

int foo(int bar, int baz)

You could do '0f(df)' to delete "int bar, int baz" but that won't do if the definition is more complicated than that. 'dib' is a better choice to delete the text.

(ACTION)i{b|B} applies ACTION to a block, for example, pressing diB in

void foo() _ {
	/* Lots of source code */
}

(with the cursor placed at _) will delete lots of source code.

Tuesday 2 June 2009

Testing & mocking: C++

Check the previous post about this presentation.

Where I work we have been working a lot with unit testing and continuous integration. This is a presentation I worked with, about unit testing and mocking tools in C++ (only in spanish, sorry).

Link to the article
Article created with LaTeX

Testing & mocking

Where I work we have been working a lot with unit testing and continuous integration. This is a presentation I worked with, about unit testing and mocking in general (language agnostic but only in spanish, sorry). The examples are in pseudo-ruby, check the next post for a presentation on C++ tools for testing and mocking.

Link to the article
Article created with LaTeX

Saturday 30 May 2009

Quote of the day

If you can't see any error messages it must be because you didn't start it. Or it has already core-dumped.

Thursday 28 May 2009

LaTeX basics

LaTeX basics

Remember last post? I mentioned it's possible to create several type of documents. Even if the structure will, most likely, be different for different applications, there's a common ground which can be used for most LaTeX documents. I'd go as far as saying ALL of them, but in LaTeX it's possible to override everything and anything. Any reasonable package won't do it, so let's see some LaTeX basics you can use for any project.

LaTeX documents

The first thing to understand about LaTeX, it's not WYSIWYG. If you use a plain text editor you won't see any kind of format at all (LyX provides some sort of preview though). This confuses some people who, used to Word-like applications, tend to think in the structure and desing before the contents; LaTeX is different in the way to structure documents, a way which is called What You See Is What You Mean, WYSIWYM, for short.

What does being WYSIWYM means? You just think about the content and structure and it gets formatted for you. Instead of saying you want "Centered, Arial 12px orange font with pink background" just say "this is a title". The format will be there, but not attached to the content - it'll be in a "stylesheet", the document's class (*). Of course, these styles can be changed too.

WYSIWYM has a downside too: you'll have to "compile" the mark-up text into a pdf (or any other format) using pdflatex, for example. It may be a shock to some but it's not difficult, just write "pdf2latex file.tex" and let it work its magic. You can use the makefile I'm attaching to this post too, if you feel comfortable with makefiles (The makefile has a few cool tricks you can use too. I'll explain all of it in another entry).

Seeing some examples

In GNU/Linux you can find lots of examples and templates in /usr/share/doc/texlive-doc/latex/ (no idea where may they be in Windows). Writing this article I found out lots of templates I didn't know about so go and take a look. Go on, I'll wait here. Done? Ok, let's move on.

Preamble

In LaTeX there's a basic structure every document follows:

% Preamble
begin{document}
end{document}

What comes before the begin'ning is the preamble. There you can tell LaTeX:

  • Which packages are you going to use - there are lots of packages, some examples include source code highlighting, including images, absolute positioning of figures and much more. Include them with the usepackage command

  • The style - there are stylesheets you can use, just as you do with HTML, and the preamble is the place to define them. How to do it is package-dependent, Beamer, for example, uses a usetheme tag.
  • Global declarations - You may declare an image which you'll use throughout the entire document, you're company's logo for example
  • The author(s) - OK, this is a global declaration too, but there is certain meta-data which is declared in the preamble that's quite handy and author is one of them.
  • The title - same as before, the title is very important in your document!
  • Lots more - there are package dependent declarations so there's no way to create a comprehensive list, just remember it's a place to put global settings

This post is getting a little bit too large so I'll leave some basic commands for the next one; you should be able to start writing some basic documents anyway.

(*) Yeah, something like content and style separation but only a couple of decades before it was "invented" for the WWW.

Tuesday 26 May 2009

Vim Tip: Partial Search & Replace

So, you have a paragraph, or any kind of text, and need to replace a substring without altering other paragraphs. You could write :set number and then :A,Bs/what to search/what to replace/g, being A and B the start and end of the paragraph, or you could just use visual mode.

Enter line selection mode (Shift + V) and then select a block of text. Without moving the cursor any further type :s/SEARCH/REPLACE and the search string in the selected block will be replaced without altering any other part of the document.

Saturday 23 May 2009

self.uptime = 725328000







Today it's been 725328000 seconds of uptime since I was promoted from Release Candidate to V1.0. Still waiting for security updates though.

Friday 22 May 2009

Vim: Success

The other day I convinced someone Vim is THE true editor.



Success
Disclaimer: I love that image and would have found other excuse to use it

Thursday 21 May 2009

A case for LaTeX

So, after struggling with you word processor to get an acceptable format you decide to hunt the repos (you're using Linux, right?) for a better alternative. We already know why would you choose LyX but why would you choose LaTeX?


Let's begin by listing some of its advantages

  • Wide range of applications - LaTeX is a widely used format, with lots of years, users and fields of application. It's not used only to create papers or just presentations, it can be used in a wide range of applications.
  • There are "packages" prepared for each type of document - related to the previous point, you can find packages to create a CV, a presentation, posters, etc.
  • No need to format every single element - everything comes with a reasonable default format. You may fight a little bit whenever you need to change the default format (though you'll find it less necessary each day) but 90 percent of the time "it just works". With regular word processors it's usually the other way around (it is for me!)
  • Works from a console - OK, this may be an advantage or a disadvantage, according to whom you ask. It sure is an advantage for us, the crazy console people, who don't like to drop the CLI just for a couple of slides.
  • Great templates - no need to work in the design of the documents, that's already taken care of.
  • Plain text format - easy to integrate with any source code management system.
  • Easy to integrate with external media (images, for example) - did you just change that image? No problem, just "recompile" to get it on your document.
  • The best math system

It has some downsides too

  • Steep learning curve
  • Requires some familiarity with the console
  • There's a lot of markup to learn - this can lead to a low signal to noise ratio for some packages like Beamer and the need to RTFM more often than usual.
  • Creating a LaTeX document requires certain syntax - it's not quite like programming, but programmers will be much more comfortable around it
  • Weird error messages - the LaTeX compiler will create an enormous amount of output and error messages may not allways be easy to comprehend.
  • It's a one way ticket - you may be Word - impaired for the rest of your life

Who should use LaTeX?

As previously stated, programmers will be more comfortable around plain LaTeX but that's not the only pre requisite - you should be somewhat familiar with the console in Linux (no idea about LaTeX on Windows) and have some patience to read a couple of manuals. Once you have mastered the basics it's much easier, so don't get discouraged.

If you feel you don't fit the profile perhaps LyX is a better alternative than plain LaTeX; it's very easy to use and quite user friendly. It won't be that great for presentations and other, more "advanced", documents though.

What kind of work can you do with LaTeX?

That's an easy one, check My Articles section for some examples. You can create any kind of document but it's better suited for those in which you care most about the content and don't want to get bogged down with pesky design details.

Editors

Last (for this entry) but not least, what editor can you use to create LaTeX documents? Well, LaTeX is basically plain text so any editor will do. There are some LaTeX-specific editors, I like ViM myself. There'll be a complete post dedicated to LaTeX + Vim, coming soon.

This article will be the first in a series of LaTeX survival guide so stay tuned.

Tuesday 19 May 2009

apt-get install new computer III

Check the other two parts of this series:

I recently updated to Ubuntu 9.04 and had to reinstall my work computer. Since the stuff I use for work (mostly c++ programming) was left out in the previous two posts I'll post it here:

  • Install build tools:
    sudo apt-get install g++ gdb build-essential g++-4.2 omniorb4 omniidl4-python omniidl4 libxerces-c2-dev
  • Can't live without VIM:
    sudo apt-get install vim gvim vim-common vim-doc vim-full vim-gnome vim-gtk
  • Some additional tools:
    sudo apt-get install ddd devhelp doxygen doxygen-gui exuberant-ctags ctags  subversion
  • Install bandwith monitor:
    sudo apt-get install ifstat
  • Don't you hate when you need to read an Office document while working on the console? Me too, try antiword:
    sudo apt-get install antiword

Done, a couple of apt-get's and you are ready to build your c++ projects! (Ok, actually only the first one is needed, the others are nice-to-have programs).

Thursday 14 May 2009

Everything is a file A.K.A. Battery state on Linux

I present to you the latest release from Wheel Reinventions Inc. - Already Invented dept. - a script to check the remaining battery time from Linux console.







echo -n "Hours remaining: " 
&& echo "$(cat /proc/acpi/battery/BAT0/state
     | grep 'remaining capacity'
     | awk '{print $3}') /
   $(cat /proc/acpi/battery/BAT0/state
     | grep 'present rate'
     | awk '{print $3}')"
   | bc -l


Yes, I was bored, so? I'm planning to release a new bogosort implementation after this one, what do you think?

Jokes aside, this nifty script shows how flexible can be the model "everything is a file" which Unix-y systems implement. With a couple of pipes (and an almost magical incantation for those uninitiated in the console cult) you can do lots of stuff with very little work

This concept could be associated with the way polymorfism works in a programming language, but that's an entry for another day.

Tuesday 12 May 2009

LaTeX!

Some time ago I wrote a review about LyX for DPOTD (recommended link) and now I think it's time for an update: what can you do when LyX is not enough?


I'll quote myself; the original article ends (almost) like this:
What LyX isn’t for

Although LyX may be a valuable piece in anyone toolkit it’s worth noticing it isn’t exactly the Swiss army knife of the text editors. If you need to define a very customized layout or format, like slides for a presentation, this is the wrong tool for the job.

After having prepared several presentations with LyX (even my CV!) I'd like to write some more on this last part. Even if I thought that my original comment was mistaken I write once again the same: when you have to create a presentation LyX is not the tool for the job, LaTeX is.

As I explained in that article, LyX is a front-end for LaTeX but at the same time it's only a small part of LaTeX. Doing several presentations in LyX (using Beamer, a package I'll talk about in another post) I noticed that most of my documents where "ERT", evil red text, which is nothing else than plain TeX code: that means, each time more, I was using LaTeX functionality not available from LyX. This is the reason I've decided to write a how-to LaTeX, a small survival guide for those want to start using with the tips and tricks I've learned in this time.

The target for these posts series will be, mainly, programmers or other advanced users, without fear of working a little bit in the console, markup languages and maybe a makefile.

Soon the first part :)

Thursday 7 May 2009

Vim Tip: Visual Mode

There's normal mode, command mode and a third, less known to the beginners, visual mode. What's this mode about?

Using Vim on visual mode can make some rather complex tasks and regex operations go away with a couple of keystrokes and it's as easy as selecting the text you want with the cursor.

Move your cursor over the first part of the text you're trying to select and press Ctrl + V to set Vim to visual mode, then move the cursor to the last part of the text you're trying to select (it works in blocks, not character by character nor line by line... try it, it's easier than it may seem).

What can you do after selecting text this way? Pretty much anything else you'd do with normal text, like cut (x) and paste (p). This is specially useful when working with formatted text (i.e. programming).

Visual mode can also work with lines (use Shift + V instead. Notice the uppercase V) and with other modes; check the manual for more information.

Tuesday 5 May 2009

Fixing keyboard problems in Ubuntu J.J.

I recently metioned in my Ubuntu J.J. review I was experiencing some issues with the keyboard in Opera. Well, the solution is simple, though not easy to find: the culprit was a missing language pack.

While installing the OS I didn't have Internet connection (the Squid server died and left me with no repos to work with after installing) so it didn't download some required language files, thus screwing up non Gnome programs (Opera, in my case).

To fix this problem go to System > Administration > Language Support (1) and a notification should pop up if there are packages missing; install them and then uncheck "Use Input Method Engine ..." (2), then restart the session.

Everything should work fine now (áéíóú :)).

(1) Sistema > Administración > Soporte de Idiomas
(2) Usar motores de método de entrada (IME) para ...

Monday 27 April 2009

Vim Tip: Find Next

In normal mode, move the cursor to any word. How do you search for the next occurrence of that word?

Press the * key to search forwards for the current word, or press # to search backwards.

Using * or # searches for the exact word at the cursor (searching for rain would not find rainbow).

Use g* or g# if you don't want to search for the exact word.

Ubuntu J.J.

I've been using Ubuntu 8.10 for couple of months and soon began to think about switching to Debian or some other - more stable - distro. At work Ubuntu 8.10 seemd too unstable, with frequent crashes and slow. Instead of switching I decided to upgrade to 9.04 soon after its release, something I've always avoided (best to wait for a couple of months, until it gets more stable. Even better if it is an LTS). So far I must say this is the best Ubuntu relase I've seen.

Some highlights after the first couple of days:


  • The install was flawless and quick. In fact I didn't even see it install, just left it running and went to another PC to install 8.04 (I was at FLISOL) and came back to a fully functioning system.

  • Configuring my dual monitor setup at the office required some work but not more than 8.04 and 8.10.

  • I'm still a little uncomfortable with the notification system but it's not worse than before (though I'm not sure if it's better).

  • Still having some problems with SCIM on Opera, not sure who's at fault there.

  • The boot times are FAST. In fact the whole thing seems fast and stable.

  • The graphics handling are improved. Compiz works much better, I can even run it with my dual monitr setup (something I couldn't do with 8.10).


All in all, a great release and a must upgrade for sure. Ubuntu FTW!

Thursday 23 April 2009

FLISOL / Presentación

Con motivo del FLISOL voy a estar dando con Juanman (de GNUTN, el LUG de la UTN) una versión actualizada de la charla GNU/Linux: Introducción y Programación Gráfica (link al post original) que ya dimos en la UTN el año pasado, con muy buenos resultados.

La charla, que a pedido del departamento de marketing ahora se llama GNU/Linux: Guía de supervivencia, va a ser el sábado 25 de abril del 2009 en FM La Tribu, Lambaré 873, de 12:45 a 13:30 (link al programa completo). Dejo un link a la presentación que estaremos utilizando.

Quedan todos invitados!

Monday 20 April 2009

Vim Tip: Using markers

Set a marker if you whish Vim to remember a cursor position Use m* to mark current position (use a to z for position names) and then '* to move to mark * (again, a to z).

This trick can be very useful when editing a large file (or lots of files) in case you need to quickly edit something and then return to the previous spot.

Thursday 16 April 2009

FLISOL

Está abierta la inscripción para participar de FLISOL, Festival Latinoamericano de Instalación de Software Libre.

El Grupo de Usuarios de Software Libre de Capital Federal (CaFeLUG) abrió el registro para participar de FLISOL, el Festival Latinoamericano de Instalación de Software Libre, que este año se realizará el sábado 25 de abril, de 10 a 20 hs. en FM La Tribu, ubicada en Lambare 873, Buenos Aires.

Mas info: http://flisol.net/FLISOL2009/Argentina
Mas info II: http://www.cafelug.org.ar/modules/news/

PD: Voy a estar dando una charla en el FLISOL :D

Friday 27 March 2009

Vim tips: Using macros

Clik-click tap, clik-click tap, clik-click tap. A team mate is performing some kind of repetitive operation with text and it's becoming more and more annoying. Good news, there's a way to keep your mental sanity and help this guy to be more productive: replace him with a sed/awk script teach him how to use Vim macros!

Vim macros can repeat for you a sequence of commands. Press qq to start recording, then q again to stop. Use @q to execute a macro. Let's try it:

This - random garbage
is - random garbage
a - random garbage
sample - random garbage
text - random garbage

So, how would you get rid of the random garbage? Move the cursor to the beggining of the first line, press qq to start recording then f- to move the cursor to the dash and d$ to delete the rest of the line. Now move the cursor to the begging of the next line (0j) and press q to stop recording. Now press 4@q to repeat the macro for times and check the results; you should have something like this:

This
is
a
sample
text

Neat, huh? You can also store any number of macros using a different letter after the q to start recording, for example qn to record and @n to execute. Also, use @@ to execute once again the last executed macro (from any buffer).

There are some more things you can do with macros (like editing before executing one) but the best source for that is the manual.

Monday 23 March 2009

Valgrind - OCI: Suppressions file FTW!

Update: There's a new Valgrind suppressions file @ this link.

Working [1] on a C++ project with Oracle I found that Valgrind reported lots of warnings related to OCI, for which, regardless of being false positives [2] or not, there's little I can do about (other than migrating to MySQL, that is). As the error report kept growing I found that Valgrind will refuse to keep track of new errors after a million or so:

More than 1000000 errors detected. I'm not reporting any more. Final error counts may be inaccurate. Go fix your program!

The solution in this case is a suppresions file for Valgrind. After spending a good deal of time unsuccsesfuly trying to get one I had to do it myself and upload it for the next one to run into this problem:

Link to the file: Valgrind / OCI suppressions.

Saturday 14 March 2009

Vim tips: Moving the cursor to a letter

Let's face it, Vim is the best editor in the world, and from now on there'll be a spot in the homepage with a "Vim Tip of the Week" (check the sidebar).

For the first one a basic tip: Moving to a letter

While in command mode press ' f' and any other letter; the cursor will move to the first occurence of this letter. This can be combined with other commands and a number of repetitions (e.g. ' d2f.', to delete until the second dot).

As a sidenote, I guess there must be a Word Press plugin to display the latest post in a category but I coudn't find it, so I hacked my own: tip-of-the-week

Tip of the Week

I recently added a new plugin to display the latest post within a category; there must be another one out there but I coudn't find it, so I hacked my own. I plan to upload it to WP's plugin repository (some day) so I may as well use this post a man page (?)

  1. Download the plugin from // TODO

  2. Unzip / untar the file in wp-content/plugins

  3. Enable the new plugin

  4. Configure the category to be searched (in my case I used "Vim Tips") in the settings tab

  5. Add the plugin as a widget (or copy&paste the code as needed, it's in the readme)

  6. Post something within the new category, if there's nothing

  7. The excerpt from the post and its title will be displayed in the sidebar (or wherever you configured the new plugin)


Easy to use. Hope you like it.

Friday 6 March 2009

Introducción a GNU Linux

Subo una presentación que usamos para dar una charla de introducción a GNU/Linux en la UTN a principios del 2008 con el grupo GNUTN, orientada al desarrollo. La charla salió muy bien pero todavía no hubo quorum para armar una nueva.

Link a la presentación (PDF)

 

  

También dejo link en la sección de artículos.

Monday 2 March 2009

Valgrind FTW

Una presentación que armé para el trabajo con una introducción a Valgrind, herramienta para profiling y debugging, principalmente para C/C++ en Linux (es posible usarlo con otros lenguajes pero nunca probé): Link al artículo (PDF)

También dejo el link en la sección de artículos.

Saturday 31 January 2009

Changing default shortcuts in gnome

Another of those thing I usually forget: changing default shortcut actions in gnome. In this case, I'm using MOC as my music player (see apt-get install new computer II and while it's great it won't integrate nicely with gnome. Fortunately (as most GNU/Linux applications do) it can be commanded via CLI so it isn't hard to change this.

Now, gnome keyboard shortcuts already have defined actions, so how can we change them to invoke  a custom command? Easy enough:
  1. Open gconf-editor
  2. Go to apps > metacity > keybinding_commands
  3. Set a command from the list. In my case I'm going to set command_1 to "mocp -S", command_2 to "mocp -f" and command_3 to "mocp -r"
  4. Go to apps > metacity > global_keybinding
  5. Set the corresponding run_command_* to the keyboard shortcut. For me that's 0xA2 for run_command_1, 0xE9 for run_command_2 and 0xEA for run_command_3; beware it changes between keyboards.
Troubleshooting tips:
  • If you use gconf-editor for a key binding don't use it again System > Preferences > Key bindings
  • For hex value keybindings (like the ones I used on the example) use uppercase
  • If it's not working and you can't figure out why try with an already working command and a simple keybinding (e.g. gnome-screenshot and ctrl-p) then change each one in turn, see where it breaks. Divide and conquer!!