# September 2007 Archives

To display a number x in 2 digits with padding zero in the front, here's the snippet to do so:

```String("0" + x).slice(-2);
```

To display 5 digits with padding zeros, it'll be:

```String("0000" + x).slice(-5);
```

The number of zero can be parameterized, of course:

```var padding_zero = function(x, n) {
var zeros = repeat("0", n);
return String(zeros + x).slice(-1 * n)
}
```

The function repeat is the string repeater defined in here.

But these definitions doesn't check the original number if it's longer then n digits. Calling padding_zero(357, 2) will give you 57. Neither does it check if its parameters are numbers or not. (Easy and may not be a big issue depends on what you want.)

And of course, you can pad something other than zero. For example, you can pad up to 5 number of before . They are just two different img strings anyway:

```// pad up to n Ys before X.
var pad = function(x, n, y) {
var zeros = repeat(y, n);
return String(zeros + x).slice(-1 * n);
}
```

So the code to generate a line of 5 rating stars may just looks like:

```pad("111", 5, "0).replace(/1/g, star_img).replace(/0/g, empty_star_img);
```

The idea here is to generate something like "11100" first, then replace them with img tags.

All these functions assumes x,y variables are only one character to work properly because I use slice() function on String classes. To make it more general, should probably use Array.

Labels: , , ,

## String repeat in JavaScript, and as a jQuery extension.

Repeating a string multiple times isn't as easy as in Perl that you say \$str x 3. str * 3 simply gives you a NaN. So I wrote this textbook-code-example-like repeat() funciton, that takes a String and a Number, returns a new String.
```function repeat(str, i) {
if (isNaN(i) || i <= 0) return "";
return str + repeat(str, i-1);
}
```

Putting it down as a jquery extension, it becomes this snippet:

```(function(\$){
\$.extend({
repeat: function(str, i) {
if (isNaN(i) || i == 0) return "";
return str + \$.repeat(str, i-1);
}
})
})(jQuery);
```

It's used like this:

```var rating = 3;
var star = "<img src='star.gif'>";

// Show some number of stars based on rating.
\$("#rating").html( \$.repeat(star, rating) )
```

Labels: ,

Labels:

## A simple Perlbal load balancer config for mongrel cluster

I use these two configuration for my little Rails app. 5 mongrel instances, balanced and externally served with Perlbal. It can still be refined to let Perlbal serves the public/ folder. But this is good enough for me at this point:

mongrel_cluster.yml:

```---
log_file: log/mongrel.log
port: 4000
pid_file: tmp/pids/mongrel.pid
servers: 5
```

```CREATE POOL my_servers

CREATE SERVICE balancer
SET listen          = 0.0.0.0:3000
SET role            = reverse_proxy
SET pool            = my_servers
SET persist_client  = off
SET persist_backend = off
SET verify_backend  = off

ENABLE balancer
```

Labels: , , , ,

Labels: , , , ,