Saturday, January 26, 2008

Why You Should Bother About 2°

So the long term prediction for the climate is that it'll become 2°C hotter worldwide - on average. "Big deal", I hear the sceptics say, "between January and Juli, we get 30°C difference. How much is 2°C is going to add to that? A mere 6%!"

Wrong.

If the climate was a linear system, the 6% would be correct. But the climate is not a car which accelerates smoothly. It's a complex system. Let's look at a really simple complex system, called the Lorentz attractor:

Example of the Lorentz attractor
This is a file from the Wikimedia Commons which I got from the Wikipedia article mentioned above.

The Lorentz attractor is not a perfect example because it's not actually a system that flips rarely (if you follow the curves, you'll see that they go back and forth between the two points all the time instead of staying with one side for some time as our climate does).

Still, it's a good way to visualize what is going on. Imagine that the lower disc with the fat red circle in the middle is the current weather. Temperature is pretty stable around one spot. Now the system gets jolt and starts to move out of the current equilibrum.

Instead of just dropping into the next equilibrum 2°C away, it starts to move in strange patterns. Instead of the temperature simply raising until it's 2°C hotter, it's sometimes much colder, sometimes much hotter. And the change is also not a smooth one. The farther the curve is from the two stable points, the faster it travels. Which means that within a few days, the temperature can drop and raise sharply.

Last week, we had temperatures at 900 in the morning between -1°C and 7°C, a delta of 8°C withing a week. And that's not the lowest and highest overall temperature, it's the temperature measured at the same time in the morning.

You should start to worry about the 2°C because they mean we'll see natural disasters like man has never known before while the climate adjusts to the new average.

Or to put it another way: 2°C means that the earth becomes more hot. It means, if the earth was on a stove, someone is adding more heat or energy to the stovetop. If the earth was a pot with water, that energy would amount to 10.471 zettajoules (one zettajoule is 1 times 10 to the power of 21J) which is roughly the same as the energy the whole earth receives from the sun every day. As a number:

10'471'032'000'000'000'000'000J

The energy released by an average hurricane in one second is a meager 6 terajoule which is a billion times less. Imagine what power a hurricane could get from an athmosphere which has so much more energy to lay waste to our civilization?

Links:

Orders of magnitude (energy)
Thermal energy
Global warming
A Java applet where you can play with the Lorentz attractor

Thursday, January 24, 2008

Safer Java: No Pseudo Constants

