Why I want to beat Java with a stick

int x = 100;
Stuff.doStuff(x);

The method doStuff(String) in the type Stuff is not applicable for the arguments (int)

int x = 100;
Stuff.doStuff(x.toString());

Cannot invoke toString() on the primitive type int

int x = 100;
Stuff.doStuff((String)x);

Cannot cast from int to String

int x = 100;
Stuff.doStuff(new Integer(x).toString());   // OMGWTFGRRRBBQ!!!

BUILD SUCCESSFUL

htmlspecialchars() for JavaScript

Creating markup with JavaScript for fun and profit is easy due to innerHTML. However, it would be nice to be able to escape output that is not trusted or known. Most references online point to encodeURI or encodeURIComponent, which will kind-of work; however those functions are intended for URI escaping, which has different rules.

So, here’s a quick solution that works pretty much like the similarly-named PHP function, htmlspecialchars:

function htmlspecialchars(str) {

    if (str === undefined) return "";
 
    return str.replace(/[<>"&]/g, function(match){
        return (match == "<") ? "&lt;" :
               (match == ">") ? "&gt;" :
               (match == '"') ? "&quot;" :
               (match == "&") ? "&amp;" : "";
    });
}

What’s missing? The “quote_style” parameter which allows deciding what will happen with single quotes (‘). If your markup is sane and under control, there should be no need for it — if it isn’t, it’s not hard to change the above function.

Making YUI ButtonGroups behave

I like YUI Buttons. Amongst other niceties they allow you to have reliable cross-browser, cross platform custom-rendered form widgets like checkboxes and radio buttons — while keeping all the accessibility concerns in check. One of the functionalities it has is to create “ButtonGroups”, i.e. a bunch of button controls that behave as a traditional radio-button group. All nice and good, except that it has one obnoxious behaviour: it forces all your radio buttons inside a common container — which might not be what you had in mind. I like my radio buttons where I put them, thank you…

So, quick fix coming up:

var radioGroup = new YAHOO.widget.ButtonGroup({ container: aDivSomewhereItDoesntMatterWhere });
var radioButtons = anArrayOfPlainNormalRadioButtons;

for (var i = 0, len = radioButtons.length; i < len; ++i) {

    var nodeIndex = getNodeIndex(radioButtons[i]),
        parentNode = radioButtons[i].parentNode,
        radioButton = new YAHOO.widget.Button(radioButtons[i]);

    // This will put the button somewhere silly
    radioGroup.addButton(radioButton);

    // Move the button back where it was
    parentNode.insertBefore(radioButton.get("element"), parentNode.childNodes[nodeIndex]);
}

So, it’s more verbose than just using the simple “new YAHOO.widget.ButtonGroup(radioButtonContainer)” syntax that does everything for you — if you are willing to have the radio buttons where YUI put them. Also… what’s that “getNodeIndex()” function?, I hear you ask. Just a simple utility off my toolbox; it gets the index of a node within all the nodes with the same parent:

var nodeIndex = function(element) {
    for (var index = 0, el = element; el = el.previousSibling; ++index);
    return index;
}

Hope that’s helpful…

Getting the category ID in WordPress

There is quite a bit of documentation in the WordPress site about categories, specifically how to retrieve data about them. Unfortunately all the available methods seem to focus on getting category data from a post, but it’s nearly impossible to figure out the category you are looking at when viewing the category page itself (i.e. the special “archive page” that lists all posts in a category).

The function is_category() falls short, since it only indicates whether or not the current page is a category page, but not which one. And get_cat_id(), get_category(), get_the_category(), and the half-dozen other “obviously”-named functions either require that you already know something about the category or provide information about a post.

So, the solution?

if (is_category()) {
   $categoryId = $GLOBALS["cat"];
}

Yes, it’s a global variable…

Making sprites

So you have a website that uses dozens of little images to make the interface more attractive. Maybe there’s a toolbar or menu, where each item or button has its own icon. It looks great, but it’s a pain to load – each image is a small file and the browser frantically struggles to manage the 20 or 30 requests for all the graphical nicety. The interface feels sluggish. Users get bored and leave. Civilisational collapse soon ensues.

Fortunately, you know how to fix the problem with the use of the great technique of CSS Sprites. If you don’t, you should. Click the link and learn about it; I will assume that you know what CSS sprites are from here on… Yes, CSS sprites are great, but they are a pain to create manually. Not only you need to stitch the images together but also there will be lots of CSS rules to position the background image correctly. Automation comes to the rescue in the form of the montage command (part of the fantastic ImageMagick collection of image-manipulation software goodness) and some quick script hacking…

Creating the sprite

This little tip will create a sprite off a directory of image files with identical size (in this case, 16×16 icons), each one named something sensible. The objective is to get one image file and a bunch of CSS rules built automatically. First, ensure that you have ImageMagick. In Ubuntu this command will do the trick:

sudo apt-get install imagemagick

There are also downloadable distributions for Windows and Mac. Once you’re ready, open a command prompt and go to the folder where your images live, and run this command:

montage *.png -alpha on -background "#ffffff00" -tile x1 -geometry 16x16 ../sprites.png

This will create a file, sprites.png, in the parent folder (in Windows, make sure that you type “..sprites.png” as the last parameter – notice the backslash), with all the images tiled side-by-side. If you require the images to be tiled top-to-bottom substitute -tile x1 with -tile 1x. And if your images are a different size than 16×16, specify that in the -geometry parameter. And if your source images are not PNGs, replace “*.png” as appropriate. I recommend that you open the sprites.png file in your editor of choice and perform any conversions or optimisations as you see fit. Don’t forget to apply OptiPNG if you use PNG as your final format (why wouldn’t you?) to get a really small final file size. Your sprites file will look a bit like this (icons off the excellent Silk Icons set):

