finished problem B refactoring
Because I promised in my last post, and because I like to show off, here are the results of my refactoring code jam problem B. Old and new. Took it from 143 lines to just 69 - I’m definitely happy with that.
codejam, groovy, and refactoring
This past Wednesday I entered Google’s code jam 2008. For those that don’t know (as I didn’t before one of my coworkers brought it up), this is a yearly programming competition. You are given a small selection of problems to solve, and a set period of time (hours, not days) to solve it in. When you have your program done, you download their test input, run your code against it, and then upload your results and source code.
Wednesday marked the beginning of the 24-hour qualifying round. After this, the people who made it in (a few thousand contestants) continue to online round 1. After 3 online rounds, there are a few rounds onsite at Google offices.
Having succumbed to evangelism from some other people, I decided to go ahead and code my solutions in Groovy. This was (and is, since I passed the qualifiers. w00t!) a great opportunity to force myself to learn more Groovy. Closures, quick prototyping, static typing… all the things I’ve loved about Python, but with slightly more familiar syntax, the ability to natively use the millions of Java libraries, and, for work, no need to install any new VM/interpreter on target systems.
What with learning some Groovy idiosyncracies and overcoming my own mental roadblocks, it took me about 9 hours to do the first two problems in this round. With some decent lessons learned, I think I can pare my time down to around 2 hours for a problem, which falls within the expected times for the “real” rounds.
Now that I have some breathing room, I’m using these problems as exercises in refactoring; taking my first quick prototypes and making them readable and reasonable. So far, I’ve taken my solution for problem A (the search engines one) from 102 lines to 70, while improving readability. Here is the (working) code I turned in and here is what I have now that I’ve slept on and revisited the code. A couple of the things I change involved not using Groovy-specific bits of sugar just because they were there. For instance, my main() method became much simpler when I switched away from Groovy’s awesome File.eachLine() closure and just used a standard Java Iterator. This allowed me to handle the input in a more straightforward manner. If the input were similar data on each line, I think the closure would have been better, but Google has structured their files more complexly than that.
Now that a wonderful participant has actually gone through and collected stats for the languages used, I can learn from the other Groovy-ers (you can download anyone’s solution from the code jam’s score pages, after each round is complete). One thing I’ve already noticed is that the high-ranking Groovy user, nebolsin, uses several Groovy features I haven’t seen before, but also uses C++/Java-style for loops (for (int i=0; i<10; i++) {) instead of the simpler Groovy way (for (i in 0..<10) { or even 10.times() {).
I expect to post again when I’ve finished the refactor of my solution for problem B. Also doing other quick-coding exercises as practice. Training for a coding race… wow.
My Home Automation Dreams
Just some brainstorming I’ve been doing lately. So far, my wife and I have only rented, which somewhat limits what we can do with our home. Granted, we loved our old house and this apartment is great (feels like living at a resort :-)), but sometimes I need more control.
Anyway, something that’s been on my mind lately is home automation. I would love to geek up a house to do exactly what I want. Here’s what I’ve been thinking of. I’m assuming money is no object, and since I probably won’t be able to do this until several years from now, I expect most of the tech will be pretty cheap when I get started.
I want to be able to control most everything in my home from wherever I am. I’d also like this to be unobtrusive and simple. How about a laptop touch-screen display, framed and set up with a nice picture (Monet?) and hanging on the wall. Touch it appropriately, and it alt-tabs over to a control panel. This control panel hooks into a server hidden away somewhere and gives me house-wide control over most of the following features:
My music, anywhere. I want a decent set of speakers set up in all or most of the rooms of my house - kitchen, den/living room, and office, at least. Pop up the control panel on my Monet and set up a playlist from the mp3s stored on that server, and it automatically pipes to the speakers in the room I’m in. If I go to another room, either let me manually transfer the music to the new room, or track me via RFID, Bluetooth (BlueProximity anyone?), or something similar.
HVAC control. I’ll have room-by-room central air control, naturally set up with this client-server system. No need for an extra thermostat in each room taking up wall space.
Security control. If I have any security monitors set up, I want to be able to access them from any of my dumb terminals. Probably password this in some way.
Information mashups. What’s the weather forecast? I can pull up an online recipe in the kitchen, or a car repair tutorial in the garage (lame, I know).
Alerts. Is there a tornado warning here? Do I have new email (this could tie into the aforementioned RFID/Bluetooth tracking to only display in the room I’m in)? Is someone at the front door (whether they’ve rung the doorbell or not - motion detector!)?
Cat tracking. I’m done in the basement and about to kill the lights and close the door, but I can’t be sure Anastasia didn’t follow me down here. Luckily, my Monet control panel says the RFID tag in her collar is currently batting things off the top of my dresser in my bedroom. I’ll deal with that later, but I can close up the basement now.
Along with the hidden panels on my walls, I would of course have a desktop machine in the office hooked into the system, and an EeePC or similar ultraportable near my coffee table in the den/living room. If I want to find out who that actress is in the movie I’m watching, I don’t want to get up and walk to the wall to do it.
There are a few other things that don’t make sense for the control panel theme, but can hook into the system just fine.
RFID/Bluetooth door locks. I want a front door that can tell when I’ve walked up to it, and unlocks (and maybe opens) at the push of a hidden button outside. If I walk up with arms full of groceries, I don’t want to have to dig for keys to get in - I’ll just lean on the button and walk inside.
Wireless connection to the mp3 player in my car. If I have to go buy some spackling or a hammer or whatever else I need as a homeowner doing geeky repairs, I want that playlist I was listening to to automatically transfer over so I can keep jamming on the way to Home Depot.
So, we’ll have to see how all of this matches up with my near-Amish wife who wants an authentic Victorian house.
Anybody feel like donating me an X10 gift card?
Mark Your Calendars
*salivates*
Um… ok. I didn’t have anything useful to say. ![]()
Obligatory List of Firefox Plugins
Seems every third Stumble I hit is a list of “must have” Firefox plugins. I guess it’s time for me to join the fray. Here are the plugins I have installed right now, and the reasons I can’t live without them.
In the order they show in my Add Ons dialog:
CustomizeGoogle: This extension has a myriad of options to make Google do just what you want. For instance, my Google results are now defaulted to 30 results per page, and images in image searches are linked to the image, not a thumbnailed, framed version of the original page. Can also remove ads from essentially every Google tool.
Deepest Sender: I’m using this to write this blog post. Gives me a simple notepad-esque editor, usable offline, for my wordpress posts. Can also edit existing entries.
FaviconizeTab: This allows you to arbitrarily remove the text from a Firefox tab, making the tab just as wide as that website’s favicon. It can also auto-iconize tabs that you specify (for me, that’s Pandora, GMail, and Twitter)
FireFTP: FTP client that loads in a new tab in Firefox. Honestly, it’s the most usable FTP client I’ve been able to find - loading in an existing window is just icing.
Gmail Manager: Gmail notifier on steroids. Can handle multiple accounts, including own-domain accounts (such as my sam@imnotpete.com address)
Sage: An RSS reader that loads in your sidebar, and takes its feeds from a folder in your bookmarks (customizable). It can be set to load the linked items in a custom page with simplified CSS and no ads, saving you from having to navigate the target site.
Stop-or-Reload Button: This simple extension merges your stop and reload buttons into one. If the page is loading, it’s a stop button. If the page is done or has stopped, it’s a reload button. The icon changes to match the current function.
StumbleUpon: Do I really need to talk about this one? Do I really?
Twitterbar: This adds a small button to my address bar. I can type a Twitter update into my address bar (just overwrite what’s there), and click the new button, and it will post to Twitter for me, returning the bar to its original contents when it’s done.
User Agent Switcher: This should be known by web developers (and non-Windows users). This add-on changes what Firefox reports itself as. For instance, if a software site just gives me a page that says “sorry, there’s no Linux version” instead of alternative downloads, I can just change my user agent to IE and grab a Windows download to try in wine.
Web Developer: This toolbar has a huge number of very handy tools. Visual HTML parsing (IE, dynamic borders on your tables), links to web standards validators, etc. Very complete
XML Developer Toolbar: I just installed this one today. It claims to be the equivalent of the afore-mentioned Web Developer, but with a focus on XML. We shall see.
The Honorable Mentions
ColorZilla: This extension adds a Gimp-style color dropper to the statusbar, making it easy to grab the color of anything you see (including outside the browser) without needing a third app open. Unfortunately, it seems to be inoperable with any Linux install I try (including my current Fedora 8 x86_64).
SpiderZilla: This will download an entire website to your harddrive, keeping all internal links synchronized. I used it with great success to download a part of my geneaology. This extension is also Windows-only (depends on an .exe file. I haven’t tried to see if it will work with wine).
ChatZilla: Hmmm I’m seeing a theme. This extension is a light-weight IRC client. Was greatly useful when I occasionally needed chat access. Now that I use IRC more often, I’ve switched to standalone clients - first xChat and now irssi.
Firebug: An HTML/CSS/JavaScript debugger. Somewhat buggy on Linux (IE, reeeeally slows down Gmail).
Thus endeth the roundup. What extensions do you depend on for day-to-day use or development?
Awesome Things I’ve Discovered Lately
Not necessarily new, but stuff I didn’t know about.
BlueProximity: On *nix systems, this will lock or unlock your pc based on your cell phone’s bluetooth signal strength. Get up and go to lunch, and it’ll be locked before you’re out the door. Come back, and it’s up and ready by the time you sit down at your desk.
Screen: Start up a shell session unattached to the screen. Start up irssi in a screen session, and it will survive an xserver restart. Use screen -x to have a multi-user session (IE, 2 machines in different rooms can monitor the same log file or IRC session)
Irssi: Incredible command-line IRC client. Use it. ’nuff said.
Pistachios: These things rock. I can’t believe I never had them before this week. Somebody pinch me.
Synergy: Share your mouse and keyboard between two machines over the network. Multi-platform and copies your clipboard, too. They’re working on copying more complex data (such as whole files), but probably a long way off.
PSP: Seriously. I haven’t even played any games. It’s just a great little portable internet tablet so far. Looking forward to flashing the firmware for homebrew. Have to do the whole Pandora’s Battery/Magic Memory Stick thing, so it’ll be put off for now.
servethis: simple http server
This post is actually mainly a test for the google-syntax-highlighter WordPress plugin, but it also gives me a chance to share this small script.
EDIT: {This looks bland now, because I got rid of the aforementioned plugin. Looked great, but I don’t like that it’s all JavaScript (ends up showing the code unmodified for 2-3 seconds while the page loads). It needs to run when the page is generated server-side.}
Found a python one-liner a while back to serve the current directory, but needed the ability to specify what port to use (the one-liner used 8100). I added that, and came up with this. Just call it from any directory to serve the contents up in a quick-and-dirty HTTP server. It defaults to port 8100, or you can specify the port by doing servethis [PORT]
#!/usr/bin/python
import sys
import SimpleHTTPServer
import SocketServer
# minimal web server. serves files relative to the
# current directory.
PORT = 8100
if len(sys.argv) == 2:
PORT = int(sys.argv[1])
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
I am ashamed

Singleton Pattern in AS3
I’m so proud. For the first time I’m having to actually look up a pattern for my coding. I’m implementing the Singleton pattern right now, and have run into a unique problem.
The idea of the singleton is that there will only ever be one instance of this class in the app. On top of that, the instance will not be instantiated until the class is actually needed, so as not to eat extra system resources. Usually, this is accomplished by making the class’s constructor private, and instead implementing a “getInstance()” method, which then calls the the constructor if there is not already an instance of the class. The problem here is, AS3 does not have a concept of private constructors, so there’s no way to prevent other classes from instantiating multiple instances.
The best workaround I’ve found is detailed in this blog post. By creating a private internal dummy class, and checking that it is passed into the constructor, you can at least block external calls at run time.
My code using this method:
public class DrillDownManager {
private static const instance:DrillDownManager;
public function DrillDownManager(lock:Class) {
if (! lock is SingletonLock) {
throw new Error( “Invalid Singleton access. Use DrillDownManager.getInstance()”);
}
}
public static function getInstance():DrillDownManager {
if (null == instance) {
instance = new DrillDownManager(SingletonLock);
}
return instance;
}
}
class SingletonLock {}
So in this case, if any other class tries to instantiate your class, you’ll at least get a runtime error. Also, your IDE should give you a clue that something odd is going on, by the name and type of the constructor’s argument.
Ooops. New title.
The scene with which I was greeted upon sitting at my desk this morning:

Yes, that is Darth Vader holding a flower while standing atop Ratchet, who is being attacked by Yoda, Luke, and bobblehead Darth Vader.
I love my office ![]()