Even the pros do it: String "constants" i.e. a string literal (that is something between " quotes) used as a "constant".

That's almost as bad as using integer values as arguments instead of defining symbolic names for them! I mean, the values passed into this API are defined by the standard, aren't they? Sure, you can pass additional feature names as well but that doesn't stop anyone from defining those which the standard defines somewhere! So what that not all of them must be supported!

There are several reasons why you should always define string constants when your API need strings as parts of it's "configuration":

  1. It makes it much more simple to find possible values for your API.
  2. Auto completion in an IDE is possible and helps to avoid typos.
  3. You can add JavaDoc to your strings explaining what they do.
  4. Modern IDEs can find out where your strings are being used in the project.
  5. You can rename the constant and change the string value, even if you have several constants with the same value!
  6. Even if the literals are read from a file, still define a constant for the string and map the raw string to the constant as soon as possible. It makes it so much more simple to track!

Tip: If you still use Java 1.4, define your string constants in an interface (without any other methods). That allows you to use "implements" anywhere where you want to use the constant names without having to prefix them with the name of the interface:

public interface Constants {
    public final static String A = "a";
}

class Demo implements Constants {
    private String value = A;
}

With Java 5, you'll use enum, of course (especially because you can then use these "strings" in switch statements.

Wednesday, January 23, 2008

Laughed Today?

Often, something is seriously funny. The world's best joke, for example, as researched by psychologist Dr Richard Wiseman:

Two hunters are out in the woods when one of them collapses. He doesn't seem to be breathing and his eyes are glazed. The other guy whips out his phone and calls the emergency services. He gasps: "My friend is dead! What can I do?" The operator says: "Calm down, I can help. First, let's make sure he's dead." There is a silence, then a shot is heard. Back on the phone, the guy says: "OK, now what?"

I also like the European favorite a lot:

An Alsatian went to a telegram office, took out a blank form and wrote: "Woof. Woof. Woof. Woof. Woof. Woof. Woof. Woof. Woof." The clerk examined the paper and politely told the dog: "There are only nine words here. You could send another Woof for the same price." "But," the dog replied, "that would make no sense at all."

From this article, after reading about it in the Tages-Anzeiger.

Tuesday, January 22, 2008

Safer Java: Constants First

Here is a simple change in your Java development style that will save you a lot of time: When comparing something against a constant, always put the constant first. Examples:

    if (0 == x)...

    public final static String RUN = "run";
    if (RUN.equals (mode))...

That will look strange at first because we're used to have the constants on the right hand side (from assigns). So what's the advantage of this? There are three:

  1. It will save you a lot of NullPointerException when using equals().
  2. It's more readable in big if/else "switch-alikes", when you compare a variable against a lot of values.
  3. It avoids the accidental assignment as in if (x = 0) (which should have been if (x == 0) ... and if you can't see the difference between the two, you really should always do it this way!) because if (0 = x) generates a compile time error.

The Dreaming Void

The Dreaming Void is not an insult but the latest book of Peter F. Hamilton. It's been sitting in my shelf for quite some time, now, and since I'm sick with the flu, I had a couple of hours between fever attacks to read.

I'm again impressed how Peter can flesh out characters with a few sentences. As an aspiring writer, it's always both intimidating and relieving to read a good book. On one hand, it shows how much more one has to travel, on the other hand, it shows it's an effort well spent.

All in all, a good story, maybe a bit confusing because the author skips back and forth between so many characters, storylines and timelines which makes it hard to track what happened in which order and why something is important. It shows Peters talent as a writer how he can manage all these details without ever stumbling. He's also probably the only SciFi author who can get away at writing a couple of pages how to renovate a flat including buying a new kitchen and a bathroom for it. :)

There is one sore spot, though. In one scene, Aaron breaks into a high-security memory-cell vault and gets pummeled by two heavily armed guards. In the process, a lot of damage is dealt to the environment, especially the racks with the memory cells and their valuable content.

Peter, please. No one in their right mind allows heavy arms near valuable, delicate stuff. Next time, put these guards in the corridor before the vault, so they can hammer away at any intruder with a fat, reliable forcefield between them and the cells with takes the excess damage. That would make it a bit more realistic.

Other than that, a great book. Recommendation: Buy.

Friday, January 18, 2008

Portable UI

For many years, I've been looking for a way to write portable applications with a nice, responsive user interface. Many have tried and many have failed:

  • Python with tcl/tk - A nice experience from the developer side. The Python wrapper around the tk widget set shows how you can get compact, yet easy understandable code and write UI's in short time. If it just weren't that ugly ...
  • Java with Swing - Swing borrows a lot from X11, the grandfather of all graphical desktops. I have yet to see anyone managing to impress the world with their grandfather ...
  • Java with SWT - Now, here comes a contender. Java is pretty widely available (not quite as many platforms as Python, but still), it is pretty fast, okay, the download is a bit on the big side ... but no DLL hell, easy to setup (especially if you don't provide an installer and just push a ZIP out). SWT is nice, fast ... and bare bones. MFC? Well, they have JFace and in a few years, there might even be a text editing component that can do word wrap and still show line numbers. Oh, and SWT is available on even fewer platforms than Java. Palm, anyone?
  • HTML - Web based apps are all the hype. If you want to use your app on the run, it gets tricky. I don't know about the US, but here in Europe, going online with you mobile will ruin you. Literally. Also, I've had my struggles with HTML and CSS and I can do without. Either and both.

I've tried a few more but in the end, things never felt right. Until recently. I'm a big fan of treeline. Treeline uses Python and PyQt which wraps Qt (say: "cute"). Qt is a mature framework, currently at version 4.3.3, with 4.4 is around the corner. It doesn't have all the nifty stuff I can imagine (like an RTF editor; QTextEdit can only do a (big) fraction of that) but it gets closer to what I want than anything else.

In the past two weeks, I wrote a little clone of yWriter4. The little baby has currently about 8000 loc and about half of the functionality I want to give it (especially the text editing is still leaving a lot to be desired). Except for two bugs (signal names and GC issues), it's been a real pleasure to use. I managed to implement almost every feature within a few minutes or few hours (the storyboard took 6 hours, the scene chart view took two), also thanks to the good defaults of the framework. Here is an impression of v0.2:

So when you're considering to write a small to medium sized application which needs to run on Windows, Linux and MacOS, give PyQt a try.

Monday, January 14, 2008

Sorting Number Table Columns in PyQt4

Here is a simple trick to sort number columns in the QTableWidget of Qt4 and PyQt4: Format the number as a right aligned string:

for i range(12):
    item = QTableWidgetItem(u'%7d' random.randint(1, 10000))
    item.setTextAlignment(Qt.AlignRight)
    table.setItem (i, 1, item)

Testing JavaScript

If you're test mad like me, then the <script> tag in HTML was probably one sore spot for you as it was for me: How to test the damn thing? Well, now, there is a way: John Resig wrote a small script which you can source into Rhino 1.6R6 (or later; 1.6R5 won't work, though. You'll get "missing : after property id"). Afterwards, you'll have window, document, nagivation, even XMLHttpRequest!

Yes, you can actually test AJAX within unit tests, now! TDD fans, start your engines!

Unfortunately, it doesn't emulate browser bugs, yet ;-> But you can fix that. I, for example, had problems to get the code load HTML 3.2 files. Especially this code made the SAX parser vomit:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 //EN">

The fix here is to download some XHTML DTD (like XHTML 1 Strict), put it somewhere (along with the three entity files xhtml-lat1.ent, xhtml-special.ent and xhtml-symbol.ent) and change the DTD to point to the new file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 //EN" "html/xhtml1-strict.dtd">

In my case, I've put the files in a subdirectory "html/" of the directory I start the tests from. (Hm ... shouldn't this path be raltive to the HTML file?? Well, it isn't.)

Also, the env.js supplied doesn't support forms. Here is my which fix:

function collectForms() {
    document.forms = document.body.getElementsByTagName('FORM');
    
    for (var i=0; i<document.forms.length; i++) {
        var f = document.forms[i];
        f.name = f.attributes['name'];
        //print('Form '+f.name);
        f.elements = f.getElementsByTagName('INPUT');
        
        for(var j=0; j<f.elements.length; j++) {
            var e = f.elements[j];
            var attr = e.attributes;
            
            forEach(attr, print);
            e.type = attr['type'];
            e.name = attr['name'];
            e.className = attr['class'];
            
            _elements[ f.name + '.' + e.name ] = e;
        }
        //print(f.elements);
    }
}

Note: I also had to remove the calls to toLowerCase() for the tag names (*not* the attributes!), too. Otherwise, document.body would return UNDEFINED for me. But that's because I'm stuck with old HTML; If you can convert all tag and attribute names to lowercase, then you're safe.

Lastly, the loading of the document is asynchronous. To fix this, we need a class to synchronize the Java and the JavaScript thread. That one is simple:

package test.js;

import org.mozilla.javascript.ScriptableObject;

import test.ShouldNotHappenException;

public class JSJSynchronize extends ScriptableObject
{
    public Object data;
    public Object lock = new Object ();
    
    @Override
    public String getClassName () {
        return "JSJSynchronize";
    }
    
    public Object jsGet_data() {
        synchronized (lock) {
            try {
                lock.wait ();
            }
            catch (InterruptedException e) {
                throw new ShouldNotHappenException(e);
            }
            
            return data;
        }
    }

    public void jsSet_data(Object data) {
        synchronized (lock) {
            this.data = data;
            lock.notify ();
        }
    }
    
    public Object getData() {
        synchronized (lock) {
            try {
                lock.wait ();
            }
            catch (InterruptedException e) {
                throw new ShouldNotHappenException(e);
            }
            
            return data;
        }
    }

    public void setData(Object data) {
        synchronized (lock) {
            this.data = data;
            lock.notify ();
        }
    }
    
}

ShouldNotHappenException is derived from RuntimeException. After registering that with

        jsjSynchronize = (JSJSynchronize)cx.newObject (scope, "JSJSynchronize");
        scope.put("jsjSynchronize", scope, jsjSynchronize);

in the test, I can use the new jsjSynchronize global variable in JavaScript in wondow.onload:

    public void testAddTextFilters() throws Exception
    {
        setupContext ();
        addScript(cx, scope, new File ("html/env.js"));
        cx.evaluateString(scope, 
                "window.location = 'file:///d:/devm2/globus/abs/webapp/html/testAbsSkuOutput.html';\n" +
      "window.onload = function(){\n" +
      "    jsjSynchronize.data = window;\n" +
      "};\n" +
      "", "<"+getName ()+">", 1, null);
        
        ScriptableObject window = (ScriptableObject)jsjSynchronize.getData();
        System.out.println ("window="+window);

At this point, the document has been loaded and you can access all the fields, elements, etc. Good luck!

Tuesday, January 01, 2008

Silence the HD

Some follow up to yesterday's post. Using a Sharkoon HDD Vibe-Fixer in a case which doesn't require screws to install drives doesn't work; the Vibe-Fixer consists of several independent parts which are only loosely coupled. So when the drive starts to work, you'll hear a clatter between the U shaped Vibe-Fixer and the slot in the case.

One solution would be to force some felt between the parts and the slot but it's hard to get there and I'm not sure if the results are worthwhile. So I've bought a ichbinleise® Box HDD 10. This is basically a set of four aluminium pieces held together by four screws which keep the HD between two sheets of damping foam. The whole thing is then glued to the case with a thick foam piece to isolate the vibrations.

I had to use hdparm -M 128 /dev/sda to switch the drive into silent mode, though, to reduce the noise to a low murmur.

The main disadvantage of this setup is heat: I've applied some thermo transfer goo following a tip of the nice guys at ichbinleise.ch. Also, the HD case is in the flow of the front fan. Still the drive reports temperatures between 60°C and 80°C according to smartctl. I hope this is a bug but I'll keep an eye on it.

Another disadvantage is that I can't easily remove the 3.5" drive cage; it's riveted into the case and I'd have to use a drill to get it out. So I glued it in front of the mainboard which means it blocks the lowest two PCI slots. Since I don't need them, it's not a big deal but still ...