Example of icons in sprite file

That takes care of the sprite image. Now for the CSS rules.

Auto-generating CSS rules

We’ll be defining a couple of base rules that apply to all elements (note the references to 16px, the size of the icons; adjust as necessary):

.i16:before, .i16 span {
    content: "";
    background-image: url("sprites.png");
    background-repeat: no-repeat;
    padding: 0 0 0 16px;
    margin: 0 0.25em 0 0;
    *zoom: 1;  /* For IE 6 and 7 */
}

.i16block {
    display: block;
    margin: 0 0 0 16px;
    padding: 0 0 0 0.25em;
    position: relative;
    *zoom: 1;  /* For IE 6 and 7 */
}

.i16block span {
    background-image: url("sprites.png");
    background-repeat: no-repeat;
    height: 16px;
    left: -16px;
    min-height: 1em;
    position: absolute;
    top: 0.115em;
    width: 16px;
}

And one more rule per image, which provides the correct background position. The objective is to be able to use classes like this (in this case, to obtain the PDF icon):

<a class="i16 i16pdf" href="example.pdf">PDF link</a>

Or, for links that might span multiple lines and require nice text alignment (or for IE6 support) we need an extra element:

<a class="i16block i16pdf" href="example.pdf"><span></span>PDF link</a>

First, we need to get a list of files in the directory. Each file will produce a rule, and it is important that the contents of the directory haven’t changed since the sprite was created (this is why we placed the sprite in the parent directory). So, drop to the command line and, in Linux, run this:

ls -1 *.png > filelist.txt

Or, in Windows:

dir /b *.png > filelist.txt

Now we only need a quick script to output a bunch of CSS rules. This can be done with your favourite programming language, but here is an example in Python:

rules = ""
f = open('filelist.txt', 'r')
x = 0
for name in f:
    rules = rules + ".i16Mime" + name[0].capitalize() + name[1:] + ":before"
    rules = rules + ", .i16Mime" +  name[0].capitalize() + name[1:]"
    rules = rules + " span {n    background-position: -" + str(x) + "px 50%;n}nn"
    x = x + 16
f.close()
f = open('rules.css', 'w')
f.write(rules)
f.close()

The above code can be saved as a Python script file (say, “myscript.py”) in the same directory as the images, and run from the command-line like so:

python myscript.py

This will generate a new CSS file, “rules.css”, with all the correct rules for all the icons. It should be pretty easy to rewrite the above in your language of choice (PHP, Ruby, Assembler…)   Simple apply to your links the appropriate “i16 i16type” class names and you should be good to go.

Testing for outline CSS support with jQuery

In the good spirit of testing capabilities rather than browser versions, I needed a way to find out whether or not a browser supports setting the values of the “outline” property via CSS. IE6 and 7 don’t support it, everything else seems to. So I just quickly extended the jQuery.support functionality like so:

$.support.outlineCss = function() {
    var $el = $("<div></div>").css("outline", "1px solid black"),
        outlineStyle = $el.appendTo(document.body).css("outline-style");
    $el.remove();
    return outlineStyle == "solid";
}();

Simply test if $.support.outlineCss is true and you’re good to go…

Moving to WordPress

I’ve been planing this for a while, but I’ve finally gone ahead and done it. I ditched my previous site, which was built as an amalgamation of Serendipity (S9Y) and Zend Framework (ZF) and moved to WordPress.

Why? Mostly because the previous setup still required quite a bit of work for me to be happy with it: it looked OK for a visitor, but integrating S9Y into an MVC framework like Zend was somewhat nightmarish, and the admin interface was quite cumbersome even for simple things like adding a post. So I’m setting up a vanilla WordPress installation (apologies about the design; I’m working on it!) which will hopefuly translate into more interesting content and less hassle for me!

I initially set up a ZF site to try and get some more experience with the framework itself, and I am very glad I did. It was a completely overkill application of the technology but I feel I can now use ZF for quite more complex applications: it is very capable and powerful while avoiding the typical “application server” setup that seems so common with larger frameworks. I especially liked the way you can cherry-pick which parts of the framework are of interest, including whether or not the whole MVC stack gets used. For simpler applications something like Cake PHP might still be a faster and simpler way to do things, and I’ll keep to plain-no-frills-PHP for really simple things like prototyping.

As for S9Y, it was a bit of a disappointment. I was looking for a blogging engine that could be plugged into my ZF setup, but since there seem to be none that are happy to do that kind of “blog backend” role only, I settled for something that seemed easy to hack into submission. S9Y does bring its own kitchen sink as well, but it seemed easy to hack. However, two things let it down: convoluted, poorly-documented code, and the templating system.

I won’t say much about the code quality, except that it was at first sight simple but in fact quite messy once you tried to wok out interactions between different parts. The lack of documentation was the really frustrating part, though. So far WordPress seems much better documented and understandable.

The templating system of S9Y is Smarty. There’s nothing wrong with Smarty itself; I guess my problem is with templating systems in general. I know these have their usefulness in some development environments, and of course it is essential to separate as much logic as possible from your markup. However, I don’t think templating systems are a great solution: many times the behaviour of a template is itself complex, and a custom-syntax, crippled language like Smarty is a hindrance.

So there you have the reasons for moving on. Both ZF and S9Y had its fun moments but that setup wasn’t really suitable for this tiny site. Getting rid of the not-invented-here syndrome is also a good thing. In the coming days/weeks I hope to put together a nicer design (I promise I’ll go easy on the orange…) and I now also have fewer excuses to create content more often. So overall I think this was the right decision!