Recently I had a small requirement for a project I am currently working at in my spare time: centralize a text inside a given rectangular area (if I already know the x, y, w, h dimensions of the rectangle).

The main idea was to use the context.measureText(text).width; method, as it returns the width of the specified text in pixels – exactly what I needed.

Eventually I’ve came up with the following code:

/**
 * @param canvas : The canvas object where to draw . 
 *                 This object is usually obtained by doing:
 *                 canvas = document.getElementById('canvasId');
 * @param x     :  The x position of the rectangle.
 * @param y     :  The y position of the rectangle.
 * @param w     :  The width of the rectangle.
 * @param h     :  The height of the rectangle.
 * @param text  :  The text we are going to centralize
 */
paint_centered = function(canvas, x, y, w, h, text) {
    // The painting properties 
    // Normally I would write this as an input parameter
    var Paint = {
        RECTANGLE_STROKE_STYLE : 'black',
        RECTANGLE_LINE_WIDTH : 1,
        VALUE_FONT : '12px Arial',
        VALUE_FILL_STYLE : 'red'
    }
    
    // Obtains the context 2d of the canvas 
    // It may return null
    var ctx2d = canvas.getContext('2d');
    
    if (ctx2d) {
        // draw rectangular
        ctx2d.strokeStyle=Paint.RECTANGLE_STROKE_STYLE;
        ctx2d.lineWidth = Paint.RECTANGLE_LINE_WIDTH;
        ctx2d.strokeRect(x, y, w, h);
        
        // draw text (this.val)
        ctx2d.textBaseline = "middle";
        ctx2d.font = Paint.VALUE_FONT;
        ctx2d.fillStyle = Paint.VALUE_FILL_STYLE;
        // ctx2d.measureText(text).width/2 
        // returns the text width (given the supplied font) / 2
        textX = x+w/2-ctx2d.measureText(text).width/2;
        textY = y+h/2;
        ctx2d.fillText(text, textX, textY);
    } else {
        // Do something meaningful
    }
}

And I thought it was working perfectly:

window.onload = function() {
    // x y w h
    canvas = document.getElementById('c1');
    paint_centered(canvas, 30, 20, 50, 30, "Test");
    paint_centered(canvas, 30, 70, 80, 40, "Centered text doesn't get wrapped");
}   

Continue reading

Recently I’ve encountered a rather strange behaviour related to Java Web Start.

If, in your .jnlp file you are referencing some signed jars, sometimes the verification fails miserably with the following stacktrace:

com.sun.deploy.net.JARSigningException: Found unsigned entry in resource: 
	at com.sun.javaws.security.SigningInfo.getCommonCodeSignersForJar(Unknown Source)
	at com.sun.javaws.security.SigningInfo.check(Unknown Source)
	at com.sun.javaws.LaunchDownload.checkSignedResourcesHelper(Unknown Source)
	at com.sun.javaws.LaunchDownload.checkSignedResources(Unknown Source)
	at com.sun.javaws.Launcher.prepareResources(Unknown Source)
	at com.sun.javaws.Launcher.prepareAllResources(Unknown Source)
	at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source)
	at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source)
	at com.sun.javaws.Launcher.launch(Unknown Source)
	at com.sun.javaws.Main.launchApp(Unknown Source)
	at com.sun.javaws.Main.continueInSecureThread(Unknown Source)
	at com.sun.javaws.Main$1.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)

If you are 100% sure that your jars are correctly signed, check if your JRE setup have “Keep temporary files on my computer” option enabled. That solved the problem for me.

So if you are on Windows: Control Panel -> Java and then:

Hope it helps.

In this article I am going to show you how to write a simple file monitor. So even though Java 7 comes with a low-level API to watch for file system changes (article here), fow now we will be using using the Commons IO library from the Apache Foundation, mainly the org.apache.commons.io.monitor package.

The first step will be to define the location that we are going to monitor. For this I’ve created a temporary folder of my desktop, and defined a String constant pointing to that newly created location:

    public static final String FOLDER =
            "/home/skywalker/Desktop/simple-test-monitor/watchdir";

The next step will be to define a polling interval: how often we will “look” for file-system changes. The value is expressed in milliseconds:

        final long pollingInterval = 5 * 1000;

Now we will have to build a File object out of the folder we are monitoring:

File folder = new File(FOLDER);

At this point Commons IO comes into picture. In order to make the system monitor actually work we will need at least one instance of the following: FileAlterationObserver, FilterAlterationMonitor and FileAlterationListenerAdaptor .

        FileAlterationObserver observer = new FileAlterationObserver(folder);
        FileAlterationMonitor monitor =
                new FileAlterationMonitor(pollingInterval);
        FileAlterationListener listener = new FileAlterationListenerAdaptor() {
            // Is triggered when a file is created in the monitored folder
            @Override
            public void onFileCreate(File file) {
                try {
                    // "file" is the reference to the newly created file
                    System.out.println("File created: "
                            + file.getCanonicalPath());
                } catch (IOException e) {
                    e.printStackTrace(System.err);
                }
            }

            // Is triggered when a file is deleted from the monitored folder
            @Override
            public void onFileDelete(File file) {
                try {
                    // "file" is the reference to the removed file
                    System.out.println("File removed: "
                            + file.getCanonicalPath());
                    // "file" does not exists anymore in the location
                    System.out.println("File still exists in location: "
                            + file.exists());
                } catch (IOException e) {
                    e.printStackTrace(System.err);
                }
            }
        };

And then we will proceed to add the listener to the observer, add the observer to the monitor, and start the monitor:

        observer.addListener(listener);
        monitor.addObserver(observer);
        monitor.start();

After compiling & running the resulting code, every change I do in the folder that I monitor is being recorded:

File created: /home/skywalker/Desktop/simple-test-monitor/watchdir/1
File created: /home/skywalker/Desktop/simple-test-monitor/watchdir/test
File created: /home/skywalker/Desktop/simple-test-monitor/watchdir/test2
File removed: /home/skywalker/Desktop/simple-test-monitor/watchdir/test
File still exists in location: false

The full sourcecode for the simple file monitor: Continue reading

One of my favorite online resources for programming challenges is called Project Euler . More than certain you’ve heard about it, otherwise what would be the reason to visit this page.

Problem 22 is a simple to medium challenge . In order to solve it you’ll need basic programming knowledge: reading a line from a file, apply some functions on a string, lambda functions and python list comprehension .

Here is the requirment:

Using names.txt (right click and ‘Save Link/Target As…’), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?

And this was my “condensed” solution:

#!/usr/bin/env python
# python version: 2.7.x
# Euler Problem 22
# author: Andrei Ciobanu (www.andreinc.net)

in_file = open('names.txt', 'r')
names = in_file.readline().replace('\"','').split(',')
names.sort()
worth = lambda idx, name: idx * sum([ord(x) - ord('A') + 1 for x in name])
print sum([worth(idx+1, name) for (idx, name) in enumerate(names)])

There’s no need for additional comments, the code is pretty straight-forward.