Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Sunday, 5 September 2010

Sound Issue in Ubuntu 10.10 Beta

This morning when logging in to my newly-upgraded-to-Ubuntu-10.10 laptop, sound was not working. It appears that the solution was very simple: my user was not authorised to use audio devices. I don't know why it was disabled as it had always worked fine before but it's very easy to solve so if you have the same problem check that first. To resolve it, go to System → Administration → Users and Groups, select your user, click on the Advanced Settings button, enter your password, click the User Privileges tab and make sure the Use audio devices box is checked. While you're at it, do the same for the other users on your system.

User Settings dialogue

If that doesn't work, there is a handy wiki page on debugging sound problems.

Saturday, 29 May 2010

Backup and Restore a Subversion Repository

Sometimes, you just have to do serious maintenance to a server, like install a new instance of your operating system from scratch with a new partition layout. If this server happens to be your Subversion server, you need to backup your repository and restore it once you're done with the maintenance. Or maybe you just want to move your repository from one server to another. Here's how to do it. The commands below need to be performed on the SVN server by a user who has write access to the repository (in theory any SVN admnistrator).

First, here's how back up the repository to a compressed file:

$ svnadmin dump /path/to/repo | gzip > backup.gz

And how to restore it:

$ gunzip -c backup.gz | svnadmin load /path/to/repo

Those commands are meant for UNIX or Linux so you will have to adapt them if you are running Windows. It shouldn't be too difficult to do so, especially if you are using Cygwin.

Friday, 5 February 2010

Raising elephants on a ThinkPad T42 and an EeePC 701

A magic key

If you look at your computer keyboard, you probably have a key labelled SysRq somewhere, either on its own or as a secondary function of another key such as PrtSc. You probably never use it but if you run Linux, it's a magic key that enables you to perform low level commands even when the computer is completely stuck. A particularly useful combination of such commands uses the mnemonic Raising Elephants Is So Utterly Boring.

Finding SysRq

That's the theory. In practice, it can be difficult to find out what exact key combination triggers SysRq on your particular computer and whether you need to press SysRq and the command key at the same time or whether you can press SysRq first, release and then press the command key. To find out, switch to a text virtual terminal, by pressing Ctrl+Alt+F1. You will then be presented with a full screen black console with a login prompt. Don't worry, you can switch back to your normal screen by pressing Ctrl+Alt+F7 at any time. Log in with your user name and password. For this to work, we first need to check that support for SysRq is compiled in your kernel. To do this, enter the following command:

$ cat /boot/config-`uname -r` | grep CONFIG_MAGIC_SYSRQ
CONFIG_MAGIC_SYSRQ=y

If the result is as shown above, SysRq is compiled in your kernel. Next, we need to make sure it's enabled:

$ cat /proc/sys/kernel/sysrq
1

If it is enabled, you should get 1 as an answer. If you get 0, it's not enabled, if you get anything else, it's partially enabled. The full list of values can be found in the sysrq.c documentation. If it all enabled, it should be possible to try it out by sending a command directly to the SysRq trigger:

$ sudo su -
$ echo h > /proc/sysrq-trigger

You need to be root to do this, hence the sudo su - to start with. When you do this, you should see the SysRq held text printed out to the console. After that, revert to your own user immediately to avoid any risk of doing something bad to your computer: root is very powerful and it's therefore very easy to do something bad by accident. So type this command to revert to your own user:

$ exit

Now it's a case of trying all possible key combination with the h command to find out what your SysRq key is. If you have a full SysRq key, typing Alt+SysRq+h should display the same help message as above. If that's the case, you're done. Otherwise try any number of combinations of the keys Shift, Ctrl, Alt, AltGr or Fn with one of the keys SysRq, PrtSc, Insert, Delete, ScrLk and key h until you find what combination produces the help message. Once you've found it, log out by typing exit and revert to your standard virtual terminal by pressing Ctrl+Alt+F7

SysRq on a ThinkPad T42 and an EeePC 701

On my IBM ThinkPad T42, the SysRq key combination is AltGr+PrtSc so to get the help text, I would do AltGr+PrtSc+h. On my EeePC 701, the combination is Fn+Alt+Del, which means I have to press four keys at the same time to get the SysRq help text: Fn+Alt+Del+h! Luckily it's a small keyboard. On both machines, I have to press all 3 or 4 keys at the same time.

Tuesday, 31 March 2009

Custom Page Numbering with LaTeX

