Roll your own Linux alarm clock

I bought a small alarm clock when I started college almost two years ago. I currently have no idea where that alarm clock is. Over the past two years I’ve come to realize that I don’t like to have a bunch of different gadgets doing different things, especially if I can do it on a general purpose computer. I’ev been using a software alarm clock for over a year now. Mostly I use the excellent Alarm Clock 2 for OS X, but over summer I needed to have an alarm clock on my Linux laptop. There are a number of Linux alarm clock programs out there including KAlarm and the imaginatively named Alarm Clock for GNOME. However, being the minimalist that I am, I was interested in seeing if I could get what I wanted without a completely separate program. Also since I run a minimal XMonad desktop, I didn’t want to install GNOME or KDE centric apps. What I found out was that it’s really easy to roll your own alarm clock using tools that you already have.

Gathering the tools

I used three separate programs and a small shell script to create my personal alarm clock. To actually produce the sound for the alarm I used the Music Player Daemon. As the name suggests it’s a daemon that runs in the background and can be used to play music files. Since it’s a daemon you need a separate front end to communicate with it. It’s a really useful application and there are a number of great front ends to get going. The second program I needed was a simple front end to get the daemon to play something. Normally I use the excellent ncmpc client to listen to music, but for the alarm clock I decided to install the simpler mpc client which offers some simple commands for manipulating a playlist and playing it. Finally I need a way to actually get it to play at certain times. For this I used another classic UNIX daemon called cron.

Putting it all together

Now since I’m probably going to be sleeping when I want the alarm to go off, I needed to have the mpc client automatically get some music from my collection and play it. Getting it to play music involved a simple three line shell script:

mpc clear
mpc search title Universe | mpc add
mpc play

The first line clears any playlist that I may have played last. The second line searches the MPD database for songs with the word ‘Universe’ in the title (I wanted the really loud Center of the Universe by Kamelot which is almost impossible to sleep through). The final line simply tells mpc to go ahead and get started. I saved this shell script in a file called alarm and made it executable by doing a chmod u+x alarm.

With the script ready to play music, I had to make sure that it was executed at the right times. Cron is a daemon which is made exactly for tasks like this. It uses a really simple rule format to specify timing and repetitions and commands to execute at those times. A typical cron rule has the following format:

Minute Hour Day_of_Month Month Day_of_the_Week Command

Rules for cron are saved in a file which can be edited using the crontab -e command. But I found it easier to just put the rules in a separate file and then give that file to the crontab command to use. Shown below is what my current crontab looks like. I have the alarm shell script being executed 4 times a day, everyday (that’s because I’m trying to adjust to a dymaxion sleep pattern).

45 00 * * * ~/src/scripts/alarm
45 06 * * * ~/src/scripts/alarm
45 12 * * * ~/src/scripts/alarm
45 18 * * * ~/src/scripts/alarm

Looking ahead

I’ll be the first to admit that it isn’t the perfect alarm clock. There’s no snooze or gradually increasing volume and if I want to stop I either have to type in the mpc stop command or else stop MPD via another front end. If I wanted a more sophisticated alarm clock, I’d probably write a more powerful wrapper around MPD or some other player in Python to get the extra features I wanted. But this little tool is just enough to be sufficient for my needs. Also it was a good chance for me to learn about UNIX tools like cron.

Cron can be used for a lot of things besides an alarm clock, anything that needs to run on a schedule could probably be turned into a combination of a shell script and a cron job. At the same time, you don’t have to use MPD, there’s a great tutorial that tells you how to use other media players like Amarok or MPlayer. The main thing I’d like to express by writing about little experiments like this is that building your own tools can be both useful and fun and you really should invest some time in learning the tools available to you. After all, a computer really is just a dumb machine and it should work the way you want it to, not the other way around.

First thoughts on the Eee PC 1005HA

My brand new Eee PC 1005HA arrived yesterday. The first thing I can say about it is that it’s a beautiful little machine. It’s surprisingly light, even with the 6-cell battery and the shiny blue exterior is just beautiful. I was a bit apprehensive about the color choice, but it’s turned out really well. Below are pictures of the Eee PC closed and open.

