Kings of Code

For the first time this year the dutch front-end coders event Kings of Code will kick off may 27th. The company I work for is sponsoring the event, which is awesome!

More awesome then that is the fact that my colleague and buddy, Menno, has announced that he will be giving a talk about the future of front-end development.

Of course I am going to try and capture it all on video, the first time I personally know one of the cool kids on the stage ;)

Good luck menno!

Small updates

It has been some time since I wrote my last post. I wanted to share some updates with my subscribers that might be of interest:

  1. I made 2 git repositories available:
    1. 8 Queens game solution
    2. Color Theme Arjen
  2. My buddy Menno updated his website with some interesting design background.

Of interest to most people would be that color-theme-arjen is slightly updated and should be used instead of the one provided with the color-theme package.

color-theme-arjen

In order to retrieve the content of a git repository you need to have a working git installation. To retrieve color-theme-arjen you would then do: git clone http://credmp.org/git/color-theme-arjen.git

Playing games

I like playing games, from board games to computer games to logic puzzles. However, the type of puzzles that intrigue me most are the logic puzzles that really need a computer to be solved (or perhaps I am too lazy to think them through all the way and a computer is a really useful tool for anyone too lazy to think puzzles through for themselves?).

Luckily for me, one of my colleagues and friends, Menno also likes these types of puzzles and we have been playing the game of ’solve this problem with a computer program’ for some time now. The interesting part of it is that Menno programs in JavaScript while I program in C++, Java or Emacs Lisp.

Some of the puzzles we have tackled up to now include ‘17 square’ and ‘The N Queen‘ problem. With 2 people looking at a problem individually of course yields 2 completely different solutions, especially when the solutions are programmed in 2 totally different languages.

Since these type of puzzles take up a lot of my spare programming time I figured it would make good blog posts and might inspire Menno to post his solutions as well.

The first puzzles I would like to pose is the Eight Queen problem, also known as N Queen, since you can pose it with an arbitrary number really.

The problem states that you have a board of N by N squares on which you want to place N Queens (with the movement restrictions of the chess game, just to be clear) in such a manner that none of the Queens are attacked. This problem has 92 possible solutions of which 12 are unique, the rest are reflections or rotations of the board.

Many approaches will lead to a solution of this problem but I chose to use recursion to solve it and implement it in Java, although I have a partially working Emacs Lisp version as well, but am having some weirdness with the recursion not ending up the way I expected it…

Without further lingering, here is my solution:

package credmp.games;
 
public class EightQueens {
    private int SIZE = 8;
    private int board[];
    private int solutions = 0;
 
    public EightQueens() {
	board = new int[SIZE];
    }
 
    public EightQueens(int size) {
        this.SIZE = size;
	board = new int[SIZE];
    }
 
    public int getSolutions() {
        return solutions;
    }
 
    public void solve(int row) {
        for (int column = 0; column < SIZE; column++) {
            if (is_safe(board[row - 1] = column, row - 1)) {
                if (row < SIZE) solve(row + 1); else print_board();
            }
        }
    }
 
    private boolean is_safe(int column, int row) {
        for (int i = 1; i <= row; i++) {
            int current = board[row - i];
            if (current == column || 
                current == column - i || 
                current == column + i)
                return false;
        }
        return true;
    }
 
    private void print_board() {
        ++solutions;
        for (int i = 0; i < (SIZE * 4 + 1); ++i)
            System.out.print("-");
        System.out.println();
        for (int row = 0; row < SIZE; row++) {
            for (int column = 0; column < SIZE; column++ ) {
                System.out.print(column == board[row] ? "| X " : "|   ");
            }
            System.out.print("|\n");
            for (int i = 0; i < (SIZE * 4 + 1); ++i)
                System.out.print("-");
            System.out.print("\n");
        }
    }
 
    public static void main(String args[]) {
        long start = System.currentTimeMillis();
        EightQueens eq = new EightQueens(8);
        eq.solve(1);
        long end = System.currentTimeMillis();
        System.out.println("Time spent: " + 
                           (end - start) + "ms for solutions:" + 
                           eq.getSolutions() );
    }
}

Anything, anything!

A very usefull ‘feature’ of some languages is the ability to store values of different types in the same variable. Although this is generally a ‘bad idea’, since it makes it impossible to check for assignment errors during compile-time.

However, there are cases where it is very usefull; for instance, lets say that you are writing something that stores a key/value pair of data of which value can be any given type, perhaps you are writing a HTTP server where you want to store some objects between requests.