I'm currently doing a home course on short story writing. Or should I say I attempt to as I haven't been returning my assignments very promptly. Anyway, one of the requirements is that each assignment is formatted in such a way that the footer of each page contains the page number, starting at 1 on the first page, and the letters mf for More Follows on every page except the last one. In order to do this, I need to be able to set a specific footer for the last page and one for all other pages. I tried to do that with OpenOffice.org to start with but there was no way to identify whether you were on the last page using a macro with version 2.4, which is what I was using when I started. As you would expect, it is surprisingly easy to do with LaTeX, provided you import the correct packages.

  • In order to specify a custom footer (or header), I will need the fancyhdr package;
  • I will also need to be able to use some if/then/else logic to output something different whether I am on the last page or not, this is provided by the ifthen package;
  • Finally, I will need to know whether I am on the last page, which is provided by the aptly named lastpage package.

Putting all this together, the document's code needs to do the following:

  • Import all relevant packages;
  • Set the page style to fancy;
  • Set all headers and footers to blank;
  • Set the header and footer lines to 0 points (optional, you may like the defaults);
  • Set the right hand side footer so that it implements this logic:
    • If the page is the last one, print nothing;
    • Otherwise, print mf.
  • Set the left hand side footer to the current page's number.

And here is the resulting code:

\documentclass[a4paper,12pt]{article}
\usepackage{lastpage}
\usepackage{ifthen}
\usepackage{fancyhdr}

\pagestyle{fancy}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\fancyfoot[R]{\ifthenelse{\thepage=\pageref{LastPage}}{}{mf}}
\fancyfoot[L]{Page~\thepage}

\begin{document}

The content of the document goes here.

\end{document}

Sunday, 15 February 2009

Using the LaTeX letter document class

LaTeX offers a variety of built-in document classes. One of them is letter, which is designed for writing official letters, such as the one I just did to the (inept) agency that manages my flat. However, that standard document class is not very well liked: it's the ugly little duckling of the LaTeX document classes. But when you just have to get things done, better the devil you know than the one you don't. So here's a quick summary of easy tweaks I applied to my letter to bend the default document class to my needs.

Structure

The letter document class requires a specific structure. It is designed so that you can write several letters to several recipients while using the same return address. The basic structure of a letter document looks something like this:

Basic structure of a letter document
\documentclass{letter}

\address{The return address}
\signature{Your signature}