2009-08-19_06-07-24
2009-08-19_06-09-41The Eee PC comes with a battery and the power connector. It takes only a few minutes to get everything connected and the battery charges up pretty quickly too. Despite being a tiny machine, it works really well. Even though it’s considerably smaller, the keyboard on the Eee is large enough to be very comfortable and requiring very little adjustment. The keys are supposed to be 92% of normal size which I think is about right. The only little problem I have is that the up and down arrow keys are really tiny, but I think that’s something I’ll get used to easily enough. The keyboard is much easier to use than the one on my friend’s Lenovo netbook.

The screen is a nice 10″. I’ve found the 8″ and 9″ screens to be a bit too small for regular use. I think 10″ is the sweet spot. It’s still far too small for anything like programming or graphics where you need to see a lot of stuff at once, but for email, calendars and some writing, it’s a decent size. With a full screen Firefox and web apps its possible to get a lot done. Gmail and Google Calendar work quite well and a number of Firefox extensions like Twitterfox make it a breeze to stay connected easily. I had thought I could use it for blogging, but the WordPress web interface devotes a bit too much space to the sidebar to be very usable on such a small screen. I might resort to something like Bespin or Google Docs for the actual writing and wait to get to a larger monitor before I clean up and publish.

With a 6-cell battery and Asus’ Super Hybrid Engine technology the Eee PC can be expected to go a long way on a single charge. I think the claims of 8.5 hours are a bit unrealistic, but 7 hours for what I’ll be using certainly seem possible. At that rate it would be no problem for me to take it out in the morning, use it for a whole day of classes and meetings and then charge it when I come back to my room at night. Of course, I won’t actually be using in class all the time, but there will be ample opportunity for taking down notes and deadlines to put it to good use.

Finally at about $329, it’s not the cheapest netbook on the market, but it’s not the priciest one either. It’s pretty much in the middle and for the battery and other specs, I think it’s a pretty good deal on the whole. I’m wish they would have included at least a basic sleeve for that price, but since I can get a good one for about $17, thats not something I’m too bummed about. I’m looking forward to using this little baby on the go. I have a week full of training activities next week where I hope to give it something of a stress test and will be sure to report back on how that goes.

Switch-case statement in Python revisited

This post is part of the Powerful Python series where I talk about features of the Python language that make the programmer’s job easier. The Powerful Python page contains links to more articles as well as a list of future articles.

About nine months ago I wrote a post talking about how you might go about implementing a switch case statement in the Python programming language. Python lacks a native switch-case like construct, but there are multiple ways to fake a similar effect. The most naive way would be multiple if-else blocks. A more Pythonic way would be to use Python’s dictionaries and and first class functions. A simple example in C, and the two Python ways is shown below.

switch(n) {
  case 0:
    printf("You typed zero.\n");
    break;
  case 1:
  case 9:
    printf("n is a perfect square\n");
    break;
  case 2:
    printf("n is an even number\n");
  case 3:
  case 5:
  case 7:
    printf("n is a prime number\n");
    break;
  case 4:
    printf("n is a perfect square\n");
  case 6:
  case 8:
    printf("n is an even number\n");
    break;
  default:
    printf("Only single-digit numbers are allowed\n");
  break;
}

if n == 0:
    print "You typed zero.\n"
elif n== 1 or n == 9 or n == 4:
    print "n is a perfect square\n"
elif n == 2:
    print "n is an even number\n"
elif  n== 3 or n == 5 or n == 7:
    print "n is a prime number\n"

options = {0 : zero,
                1 : sqr,
                4 : sqr,
                9 : sqr,
                2 : even,
                3 : prime,
                5 : prime,
                7 : prime,
}

def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

The Fine Print

However, as the comments in the original post show, neither of the Python examples are a very good solution. They lack the versatility and power of the original C form, both in terms of syntax and semantics. Syntactically, neither of the forms do a good job of conveying the intent of the written code. The if-else form does an acceptable job and may be fewer lines, but it clutters the code with keywords and multiple equality checks and boolean combinations. The dictionary form is even worse at conveying the intention of the code.

Semantically, the two forms don’t stand up to the C form either. Multiple if-elses are probably as close as you can get, but it doesn’t work quite the same way. In particular, the ‘fall through’ semantics of a switch-case statement, where consecutive blocks are executed if there is no break statement, is a bit clumsy to duplicate. Repetitive code is almost always bad and trying to mimic the semantics of switch-cases for non-simple examples (including the above one) inevitably requires some repetition. Using dictionaries is simply a semantic mess. Creating a list and coming up with function names is really too much trouble for the simple task at hand. List comprehensions and dictionary comprehensions are powerful tools, but they simply have no place in something like a switch-case statement.