In the Java world everything inherits from Object, making the HttpSession nothing more then a Map of String keys and Object values. In C++ we do not have such a common parent, so we cannot store multiple types into the same map.

In the Boost libraries there is something called boost::any. The easiest way to illustrate this is by showing an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <boost>
#include <iostream>
#include <string>
 
int main(int argc, char *argv[]) {
    std::string string = "this is a string";
    int integer = 42;
 
    boost::any test = integer;
    std::cout << "An int: " << boost::any_cast<int>(test) << std::endl;
 
    test = string;
    std::cout << "A string: " << boost::any_cast<std::string>(test) 
              << std::endl;
 
    try {
      int no = boost::any_cast<int>(test);
    } catch (boost::bad_any_cast &amp;ex) {
      std::cout << "Cannot cast a string to an int: "
                << ex.what() << std::endl;
    }
}

As you can see, the variable test, which is of type boost::any, can contain any other type and can easily be cast back to the original type (lines 9 and 12). Casting a boost::any to an inconvertible type will cause a boost::bad_any_cast.

Re: Code’s worst enemy

Yesterday, ironically the first day of my vacation, I was reading Steve Yegge’s blogpost about code’s worst enemy.

I often find myself intruiged by Steve’s blogposts, probably one of the few blogs on the Internet actually worth reading even if he is talking about something that does not interest you. When it comes to technical writings I often find myself in agreement with his ramblings, however the last blog post sits a little weird with me.

He starts by saying that the size of a codebase (the Lines Of Code, LOC for short) is possibly one of the worst things that can happen to a code base. Later on he starts ranting about Java in particular (seeing that his pet project, which suffered this ailment, is written in Java).

On one hand I have to agree, code bases which are very large (500K LOC as in his example) tend to be quite nasty to deal with, but I would have to disagree that this is the worst thing that can happen to code.

I have come across a lot of programmers in my own career, ranging from people who just started in this industry to well trained coding athletes who are versed in many different languages. The thing I notice most is that complexity is the key factor in making code bases unmanageable.

Young guns in our industry generally tend to write very complex code while the trained athletes choose to reduce complexity by keeping it simple. I guess this is just a learning process everyone goes through, when you are young you never have had to go back a few months/years after writing the code to do some alterations on it ;).

Having many lines of code to deal with is not a problem, as long as it is not too complex. Over the last few years I have also seen a lot of JavaScript code that is just too complex and thus too hard to handle by most minds, even though it did it in way less lines, so I don’t think rewriting a piece of software in a dynamic language just for the sake of reducing code size is the answer to anything.

The key to manageable code bases is a good coding athlete who has the discipline to keep it simple (and of course unit tested).

Emacs hidden gems: Version Control

With the release of Emacs 22 on June 2nd a new set of version control (vc for short) modes was released as well. The Emacs Tour briefly touches on it, however it fails to point out the geniusness of this feature.

As of 22.1.1 the following version control backends are supported: RCS, CVS, SVN, SCCS, Bzr, Git, Hg, Arch and MCVS. All commands work the same for all backends.

First, lets start with a link to the full documentation of this feature, the Emacs manual pages. These pages contain all the info in this blogpost, as well as a lot more!

Now, lets take a look at the global keybindings. These keybindings are usable whenever you are visiting a version controlled file (Copied over from EmacsWiki).

Key combo function — description
C-x v i vc-register — add a new file to version control
C-x v v vc-next-action — same thing, check in or out, depending on the current state
C-x v ~ vc-version-other-window — look at other revisions
C-x v = vc-diff — diff with other revisions
C-x v u vc-revert-buffer — undo checkout
C-x v c vc-cancel-version — delete the latest revision (often it makes more sense to look at an old revision and check that in again!)
C-x v d vc-directory — show all files which are not up to date
C-x v g vc-annotate — show when each line in a cvs file was added and by whom
C-x v s vc-create-snapshot — tag all the files with a symbolic name
C-x v r vc-retrieve-snapshot — undo checkouts and return to a snapshot with a symbolic name
C-x v l vc-print-log — show log (not in ChangeLog format)
C-x v a vc-update-change-log — update ChangeLog
C-x v m vc-merge
C-x v h vc-insert-headers
M-x vc-resolve-conflicts — pop up an ediff-merge session on a file with conflict markers

There are only a couple of keybindings to remember for day to day usage; C-x v i, C-x v v, C-x v =, C-x v l, C-x v m and C-x v g

Adding files

When you are adding a new file to your project, the C-x v i keybinding takes care of doing it properly for you.

The next action thing