\begin{document}
\begin{letter}{The recipient's address}

\opening{The opening, such as: Dear Sir,}

The body of the letter

\closing{The closing, such as: Best regards,}

\end{letter}
\end{document}

The letter environment that is enclosed in the document environment looks superfluous at first. The idea is that you can have several letter environments when you want to produce more than a single letter: this can be very useful for mailings.

Top space

The document class introduces a lot of white space at the top. This is good for a multi-page letter but looks really awkward on a single page letter. So, I did what the TeX FAQ suggests and added the following in the preamble, just after the \documentclass command:

Preamble to remove the initial top space

\makeatletter
\let\@texttop\relax
\makeatother

\begin{document}

Adding a reference

As my managing agent specified a reference in the letter they sent me, I wanted to include that reference in my letter, just after their address but with some small vertical space in between. There is no obvious way to do that so I just added it to the end of the recipient's address with a space of length \parskip:

Adding a reference
\begin{letter}{The recipient's address\\[\parskip]
Your ref: The reference}

Adding some vertical space before the closing sentence

The closing sentence is printed very close to the last paragraph in the letter. I wanted a bit more space so added the following just before the \closing command:

Adding space before closing
\vspace{3\parskip}
\closing{The closing, such as: Best regards,}

Adding space between the closing and the signature

When writing a letter, I like leaving enough space between the closing sentence and the printed signature so that I can add a hand written signature once it's printed. The standard space is too small for this. However, considering both lines are printed by the \closing command, there is no obvious way to include any space in between. However, looking at the letter.cls code, it appears that the standard template adds 6 times the \medskipamount length in between the two lines so the simple way to change that space is to change the relevant length just before the \closing command:

Adding between the closing and signature
\vspace{3\parskip}
\addtolength{\medskipamount}{2\medskipamount}
\closing{The closing, such as: Best regards,}

This will multiply the \medskipamount length by 3 and as result multiply the space between closing and signature by 3 as well. This works great for a single letter but will not have the intended result when you have multiple letters in the same document. The way to avoid this is to save the original length and restore it afterwards:

Adding between the closing and signature
\vspace{3\parskip}
\setlength{\oldmedskipamount}{\medskipamount}
\addtolength{\medskipamount}{2\medskipamount}
\closing{The closing, such as: Best regards,}
\setlength{\medskipamount}{\oldmedskipamount}

With those few tricks, I got a letter that was close enough to what I wanted. I could probably have spent a lot more time tweaking it or trying alternative document classes but this particular job didn't warrant me spending too much time on it.

Tuesday, 13 January 2009

Tuning a Wi-Fi Router with Linux

Nowadays, with Wi-Fi broadband routers becoming the de-facto standard in the home, comes a new problem for people who live in cities: interferences between neighbouring wireless networks. This can lead to slow connections or even dropped connections. A few years ago it was not a problem, few people had Wi-Fi routers at home and if you had one your router would work great out of the box. Nowadays, everybody's got a Wi-Fi router at home, whether it be a traditional router or a phone that masquerades as one. Wi-Fi was designed to avoid interferences by being able to work on a number of frequencies and every single router allows you to choose what frequency to use by selecting a channel. In the UK, you will typically have the choice of a channel value between 1 and 13. Just go to the wireless settings area of your router administration page and you should be able to change the channel, as shown on this example from a Netgear router:

Netgear wireless settings screen, set to Channel 4

Netgear wireless settings screenshot

That's simple: change the value, ensure it's applied and, depending on the manufacturer, reboot the router. But what is a good value that will ensure a good connection? Well, it depends on your environment. As you want to avoid interferences, this value should be as far as possible from other routers in the range of your equipment. But how do you tell what channel other routers in your area use? The Linux wireless tools come to the rescue, and in particular the one called iwlist. If you have a Wi-Fi laptop running Linux, it will have this utility installed as standard. The basic command we want is:

$ iwlist [interface] scan[ning]

To do a full scan, we need to run it as root so we'll prepend sudo to it. It is not necessary to specify a network interface but you might as well do so to avoid scanning non-wireless adapters. On my laptop, the wireless interface is eth1 so here is what I obtain by running iwlist against it:

$ sudo iwlist eth1 scan
eth1      Scan completed :
          Cell 01 - Address: 02:1D:68:4B:6D:F6
                    ESSID:"BTOpenzone"
                    Protocol:IEEE 802.11bg
                    Mode:Master
                    Frequency:2.412 GHz (Channel 1)
                    Encryption key:off
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 6 Mb/s; 9 Mb/s
                              11 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
                              48 Mb/s; 54 Mb/s
                    Quality=27/100  Signal level=-83 dBm  
                    Extra: Last beacon: 240ms ago
          Cell 02 - Address: 00:1D:68:4B:6D:F5
                    ESSID:"BTHomeHub-954D"
                    Protocol:IEEE 802.11bg
                    Mode:Master
                    Frequency:2.412 GHz (Channel 1)
                    Encryption key:on
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 6 Mb/s; 9 Mb/s
                              11 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
                              48 Mb/s; 54 Mb/s
                    Quality=29/100  Signal level=-82 dBm  
                    Extra: Last beacon: 248ms ago

... and so on

Each Cell section provides the details of a wireless hub in range. For each of them, the line we are interested in is the one that start with the word Frequency. So, if we use grep to filter the data, we get:

$ sudo iwlist eth1 scan | grep Frequency
Frequency:2.412 GHz (Channel 1)
Frequency:2.412 GHz (Channel 1)
Frequency:2.412 GHz (Channel 1)
Frequency:2.427 GHz (Channel 4)
Frequency:2.442 GHz (Channel 7)
Frequency:2.442 GHz (Channel 7)
Frequency:2.462 GHz (Channel 11)
Frequency:2.442 GHz (Channel 7)

This shows that I am in range of 8 wireless hubs. The one I am using is the fourth one, set to use channel 4. But that's because I changed it yesterday. It used to be configured with its default setting, using channel 11, which was clashing with the one before last. In fact, running the command at different times, it appears that all routers in my area use channels 1, 7 or 11. With a possible set of channels between 1 and 13, there are 5 unused channels between 1 and 7, 3 between 7 and 11 and 2 above 11. So the best choice is halfway between 1 and 7: channel 4. And since I reconfigured the router to use that channel, speed has improved significantly and dropped connections have been a thing of the past.

Now, why router manufacturers don't design their products to be able to scan neighbouring wireless networks at start-up and choose a frequency that doesn't clash with other hubs, I don't know. By any means, leave the ability to power users to explicitly specify the channel but a little bit of automation would go a long way in making Wi-Fi easier for the average home user.

Update

After all this, I had to change the router's channel again earlier, as more access points were switched on during the evening. At one point, a full scan showed a grand total of 24 wireless networks! So I changed my router to channel 13 and it all seems fine so far. Methinks I'll have to do something about improving the range of that router. While I was at it, I also upgraded the firmware so we'll see if it makes a difference.

Saturday, 26 July 2008

Parameterised Testing with JUnit 4

Anybody who's ever written software more complex than the typical Hello, World! examples knows that software without bugs doesn't exist and that it needs to be tested. Most people who have ever done testing on programs written in the Java language have come across JUnit. Now, JUnit is a very small package. In fact, when you look at the number of classes provided you'd think it doesn't do anything useful. But don't be fooled, in this small amount of code lies extreme power and flexibility. Even more so since JUnit 4 that makes full use of the power of annotations, introduced in Java 5.0.

Typically, when using JUnit 3, you'd create one test case class per class you want to test and one test method per method you want to test. The problem is, as soon as your method takes a parameter, it is likely that you will want to test your method with a variety of values for this parameter: normal and invalid values as well as border conditions. In the old days, you had two ways to do it:

  • Test the same method with several different parameters in a single test: it works but all your tests with different values are bundled into a single test when it comes to output. And if you have 100 error conditions and it fails on the second one, you don't know whether any of the remaining 98 work.
  • Create one method per parameter variation you want to try: you can then report each test condition individually but it can be difficult to tell when they are related to the same method. And it requires a stupid amount of extra code.

There must be a better way to do this. And JUnit 4 has the answer: parameterised tests. So how does it work? Let's take a real life example. I've been playing with the new script package in Java 6.0 to create a basic Forth language interpreter in Java. So far, I can do the four basic arithmetic operations and print stuff off the stack. That sort of code is the ideal candidate for parameterised testing as I'd want to test my eval method with a number of different scripts without having to write one single method for each test script. So, the JUnit test class I started from looked something like this:

<some more imports go here...>

import static org.junit.Assert.*;
import org.junit.Test;

public class JForthScriptEngineTest {

 @Before
 public void setUp() throws Exception {
  jforthEngineFactory = new JForthScriptEngineFactory();
  jforthEngine = jforthEngineFactory.getScriptEngine();
 }

 @After
 public void tearDown() throws Exception {
  jforthEngine = null;
  jforthEngineFactory = null;
 }

 @Test
 public void testEvalReaderScriptContext() throws ScriptException {
  // context
  String script = "2 3 + .";
  String expectedResult = "5 ";
  ScriptContext context = new SimpleScriptContext();
  StringWriter out = new StringWriter();
  context.setWriter(out);
  // script
  StringReader in = new StringReader(script);
  Object r = jforthEngine.eval(in, context);
  assertEquals("Unexpected script output", expectedResult,
   out.toString());
 }

 @Test
 public void testGetFactory() {
  ScriptEngine engine = new JForthScriptEngine();
  ScriptEngineFactory factory = engine.getFactory();
  assertEquals(JForthScriptEngineFactory.class, factory.getClass());
 }

 private ScriptEngine jforthEngine;
 
 private ScriptEngineFactory jforthEngineFactory;
}

My testEvalReaderScriptContext method was exactly the sort of things that should be parameterised. The solution was to extract that method from this test class and create a new parameterised test class:

<some more imports go here...>

import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class ParameterizedJForthScriptEngineTest {
 @Parameters
 public static Collection<String[]> data() {
  return Arrays.asList(new String[][] {
    { "2 3 + .", "5 " },
    { "2 3 * .", "6 " }
  }
  );
 }
 
 public ParameterizedJForthScriptEngineTest(
   String script, String expectedResult) {
  this.script = script;
  this.expectedResult = expectedResult;
 }

 @Before
 public void setUp() throws Exception {
  jforthEngineFactory = new JForthScriptEngineFactory();
  jforthEngine = jforthEngineFactory.getScriptEngine();
 }

 @After
 public void tearDown() throws Exception {
  jforthEngine = null;
  jforthEngineFactory = null;
 }

 @Test
 public void testEvalReaderScriptContext() throws ScriptException {
  // context
  ScriptContext context = new SimpleScriptContext();
  StringWriter out = new StringWriter();
  context.setWriter(out);
  // script
  StringReader in = new StringReader(script);
  Object r = jforthEngine.eval(in, context);
  assertEquals("Unexpected script output", expectedResult,
   out.toString());
 }

 private String script;
 
 private String expectedResult;

 private ScriptEngine jforthEngine;
 
 private ScriptEngineFactory jforthEngineFactory;
}

The annotation before the class declaration tells it to run with a custom runner, in this case, the Parameterized one. Then the @Parameters annotation tells the runner what method will return a collection of parameters that can then be passed to the constructor in sequence. In my case, each entry in the collection is an array with two String values which is what the constructor takes. If I want to add more test conditions, I can just add more values in that collection. Of course, you could also write the data() method so that it reads from a set of files rather than hard code the test conditions and then you will reach testing nirvana: complete separation between tested code, testing code and test data!

So there you have it again: size doesn't matter, it's what you put in your code that does. JUnit is a very small package that packs enormous power. Use it early, use it often. It even makes testing fun! Did I just say that?

Update

I added the ability to produce compiled scripts in my Forth engine today, in addition to straight evaluation. I added a new test method in ParameterizedJForthScriptEngineTest and all parameterised tests are now run through both methods without having to do anything. What's better, I can immediately see what test data work in one case but not the other.

Thursday, 19 June 2008

Web Sharing and PHP on Mac OS-X Leopard

Mac OS-X comes with a version the Apache web server that is configured to allow users of the system to publish their own web pages directly from the Sites directory in their home folder. This is of limited use for the average user but is just great for web developers who can test their work directly, using a real web server. However, there is a glitch: if you upgrade from OS-X Tiger (10.4) to Leopard (10.5), existing users will suddenly get an HTTP error 403 Forbidden when navigating to their web pages. This is because in Leopard, Apache's security is tightened by default.

Apple provide an article that describes how to re-enable access for those users. However, their version will still deny access to sub-directories. So I slightly adapted the shortname.conf file to make it more flexible. Here is my version:

<Directory "/Users/shortname/Sites/*">
Options Indexes MultiViews
AllowOverride FileInfo
Order allow,deny
Allow from all
</Directory>

The star (*) at the end of the directory name on the first line ensures that the rule applies not only to the ~/Sites directory but also all sub-directories. The FileInfo value for the AllowOverride option on the third line tells Apache to allow settings override in a .htaccess file in that directory or any sub-directory thus allowing much finer grained control.

After getting this to work, it appears that, although PHP5 is installed, it is not enabled in Leopard's Apache installation. Enabling it is very easy and very well explained at Foundation PHP.

There you go: a full blown web server with PHP support is just what you need to locally test drive you beautiful web creations and you don't even have to install any extra software.

Wednesday, 12 March 2008

Making your Business Profitable: Rule #1

Okay, so I'm not a business guru, I'm a geek. But setting up my own limited company to operate as a contractor has taught me a few tricks about business and how to make it profitable. So, going back to basics, how do you make a business profitable? You ensure that there is more money coming in than going out. The money going out part is easy: it's all the bills you have to pay and it's a bit like your personal finances: you've got to make sure you don't overspend. The tricky part is the money coming in because it's different from what you're used to as an employee: the amount that comes in can vary widely and you never know when it will come in. So that's the area to concentrate on. As a result, here is in my (not very experienced) opinion the most important rule of running a business:

Make it as easy as possible for the money to come in.

At that point, you may be thinking about marketing, sales and all that sort of things. But before that, think about the plain boring basics. There are two things you need to get right from the start:

  • Tell your customers how much they owe you,
  • Make it easy for your customers to pay you.

Well, yes, the vast majority of your customers will gladly pay you if you tell them how much they owe you and make it easy for them to pay. So how does that work in real life?

Tell your customers how much they owe you

If your business is retail, this should be easy: just tell the customer when they buy something. In other businesses, like services, this is usually done by invoicing your customer. An invoice can be quite complex, especially when you start taking VAT into account. Some companies spend millions of pounds on invoicing systems. The reason is that the quicker you can invoice a customer, the quicker they will pay you. So spend a bit of time getting it right so that it's easy to do. In my case, I made sure I had a number of document templates for this and that they did most of the work for me. Nowadays, I can just open one of those templates, fill in the number of days worked, the rate per day and it does the rest for me: calculate the VAT and all total amounts. The result is that is takes me about 5 minutes to produce an invoice. Granted, my business model is very simple but it still applies whatever your model is.

Make it easy for your customers to pay you

Think about how your customers may want to pay you and make it easy for them to do so. Rather than theorise on what you could do, I'll give you a simple example.

Tonight, a colleague and I went out for dinner at a Chinese restaurant round the corner. We had a very good meal and were served by nice and helpful staff. We couldn't ask for more. Then came the time to pay the bill. The total amount for the two of us was £28.25 so we added a tip to take the total to £32. Because we have to file in our expenses differently, we wanted to pay half each and get two receipts for £16. I wanted to pay by credit card while my colleague wanted to pay cash. At that point, it all went downhill. For whatever reason, what we wanted to do was impossible. After a good 10 minutes talking to the head waiter, he managed to split the bill provided we both paid cash. From the explanation we got, I understood that the main problem in paying the way we wanted was the till system that just couldn't deal with it and didn't have a manual override.

The end result of that experience is that the problems in paying completely ruined the good experience we had had of the place, meaning that we will probably not go back there, even if everything else was great.

Invoicing your customers efficiently and making it easy for them to pay you may sound like boring mundane details but if you don't get them right, it doesn't matter how good the rest of your business is, money won't be coming in.

Friday, 21 December 2007

Zend Framework on XAMPP

I am currently experimenting with the Zend Framework, using XAMPP on a Windows laptop and following Rob Allen's excellent tutorial. With a default installation of XAMPP, you get a nasty Error 500 whenever you test your system. This is because XAMPP doesn't enable the Apache mod_rewrite extension by default. So here's how to do it. Find the Apache configuration file, called httpd.conf, which on my install is in C:\xampp\apache\conf and uncomment the following line:

LoadModule rewrite_module modules/mod_rewrite.so

Restart XAMPP and it should all work.

Wednesday, 22 August 2007

Cheap Taxi

I arrived in Sofia yesterday morning. The first thing I needed to do was find a hotel. James, whom I had met on the train already had one booked so we decided to go to his hotel and drop the bags there. If they had an extra room free for me, that'd be ideal, otherwise I'd go looking but without having to lug the bags around.

The first thing we did was have a coffee and pull out the map I had bought in Belgrade to have an idea where his hotel was. We found it easily right in the centre and estimated it was about 2 kilometres from the train station. That was easily walkable but we decided we really didn't want to carry the bags and we'd take a taxi. So once the coffee paid for, we went to the taxi rank.

As soon as we got to the taxi rank, we were approached by a guy who asked if we wanted a cheap taxi. Smelling a trap we asked how much it would be to the address we wanted to go to. He immediately answered 10 Euro, pulling his it's-very-far-away-you-know face. Even in London, they wouldn't attempt to charge you that much for a distance you could walk! We thanked him and went to an official taxi. We were in front of the hotel some 10 minutes later and got charged 4 Leva: 2 Euro.

Moral of the story: unlicensed taxi drivers have an interesting understanding of the word cheap.

Sunday, 17 June 2007

How to create a colour palette from a photograph using Photoshop

Following a talk by John Hicks at @media2007, I was wondering how to derive a colour palette from a photograph in Photoshop. As I am a real Photoshop novice, I started by searching through the help and eventually came to a technique that involving transforming the image to indexed colour mode, reducing the number of colours and creating a swatch library from the resulting image. The results were quite poor and it was very cumbersome to do. There had to be a better way.

So I ditched the Photoshop manual and went googling. It took about 5 minutes to come up with the answer: pixelate the picture, as explained graphically on Upstart Blogger from the original article at YourTotalSite. Here is the result with one of my pictures:

Pixelated photograph to extract its colour palette

Pixelated photograph to extract its colour palette

The cool thing about this technique is that it is very fast and you can manipulate the resulting colour palette as an image. Of course, if you want to, you can always extract a swatch library out of it as you would have done in the original picture.

Update: Of course, as I had just published this article I had a brain wave and decided to check out fd's flickr toys. As you would expect, they have a palette generator that does exactly what it says on the tin and gives you a 15 colour palette with hexadecimal codes and an example CSS snippet.

Screenshot of fd's flickr toys palette generator output

Screenshot of fd's flickr toys palette generator output

Sunday, 24 September 2006

White Balance

Three images showing different white balance settings

Digital cameras have one very interesting advantage over good old film cameras: you can adjust settings that you would normally have adjusted by changing film. An obvious one is the ISO setting: one shot can be taken at 100 ASA, the next one at 400. A less obvious but very important setting is the white balance. This setting is meant to adjust the colour balance in different types of light so that white areas actually come out white. If you get the white balance wrong, the white areas in your shot will come out yellow or blue, depending which way you got it wrong.

Most DSLR cameras and some high end compact digital ones allow you to override the white balance, typically by offering a presets for tungsten or fluorescent light, cloudy or shade conditions, etc. But your specific lighting conditions don’t always match a preset. Some cameras allow you to provide a sun temperature equivalent in Kelvin but this is confusing if you are not an astronomer or a physicist. Finally some cameras allow you to specify a custom white balance by giving them a reference. I had never used this setting as I wasn’t too sure how it worked on my camera, until today when I picked up a copy of Mac User that has a very simple and straightforward explanation.

I decided that the subject for experimentation would be my bedroom, complete with unmade bed. Not that I want to pretend I am Tracey Emin but the wall behind my bed is the best white reference in my flat. To make my life easier, I composed the shot to ensure a large area of white wall would cover the centre of the image, as this is the area the camera will use as white reference.

  • The first picture is taken using the automatic white balance setting. Although the camera tried to compensate for the yellow hue produced by the tungsten light, it is still very yellow.
  • The second picture is taken with a preset white balance for tungsten light, which should be the right setting in this case. unfortunately, and probably because of the lamp shade that modifies the light, it is still quite yellow. Although, in this case, when seen on its own and in the original light, the mind adjusts and makes you think it is actually white.
  • The last picture was taken using the custom white balance seting and the previous picture as a reference. This time it is really white: I verified this by using the colour picker tool in Photoshop. The funny thing though is that seeing the shot on the camera’s LCD screen, on its own and just after the previous one, the mind plays tricks again and makes you think it is blue-ish.

Using a custom white balance produces great results. The only complication is that you have to take a reference shot and adjust the setting every time you change light condition but it is easier and quicker than doing that in Photoshop afterwards, especially if you take several shots in the same lighting conditions. Also note that, because it consists in comparing the balance of primary colours in a reference subject, this reference doesn’t have to be pure white, it can be light grey. So a photographic 18% grey card is an ideal reference object.

Saturday, 30 July 2005

CSS Superscript and Subscript Using Relative Position

You might have noticed in my previous post that the note references in the body of the text were displayed as superscript. Now sup and sub are tags and should be avoided because the presentation should be in the CSS. However, there is no immediate CSS property for superscript and subscript. Here is a solution using the relative value of the position property. Let's take fractions as an example and assume I want to write 3/17. I will use classes fnum and fden for the fraction numerator and denominator respectively.

The first step is to make the text smaller, 70% should be fine. Then we need to offset it vertically. The best way to do this is to use position:relative. For the superscript, it's easy, just push it up from the bottom by 0.5em. For the subscript it is a bit more difficult. Using the top property has no effect so instead we are going to use a negative bottom property to push it down. Here is the resulting code:

.fnum {
  font-size:70%;
  position:relative;
  bottom: 0.5em;
}
.fden {
  font-size:70%;
  position:relative;
  bottom:-0.5em;
}

This works but looks weird for the denominator because, in a fraction, the forward slash (/) character between the numerator and denominator leaves a lot of white space in front of the denominator. The solution for this is to slightly shift the left margin of the denominator: margin-left:-0.2em. Why not use the fact that we are using a relative position and add left:-0.2em instead? This is because the left property shifts the content of the display box but not the box itself and it would leave a gap on the right of the denominator. The margin-left property will shift the whole box and modify the right margin as well. Of course, none of this applies for a standard subscript such as the one used in chemical fomulae like C2H5OH. That's one more reason to use semantic HTML and CSS: you can adjust the display of each individual element depending on their meaning so that they look good in context.

Update

Following the comments below, here's a simpler solution to achieve the same thing courtesy of squidoography.com:

.fnum {
  font-size:70%;
  vertical-align: super;
}
.fden {
  font-size:70%;
  vertical-align: sub;
  margin-left:-0.1em;
}
.atomnum {
  font-size:70%;
  vertical-align: sub;
}

I also agree that in an ideal world we would use MathML to display mathematical formulae but a number of major browsers (this one in particular) don't support MathML so for web documents, we have to do with HTML and CSS.