The Real Problem

This is one of the cases (pun unintended) where though you can use existing language features to get what you want (or something close), you would really like to have in-built language support. Python is a pretty well designed language as far as languages go, but it has it’s share of quirks. Personally I don’t consider a lack of switch case a particularly damaging lack, though there have been times where I wished there was one. In fact, a little Googling shows that there was a Python Enhancement Proposal submitted a few years ago but it was rejected due to lack of popular support.

There is an excellent Stack Overflow question on what the switch/case substitutes are and how to choose between them. The first answer to that question captures the essence of the problem at hand. It’s not a matter of how the alternative should be implemented, but rather what the alternative should mean. The if-else and dictionary lookups are generally useful if you have a simple choice to make in code which is mainly procedural. However if your code base is very object oriented, then you are probably better off with something like polymorphism to choose between alternatives. The solution should fit the problem, not the other way around.

The final thing I would like to say on this matter doesn’t involve Python at all. Rather it’s about Common Lisp, which I’ve been teaching myself for the last few weeks. The Lisp family of languages is particular famous (or infamous, depending on your point of view) because of the general lack of concrete syntax. Lisp code is written directly in the form of S-expressions. Essentially you write out the abstract syntax tree that in other languages is generated by the parsing the source code. Because the programmer has access to this representation, it’s possible to write code that will generate these S-expressions at compile time. In essence, this allows Lisp to be a programmable programming language. This is important because you as the programmer can basically add your own extensions to the language without waiting for a committee or community to approve it. In our case, if Common Lisp didn’t come with a switch-case statement and you really needed one, you could roll your own. In fact, it has been done. That’s not to say that rolling your language features is easy or something you should do on a daily basis, but in languages that allow it, it can be a very powerful tool if used right.

To be fair, I think you could write code to generate code in any run it in any language that has text processing and dynamic loading, but it would probably be very tedious and error-prone. The Lisp S-expression form lets you do it a much more elegant and powerful fashion.

In Conclusion

While Python does not have a switch case statement (and will probably never have one) there are a lot of other language features you can use to get the job done. It’s important to remember that you shouldn’t just be trying to recreate the semantics of switch-case (as that can be very messy). As the original post shows, trying to clone the C implementation is a futile endeavor. You need to pay attention to what the problem really is and then pick a Python feature that solves the problem correctly and elegantly. And if you get the chance, do explore languages like Lisp where syntax is fluid. It will help you better understand the difference between what your code looks like it’s doing and what it actually is doing. Happy hacking.

I miss my server

Instead of the usual Sunday Selection, I’m going to present a more personal article today. I’ve been busy moving for most of last week and by Thursday night I finally had my college room mostly set up the way I wanted it. How better to celebrate a new room and relax after a few days of heavy lifting than to completely re-install a server OS and restore everything from backups, right? My server is an old G4 Powermac with 768MB of RAM and currently 80GB of hard disk space. I used it as a desktop for about a year before I got my hands on a Mac mini and decided to turn it into a server.

Digital Disaster

I had been running OS X Leopard on it for the last year and though it worked well enough, there were some things that were starting to get to me. I didn’t like having to use a Virtual network Client to get in and change settings and I wanted a simple command line way to install programs. Though tools like Fink would have let me do that, I decided that for a production server, I wanted to run Linux. Luckily for me Arch Linux has a PowerPC port so I decided to bite the bullet, wipe the hard disk clean and install Arch on it. Unfortunately, that didn’t quite go according to plan. Though I managed to start the installer and partition the hard drive, I simply could not install anything. I also tried an over-the-network install, but I couldn’t get things off the software repository servers either. After a good three hours of fighting, I decided to throw in the towel.

I’ve decided to use the Fedora 11 PowerPC distribution, but I’ll probably strip it down to the bare essentials. I have to wait until Monday to get physical access to my server and till then I’m stuck with just my Arch laptop and my Mac mini desktop. I’m just coming to realize just how much I’ve become used to having a personal server. I’ve started using as something of a personal cloud. I use it store and sync data between my machines (using Git) and I use it to test out my web designs. Since I move around computers regularly, I’m feeling rather crippled without having my server on.

