Category Archives: tutorial

How to Generate Random Colors Programmatically

Creating random colors is actually more difficult than it seems. The randomness itself is easy, but aesthetically pleasing randomness is more difficult. For a little project at work I needed to automatically generate multiple background colors with the following properties:

  • Text over the colored background should be easily readable
  • Colors should be very distinct
  • The number of required colors is not initially known

Naïve Approach

The first and simplest approach is to create random colors by simply using a random number between [0, 256[ for the R, G, B values. I have created a little Ruby script to generate sample HTML code:

# generates HTML code for 26 background colors given R, G, B values.
def gen_html
  ('A'..'Z').each do |c|
    r, g, b = yield
    printf "#{c} ", r, g, b
  end
end

# naive approach: generate purely random colors
gen_html { [rand(256), rand(256), rand(256)] }

The generated output looks like this:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

As you can see this is quite suboptimal. Some letters are hard to read because the background is too dark (B, Q, S), other colors look very similar (F, R).

Using HSV Color Space

HSV_cylinder_smallLet's fix the too dark / too bright problem first. A convenient way to do this is to not use the RGB color space, but HSV (Hue, Saturation, Value). Here you get equally bright and colorful colors by using a fixed value for saturation and value, and just modifying the hue.

Based on the description provided by the wikipedia article on conversion from HSV to RGB I have implemented a converter:

# HSV values in [0..1[
# returns [r, g, b] values from 0 to 255
def hsv_to_rgb(h, s, v)
  h_i = (h*6).to_i
  f = h*6 - h_i
  p = v * (1 - s)
  q = v * (1 - f*s)
  t = v * (1 - (1 - f) * s)
  r, g, b = v, t, p if h_i==0
  r, g, b = q, v, p if h_i==1
  r, g, b = p, v, t if h_i==2
  r, g, b = p, q, v if h_i==3
  r, g, b = t, p, v if h_i==4
  r, g, b = v, p, q if h_i==5
  [(r*256).to_i, (g*256).to_i, (b*256).to_i]
end

Using the generator and fixed values for saturation and value: [ruby][/ruby]# using HSV with variable hue
gen_html { hsv_to_rgb(rand, 0.5, 0.95) }
returns something like this:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Much better. The text is easily readable, and all colors have a similar brightness. Unfortunately, since we have limited us to less colors now, the difference between the randomly generated colors is even less than in the first approach.

Golden Ratio

Using just rand() to choose different values for hue does not lead to a good use of the whole color spectrum, it simply is too random.

distribution-random

Here I have generated 2, 4, 8, 16, and 32 random values and printed them all on a scale. Its easy to see that some values are very tightly packed together, which we do not want.

Lo and behold, some mathematician has discovered the Golden Ratio more than 2400 years ago. It has lots of interesting properties, but for us only one is interesting:

[...] Furthermore, it is a property of the golden ratio, Φ, that each subsequent hash value divides the interval into which it falls according to the golden ratio!
-- Bruno R. Preiss, P.Eng.

Using the golden ratio as the spacing, the generated values look like this:

distribution-goldenratio

Much better! The values are very evenly distributed, regardless how many values are used. Also, the algorithm for this is extremly simple. Just add 1/Φ and modulo 1 for each subsequent color.

# use golden ratio
golden_ratio_conjugate = 0.618033988749895
h = rand # use random start value
gen_html {
  h += golden_ratio_conjugate
  h %= 1
  hsv_to_rgb(h, 0.5, 0.95)
}

The final result:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You can see that the first few values are very different, and the difference decreases as more colors are added (Z and E are already quite similar). Anyways, this is good enough for me.

And because it is so beautiful, here are some more colors ;-)
s=0.99, v=0.99, s=0.25, h=0.8, and s=0.3, v=0.99

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Have fun!
Martin

How To: Download Any Flash Video with flashrip in Ubuntu

Downloading flash videos in Linux was already not too difficult, but thanks to flashrip, it has gotten very easy. Here is a little demo how it works:



Once installed, you basically use one click to get a video preview and then a prompt with the filename to save the file. The script works by looking into the newest flash files in your /tmp folder, and creates a hardlink to the save destination. When the video has fully loaded, you can close the browser window. The temp file will get deleted, and the linked copy will remain.

Installing flashrip

Open a terminal like gnome-terminal or konsole, and run these commands:

wget http://martin.ankerl.com/wp-content/uploads/2009/11/flashrip.sh
chmod 755 flashrip.sh
sudo mv flashrip.sh /usr/local/bin

Now all thats left to do is to create a link in your gnome panel for ease of use: Right click the gnome panel, “Add to panel…”, choose “Custom Application Launcher…”. Choose a proper name, and a command like this:

/usr/local/bin/flashrip.sh /home/manker/Videos

For the command, replace the second parameter with the default location where you want to save the ripped videos (you have to use the full path here!)

I have tested this in Ubuntu, but it should work on any linux where gnome is installed.

Have fun!

Beautiful Font Hinting in Ubuntu 8.10 and 9.04

Even though I have an LCD monitor, I always have the subpixel hinting switched off because it is just painfully ugly to my eyes. Even when hinting is switched to maximum, the fonts are quite blurry (if you don’t believe me, type xmag and take a screenshot of your font. You can see red and blue linese everywhere). My eyes hurt when I see this.

Thanks to Johan Kivinemi I have just found out how to bring back the excellent legacy subpixel hinting engine. This has a much more crisp hinting, and uses subpixels only where it really is an improvement:

Just open these files in your home directory, and copy the content into them:

~/.fonts.conf

[sourcecode lang="xml"]





true


true


hintfull


lcdlegacy


rgb



[/sourcecode]

~/.Xresources

[sourcecode lang="xml"]
Xft.antialias: true
Xft.hinting: true
Xft.hintstyle: hintfull
Xft.lcdfilter: lcdlegacy
Xft.rgba: rgb
[/sourcecode]

This should work in Ubuntu 8.04, 8.10, and 9.04 too, and makes all fonts much more crisp. Of course, your mileage may vary.

UPDATE: Comparison Screenshots

As promised on reddit, I got back from an awesome snowboard trip so I am able to put up extensive comparison screenshots of the two subpixel hinting engines. Move your mouse over the following images to see the differences. Watch especially out for letters like “m” where the spacing between the lines is very small. You might have to wait a bit for the image to load.

I have used all of the most important fonts that I usually use, and just for fun I have added “Dijkstra”, which just looks cool.

Sans Fonts

Mouse to see the same fonts with the legacy hinter.

 

Mono Fonts

Mouse to see the same fonts with the legacy hinter.

 

Zoomed Comparison Screenhots

Here is an excerpt with 400% magnifications. Mouse over the pictures to see the legacy hinter.

Zoomed Sans

 

Zoomed Mono

 

Top 10 Posts of 2008

Everybody loves top 10 lists. It is amazing how much traffic they can generate with the least bit of effort. So, without further ado, here is the list of the top 10 articles on this blog for 2008.

10. Top 10 Eclipse Hotkeys

Ironically, this list starts with another top 10 list, namely Top 10 Eclipse Hotkeys. This article from 2006 has just made it onto this top list. With 3,302 pageviews it seems that these keys are still relevant.
9. Human Compact Themes for Ubuntu 8.10
Number 9 is a modification of the Ubuntu’s default theme that is optimized for small screens. With the recent rise of netbooks this becomes more and more wanted.
8. Logical Volume Manager Cheatsheet
sudo pvcreate /dev/sdg1
sudo vgcreate ext_vg /dev/sdg1
sudo lvcreate -L 450G -n ext ext_vg
sudo mkfs.ext3 -m 0 /dev/ext_vg/ext

A compact little cheat sheet that explains how to easily combine two harddisks into one large volume. I have used this to combine two 500GB disks into one large 1TB filesystem.

7. Comprehensive Linux Terminal Performance Comparison
In this highly controversial article I have compared how long several different terminals (xterm, gnome-terminal, etc.) take when displaying one large textfile. I still believe this is relevant, especially when compiling stuff and text flies by. You don’t want your terminal be the limiting factor for your compile speed! I would perform the test yourself, as this seems to be highly dependent on the graphics card driver.
6. Howto Create MANIFEST.MF Classpath from Ant
[sourcecode lang="xml"]

[/sourcecode]
This HOWTO describes a simple way to create the classpath in a MANIFEST.MF file automatically from the libraries available on the harddisk. I have been using this since 2005, and it has never failed me.
5. Human Compact Gnome Theme (for Ubuntu 8.04)
Another Compact theme has made it on the list, this time for 8.04. I have used this theme for quite a while, even on a large 1680×1050 monitor because it really saves a lot of screen space. For everybody still using Ubuntu 8.04, this is the best choice to use a compact layout while still having the default Human look.
4. Optimized pow() approximation for Java, C / C++, and C#
[sourcecode lang="java"]
public static double pow(final double a, final double b) {
final int x = (int) (Double.doubleToLongBits(a) >> 32);
final int y = (int) (b * (x – 1072632447) + 1072632447);
return Double.longBitsToDouble(((long) y) << 32);
}
[/sourcecode]
Through some funny floating point representation tricks it is possible to create an approximative calculation of the pow() operator, that is a hell of a lot faster than the standard calculation which has to be extremely precise. This might be useful for games, Artificial Intelligence applications, and everywhere else where performance is an issue and not precision.
3. Ajax Dojo Comet Tutorial
One of the most often seen article contains 3 buzzwords at once: Ajax, Dojo, Comet. This page was linked several times, and it is getting quite a bit of attention. The article was written by an intern at my workplace and he allowed me to put it up here.
2. Clearlooks Compact Gnome Theme
Yet another theme! This startet it all. The Clearlooks Compact Theme was the first compact theme I have created. It is just a modification of the original Clearlooks theme, with tighter spacing. This has been linked quite a lot of time and I get a continuous stream of visitors who are in the need for a compact theme.
1. How to get Enough Sleep Despite StumbleUpon With Ubuntu
This post about me struggling with getting enough sleep despite StumbleUpon was by far the most viewed article on the blog, it has received more than 4 times as much visits as the second best. I guess I hit some nerve with it in the large Linux using StumbleUpon crowd. The article is almost a year old, and I still get lots of visitors each and every day. Happy stumbling!

Thank you everybody for coming to this site and posting your thoughts. I appreciate each and every feedback. Happy christmas and happy new year!