The keybinding C-x v v performs the ‘next action’, this means it will look at the context of the file and will determine the next probable action for the file. When using SVN for instance, after I edit a file, the ‘next action’ will be to do a commit of that file. Some backends checkout their files in read only mode and thus the ‘next action’ is to unlock them and after that the ‘next action’ would be to commit the changes.

It turns out to be a very intuitive way of working with vc and it removes any problem you might have with learning new commands to do the same thing in different backends.

The revision log

The keybinding C-x v l will split the window and will show you a buffer with the revision history of the file. All in all not too exciting, until you read what you can actually do in that buffer. Inside the buffer the keys p and n move you to the ‘previous’ and the ‘next’ entry in the revision log. Pressing d on a revision will show you the Unified Diff of that revision compared to the previous one, so you can see exactly what changed in that revision. The diff feature turns out to be extremely usefull when working in large projects with many people.

Updating a file

If your file is out of sync with your repository just press C-x v m and you can update the file to the latest revision, just press RET. If you pass along a branch number to update to, then all changes from that branch are pulled in.

Seeing changes

To quickly see the changes you have made locally compared to the latest version in the repository, just press C-x v = and a unified diff will pop up.

Who is to blame?

My personal favorite feature of them all, the annotation. Pressing C-x v g will bring up a buffer annotating the current file. By default it will colorize the output depending on age, 18 colors for 20 day steps. So the older the line, the darker the color (default reddish to blue), with steps of 20 days.

There are several keys you can press in this buffer:

Key Description
P Annotate the previous revision, that is to say, the revision before the one currently annotated. A numeric prefix argument is a repeat count, so C-u 10 P would take you back 10 revisions.
N Annotate the next revision–the one after the revision currently annotated. A numeric prefix argument is a repeat count.
J Annotate the revision indicated by the current line.
A Annotate the revision before the one indicated by the current line. This is useful to see the state the file was in before the change on the current line was made.
D Display the diff between the current line’s revision and the previous revision. This is useful to see what the current line’s revision actually changed in the file.
L Show the log of the current line’s revision. This is useful to see the author’s description of the changes in the revision on the current line.
W Annotate the workfile version-the one you are editing. If you used P and N to browse to other revisions, use this key to return to your current version.

Version Control is probably one of the cooler features of the new Emacs (22.1) and it deserves a lot more attention then it is getting at the moment.

eBuddy is #7 fastest growing google search term!

The company I work for eBuddy (blog) has found its way onto the Google Zeitgeist for 2007 as the 7th fastest rising search term for 2007 globally. This is of course massive news, only further confirming the popularity we have among the Internet folks.

Here is the actual image with all the results:
Google Zeitgeist 2007

These results are also referenced by sites like Techcrunch but sadly they only report the fastest rising terms in the US…. (I just thought the Internet was a global thing?)…

Cool as this may be, it does pop the question ‘Has the address bar been obsoleted by the consumer?’. When I look around me, all the non-technical computer users seem to put a portal site as their start page, meaning each time they open a browser, they are confronted with a portal site. In The Netherlands, the site startpagina.nl is wildly popular.

If people don’t find what they are looking for on such a portal site, they just type the site name into the search box on the portal site, which most of the times is Google or Yahoo.

This basically means that companies actually need to invest some time and money in Search Engine Optimization if they want to be the top hit when the user performs their search.

Anyways, is the address bar obsoleted by consumers? I don’t think most of them knew what it was anyways; a big bar with lots of slashes and weird words like www and .com/.nl etc… they just want to go to the site called ‘ebuddy’ and do not want to type anything else I guess :)

Emacs and the hotswap feature of Java debuggers

I write a lot of code in Java and as you might know (if you have read some of my blogposts before) I love to use Emacs for all things related to typing on the keyboard.

When you write large applications in Java, or any other language really, you will eventually need to utilize the debugger. This is simply due to the fact that you will never have 100% code coverage and that it is nearly impossible to fully anticipate how external system integration behaves at runtime.

One of the best debuggers around (in Java land at least) is the one within Netbeans. Besides good integration with the editing process it provides HotSwapping of class files. This means that while you are in a debugging session you can make alterations to code, upload it to the running JVM and execute that piece of code without having to restart the entire debugging session. I wanted to utilize this feature from within Emacs; the following describes how the core feature works.

The ability to redefine classes was actually added to the 1.4.2 JVM and is part of the actual JPDA specification. Of course sun implemented this in their reference implementation which is delivered with each Java SDK; jdb.

Thats cool; so how do we use it? Well, lets create a totally useless application to illustrate the feature. We’ll make a nice Hello World application, consisting of 2 files Main.java and Hello.java:

public class Main {
    public static void main(String args[]) {
	Hello hello = new Hello();
	for (int i = 0; i < 100; ++i) {
	    hello.say("World!");
	}
    }
}
 
public class Hello {
    public void say(String what) {
	System.out.println("Helo, " + what);
    }
}

As you can see, quite simple. The main program will loop 100 times printing “Helo, World!”. Notice the typing error, we will fix this without leaving the debugger really.

So, lets compile the source files by running javac -g Main.java. Both source files will be compile when you use the Java 5 or 6 compiler. Now, for the fun stuff… lets start debugging. We will start the debugger with the Main class and set a breakpoint in the method Hello.say after which we will run the application.

arjenw@machine:~/test$ jdb Main
Initializing jdb ...
> stop in Hello.say
Deferring breakpoint Hello.say.
It will be set after the class is loaded.
> run
run Main
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
> 
VM Started: Set deferred breakpoint Hello.say
 
Breakpoint hit: "thread=main", Hello.say(), line=3 bci=0
3       System.out.println("Helo, " + what)
 
main[1]

As you see, quickly after running the program the breakpoint is hit and jdb prints out where it is. You can clearly see the typo on the screen. Lets fix it!

public class Hello {
    public void say(String what) {
	System.out.println("Hello, " + what);
    }
}

Then; recompile the class and lets redefine it in the debugging session.

main[1] redefine Hello Hello.class
main[1] reenter
>
Step completed: "thread=main", Hello.say(), line=3 bci=0
3       System.out.println("Hello, " + what);

main[1]

After redefining the class, which is done with the appropriately named redefine which takes as arguments the class name (including package name) and the filesystem location of the file, we reenter the current frame to reload the class file and as you see, the typo is fixed in the current debugging session.

There are, of course, several limitations to this feature; you can only create new classes and change method bodies. You can not do things like adding methods or fields and you can neither change the object hierarchy (extends / implements).

Since you can fully run jdb from within Emacs, by running M-x jdb, it only requires you to write some small elisp code snippets to prevent having to type the redefine statements based on the way you utilize Emacs with Java.

Leopard differences Intel vs PPC?

I have been running Leopard since friday, and it is amazing!… there are many reviews to read, so lets not state the obvious over and over.

Today I noticed a difference between the Intel and PowerPC in the ‘ps’ utility. Both machines say that they have the same version of ‘ps’ in /bin/ps:
MD5 (/bin/ps) = bce38c39ee7b501eaf00745b87ed0565

and both systems have the same OS:

Darwin Zaphod.local 9.0.0 Darwin Kernel Version 9.0.0: Tue Oct 9 21:35:55 PDT 2007; root:xnu-1228~1/RELEASE_I386 i386

vs

Darwin cw1m01j 9.0.0 Darwin Kernel Version 9.0.0: Tue Oct 9 21:37:58 PDT 2007; root:xnu-1228~1/RELEASE_PPC Power Macintosh powerpc

so the only difference is the architecture.

So; the difference? on an Intel mac you can no longer do ps -auxww while on the powerpc version it does give the proper output. On the Intel version you can however do ps auxww, which also works on the powerpc version. So, did someone make a booboo here? This will probably break some scripts on the server side I would think.

Makes you wonder if there are more inconsistencies between architectures.

(with thanks to Marco and his old PowerBook)

Debugging

Giles Bowkett wrote an article about how Ruby’s weak debugger support is due to the Test Driven Development (TDD) and Behaviour Drive Development (BDD) nature of the language.

As a result of the post, many people wrote counter posts (Giles names this one the most lucid: Patrick Collison, another one is by James Robertson). I personally find the responses not so bad though they are emotionally loaded…

While I agree that TDD and BDD do reduce the need for a debugger I must say that I really do not agree to the statement that you do not need a debugger, that the debugger actually is a step backward in the development process. Every professional environment that I have been in where testing was a major part of the development process also had a major need for good debugging tools.

Especially when working in a larger groups and with 3rd party dependencies the need for proper tooling only grows. It is a plain fact that you can *not* test for every possible scenario when it comes to the full integration of your software, 3rd party libraries or even 3rd party services.

Besides the ‘bug’ reason the next reason for having good debuggers is that unit tests will not tell you how code interacts. If you join a project which has an existing code base the debugger is your friend in finding your way around the code and seeing how everything interacts.

Although most debuggers are not as usefull as the smalltalk one I must stand with the statement that they are an invaluable asset to any development toolchain and lacking good debugger support is actually a severe lack in any professionals’ toolchain.