The Revelation

The thing is, I value mobility and security very highly. I’ve gotten used to starting a document or some other project on my Mini, working on it till my back hurts from sitting on the terrible school chair and then moving to the lounge to sit on the couches. Just before the move I just commit my work to a Git repository, push it to a remote mirror on the server and then pull it down to my laptop and I can be up and running like nothing happened. If need be, I can use Google Docs, which I do if I’m on a lab machine, but I really like to have a secure, safe, version controlled copy of anything important that I’m working on and I simply can’t bring myself to rely on Google Docs exclusively. My server is both a safe haven and an electronic freight route.

As you can well imagine, having the server down throws that workflow out the window. All of yesterday (and most of today) I’ve been very lethargic and reluctant to do any real writing. I dislike being tied to my laptop or desktop and I’m afraid to start anything lest I feel the need to move and have a hard time actually making the move. That in turn means that I have stuff on just one machine, something which I’ve learned to be paranoid about. The effects of this paranoia manifested in the form of writer’s block. It took me a good few hours to get myself to actually sit down and write this.

I’ll be the first to admit that I’m probably going overboard with all this. In two days the world won’t end (hopefully) and even if I start something new, I probably won’t have anything that really needs to be backed up. I suppose the real truth is that I’ve become used to a rather eccentric, and for me, efficient way of working. I’ve found and learned to use tools that aren’t used by many people, including many tech enthusiasts. It is cloud computing in a way, but in my own personal cloud for the most part. I’ve made a trade-off, and it hasn’t been an easy one to make. I’ve sacrificed the ability to use a rock-solid well managed solution (like Google Docs) with something that is more flexible and suitable, but that I have to manage myself. It’s not a choice I regret, except maybe at times like this. In fact, I don’t think regret is quite the word. A few details would make the situation much better (ie using stock x86 hardware with Arch Linux) and I don’t make the necessary changes for reasons that are not really technical. I’ve become my own cloud, I have a few dark and gloomy patches, but I could become bright and shiny without too much trouble.

Looking ahead

I’ll have my server back up and running, hopefully by lunchtime on Monday, with a fully functional Linux install. But this little incident has shown me that I need to give some serious thought to how I maintain my server in the future. The electrical engineer in me likes to have the actual physical device around (I’m putting in another hard drive once this problem is solved). But when I leave college in two years time, I’m not dragging the fairly heavy Powermac with me. At that point I will almost certainly switch over to using a hosted virtual server of some sort, maybe a Linode, depending on my budget. That will remove the need to have to personally maintain the hardware and deal with any resulting downtime.

The other question that needs answering is what software to run. Till Friday I ran OS X, but I’m pretty certain I’ll keep my servers to Linux from now on. I’ll run Fedora now, but when transition to virtual, I would like to run Arch Linux to have a more uniform computing environment. I intend to keep running an Apache server and using Git via SSH. However, if I keep using public computers the way I do, I’m going to have to find a way to get thing to Git without having to save in Google Docs first and then manually put in the repo. Luckily for me, most of the work I do is text and the Bespin text editor is coming along nicely. It’s a really nice online text editor and the backend already has support for version control systems like Mercurial and Subversion. I plan on running a local copy on my server and when it grows Git support, I’ll try to jump ship from Google Docs. Of course, for non text files I still need to use a proper Git install, but I do those rarely enough that it shouldn’t be a problem.

By the end of tomorrow I should have a fully operational Linux install ready to go. It’ll probably take a few more days of work to get everything I wanted installed and configured right and have all my git repositories set up properly again. After that I’ll begin looking into running Bespin and any other interesting personal cloud software I might find.

Sunday Selection 2009-08-09

Reading

What Works: The Wave Way vs the Web Way Google Wave might be positioning itself to be the next best thing, but the rest of the internet is gradually moving forward in its own way. This post takes an unbiased look at Google Wave and the new features the Web is evolving.

Media

Gordon Brown: Wiring a web for global good Britain’s Prime Minister talks about using the interconnected web to develop a global ethical standard and deal with situations like poverty and global warming which threaten the world.

Software

Zotero This is a Mozilla Firefox extension that makes it really easy to gather PDFs and other scholarly data from the web, organize it, attach notes and share it between computers. A must have for anyone who does regular research.