Spaces and Tabs

July 3, 2009

Like emacs vs. vi and what line you put your braces on, the issue of spaces versus tabs for indentation will always be a holy war among programmers. I’m from the always-use-spaces camp, but that’s not what this blog post is about.

Pretty much any editor worth its weight in gold (which is not very much) has a spaces/tab setting whereby you can hit the tab key and it inserts enough spaces to get you to the right indentation level, saving your wrists from tapping the space bar dozens of times and getting RSI. So if you’re a spaces guy like me, go with that setting.

And if you’re a tabs guy, use only tabs. Don’t mix the two, that will only lead to trouble when you’ve got someone else who uses a different tab size. You have to be extra-careful in order to make it look right at all tab sizes. Take the following, for instance, where [TB] is a 4-space tab, [-TAB--] is an 8-space tab, and _ is a space:

// 4 spaces:
[TB]if(condition)
[TB]{
[TB][TB]return Matrix(1, 2, 3,
[TB][TB]______________4, 5, 6,
[TB][TB]______________7, 8, 9);
[TB]}

// 8 spaces:
[-TAB--]if(condition)
[-TAB--]{
[-TAB--][-TAB--]return Matrix(1, 2, 3,
[-TAB--][-TAB--]______________4, 5, 6,
[-TAB--][-TAB--]______________7, 8, 9);
[-TAB--]}

Getting this right is hard, especially since some editors (I’m looking at you, Visual Studio) like to re-indent things with tabs whenever they darn well feel like it.

Oh, and then there’s that whole semantic whitespace thing with Python. Can we please have our from __future__ import braces not throw a SyntaxError some time soon, Guido? Using tabs with Python is just asking for trouble. PEP 8 helps, but how many people actually read PEPs?

Well, I seem to have been rambling on about spaces and tabs on longer than I intended. Don’t mix spaces and tabs.

So the reason I started writing this post. Getting back to that. No really. I was editing a makefile the other day, obtained from a source which will remain nameless. Makefiles are notorious for being cryptic hard-to-maintain build systems filled with arcane syntax. Makefiles are so bad that there are a gazillion tools out there whose only purpose is to generate Makefiles: automake, cmake, qmake, Perforce Jam, and many more, though to be fair most of these tools are targeted at producing cross-platform software.

But let’s say you’re not using any of those fancy-pants tools because you’re a masochist, or more likely you’ve inherited a build system from a masochist. So you’ve got a makefile that you need to edit. I ran into this situation the other day. I fired up emacs, made my changes, and went to save it.

But something curious happened when I did so. emacs gave me the following message: “Suspicious line 50. Save anyways?” Its makefile-mode apparently installs a hook that checks your makefile’s syntax when you go to save it. Really handy. I wish other major modes did the same, although doing so may add an unacceptable delay to saving, particularly with languages with hairy syntax such as C++.

It turned out that line 50 had a mix of spaces and tabs indenting it. Hard tabs are meaningful in target specifications. In this case it didn’t end up mattering semantically, since it was in the middle of a multiline variable declaration, but I fixed it anyways to use spaces. I was also editing another makefile for which emacs gave a warning which had a blank line with spurious spaces. Again, not meaningful, but it was nice for the heads-up.

When editing a makefile in makefile-mode, emacs highlights trailing whitespace, but that’s not good enough for me. I happened to have a snippet of elisp code in my .emacs file that highlights all hard tabs. This made it especially easy to identify the problem in the offending line 50 in the makefile. I generally keep it on, but sometimes when I’m working with an all-tabs file it gets bothersome, so I turn it off. It’s amazing how code can have an awful mix of tabs and spaces all over the place as many different coders have touched it over time, each with their own preference for space and tabs.

Without further ado, the snippet. Just plop this baby in your .emacs file, and enjoy seeing your tabs burning bright on your screen:

; Draw tabs with the same color as trailing whitespace
(add-hook 'font-lock-mode-hook
  '(lambda ()
     (font-lock-add-keywords
       nil
        '(("\t" 0 'trailing-whitespace prepend))
     )
   )
)

I found this snippet somewhere online, but I’ve lost the source. If you can point me to its source, I’ll gladly attribute it. And I just realized my syntax highlighter plugin doesn’t support any variant of Lisp. That’ll need to be fixed at some point, since there will likely be more elisp snippets posted here in the future. But until then, you’ll have to deal with broken syntax highlighting (currently highlighted as C++ code). At least there’s an even number of single quotes.

Update: Syntax highlight success! Source code for the highlighter can be found here.

0

The Spoony Blog gets a facelift

June 14, 2009

I’m lazy. I’m also not a web programmer. Put 2 and 2 together, and you’ll infer that I have very little motivation to stylize this blog. But as both regular readers of this blog have probably figured out by now, I’ve gotten off my lazy ass and given this blog a new theme.

I recently stumbled across Charles Nicholson’s blog, liked the theme, and decided to shamelessly steal^H^H^H^H^H copy it. In adding the new theme, I’ve put in a few more tweaks as well. I updated to the latest Wordpress version (currently 2.8.0), which has a much nicer dashboard. I threw away the useless calendar widget on the sidebar, and I’m now working on beautifying <code> tags.

Next up is installing a snazzy syntax highlighter. I really like the look of the Google syntax highlighter (also shamelessly stolen from Charles Nicholson), so I’m going to go with that. When I’m done with that, the following code snippet should be a little more than just monospaced text in the same color and style as regular text.

#include <stdio.h>

int main(int argc, char **argv)
{
    printf("Hello, world!\n");
    return 0;
}

Edit: Success!

0

Ocarina of Time: Best. Game. Ever.

June 12, 2009

At least according to the users of GameFAQs. The Legend of Zelda: Ocarina of Time recently finished triumphing over Final Fantasy VII in the 128-game battle royale contest of Best. Game. Ever. 2009, which took place over the past two-plus months.

Each day, four games battled it out in the Poll of the Day, with the top two advancing in the bracket. In the final battle, Ocarina of Time edged out Final Fantasy VII. With the third- and fourth-place games from that match removed (also Zelda and Final Fantasy games, incidentally), Ocarina held onto its title in the bonus match, taking in 52.69% of the 155,838 votes cast.

GameFAQs has held some sort of tournament-style contest every year since 2002, with some years hosting multiple contests. There have been seven character battles, one game villains battle, two games battles, and one game series battle. The other games battle prior to this year took place in 2004. That battle was a 64-game 1-on-1 single-elimination tournament, in which Final Fantasy VII emerged victorious over Chrono Trigger in the finals, after defeating Ocarina of Time in the Division Finals [full bracket and stats] [bonus poll].

What does this turnabout mean for GameFAQs? I’d say it’s most likely a shift in user base demographics towards Nintendo. Nintendo games absolutely dominated the contest, what with a whopping four Mario games, four Zelda games, two Super Smash Bros. games, and a Pokémon game comprising 11 of the 16 final games, the other five being three Final Fantasy games, Resident Evil 4, and Metal Gear Solid 4.

Another surprises was Chrono Trigger getting narrowly defeated by Super Mario 64. There were also a few times where one game beat another in one round but then lost to it the next, such as Pokémon Red/Blue/Yellow and Metal Gear Solid, Final Fantasy X and Super Smash Bros. Melee, and Metal Gear Solid 4 and Super Smash Bros. Brawl. There were a lot of other results that differed greatly from something which happened in 2004, but I won’t continue boring you with statistics.

All in all, it was a fun contest with a number of surprises, but I’m starting to question the value of these contests. They were fun and exciting at first when they were completely unpredictable, but now they’re starting to get dull as people get better and better at understanding what GameFAQs visitors like. It was refreshing to have a games contest this year after not having had one for five years. I suspect, though, that the contests will continue so long as they continue to attract more visitors to the site. So what will see next year? I’m hoping to see something completely new and different, but odds are it’ll be Character Battle VIII, with some mildly interesting gimmick.

My personal Best. Game. Ever. is Final Fantasy VI. What’s yours?

0

Word-Fu is out!

April 11, 2009

Ok, Word-Fu has been out for over a month now, and I’ve been really lame about updating this blog. Word-Fu is an iPhone game developed jointly between Demiurge Studios and ngmoco:) that I was working on for a couple of months. The first release was on February 26, and the first update hit the iTunes App Store not too long ago. We’re now working an a second update, to include localizations into a few other languages (which is extra challenging for a word game).

So what is Word-Fu? Word-Fu is a Boggle-like spelling game, where you’re given a bunch of dice with letters on them, you shake them up with the iPhone’s accelerometers, and then touch them to spell words. Unlike Boggle, there is no constraint that consecutive letters must be adjacent—you can use the letters in any order. If you happen to get a particularly good set of letters (such as ACEIKORTS) and you know a lot of anagrams, you can just keep spelling more and more words. You get extra time for each word spelled, so you can keep playing for quite a long time and rack up your score.

You can even reuse letters in the same word, so if you get an A, an E, and an S, and you spell long words like ASSESSES with just those three dice. There were some discussions during development with very strong opinions regarding this feature—I was in favor of not being able to reuse letters—and we ended up supporting both modes of play. The mode where you can’t reuse letters is called Shaolin Style, and it can be turned on in the Options screen; it is disabled by default.

So if you’re a word game freak, what are you waiting for? Go check out Word-Fu in the iTunes App Store today! It’s currently $1.99, although there was a special promotional price of $0.99 for the first couple of weeks after the game launched.

0

Don’t steal Mac OS X

January 5, 2009

I was reading through the Mac OS X Internals book, and came across this interesting nugget in chapter 7. In OS X 10.4, a kernel extension maps an anti-piracy message into the 256 bytes of virtual address space of every running process at address 0xFFFF1600, which you can see for yourself by compiling and running the following code:

#include <stdio.h>
int main(void)
{
    printf("%.256s\n", (char *)0xFFFF1600);
    return 0;
}

The output:

Your karma check for today:
There once was was a user that whined
his existing OS was so blind,
he'd do better to pirate
an OS that ran great
but found his hardware declined.
Please don't steal Mac OS!
Really, that's way uncool.
   (C) Apple Computer, Inc.

Note that this only works in OS X 10.4, not in 10.5. I don’t know if it runs on older versions of OS X. I wonder if this message is also on iPods and iPhones.

0

Beware of struct properties

January 1, 2009

Objective-C is an interesting programming language. Unlike C++, it’s a strict superset of C — every valid C program is a valid Objective-C program. While most C programs are valid C++ programs, there are certain incompatibilities such as the introduction of new keywords that make the relationship not strict.

One of the many features that Objective-C brings is properties. Properties essentially act like public member variables, but whenever you get or set them, those gets and sets get rerouted through a function call (more specifically, the passing of a message in Objective-C parlance). For example, if value is a property of whatever class my_object belongs to, then the code

int x = my_object.value;

gets converted into

int x = [my_object value];  // pass the 'value' message to my_object

And this code

my_object.value = 3;

gets converted into

// pass the 'setValue' message with parameter 3 to my_object
[my_object setValue:3];

Getters and setters allow you to do things like parameter validation, logging, or anything else you want whenever a property is read from or written to. The dot notation is just syntactic sugar.

Now suppose that value isn’t a simple integer, but rather a struct of some sort, such as a CGPoint. A CGPoint is a standard 2D point class, containing two float members named x and y. Consider the following innocent-looking code:

my_object.value.x = 3;  // set x-coordinate to 3?

If value were just a plain ordinary struct member, this would do exactly what you’d expect – set the x-coordinate to 3, and leave the y-coordinate untouched. But as you’ve probably surmised by now, that’s not what happens when value is a property. Why not? Well, since we’re not assigning to it, it gets turned into this:

[my_object value].x = 3;

And [my_object value] returns an object of type CGPoint. And structs are returned…..by value. Thus, we’re assigning 3 to the x-coordinate of a temporary CGPoint which is a copy of our object’s value property. The only proper way to resolve this is to make value a regular class member and not a property, reassign a completely new CGPoint to value, or add messages that allow you to independently set the x- and y-coordinates. Depending on whether or not you own the code for the class, this may or not be possible.

Fortunately, in the case of CGPoints, it’s relatively easy to assign a new value with CGPointMake():

my_object.value = CGPointMake(3, my_object.value.y);

But for more complicated structs, this solution could be less than ideal.

0

Not your average regex find-and-replace

December 25, 2008

I was reading through some of the Coding Horror archives, and came across this post examining Microsoft Visual Studio’s use of regular expressions in its find-and-replace dialog. Visual Studio has support for all of the usual regex constructs but throws in a lot of its own quirky constructs too. I suppose they could be useful if you learned to use them.

But this post isn’t about Visual Studio. Jeff’s post contained an intriguing link to Steve Yegge’s blog, where Steve goes over some of the new features in Emacs 22. And despite my being a long-time emacs user, I was pleasantly surprised to learn that you can use elisp with find-and-replace.

Now at first, this may not seem like a big deal. You can do a lot with a plain vanilla find-and-replace (M-x replace-string and M-x query-replace (also bound to M-%)), and regex find-and-replaces (M-x replace-regexp and M-x query-replace-regexp (also bound to C-M-%)) are damn powerful. But sometimes, when a sed script won’t do, an elisp find-and-replace can save you a lot of pain.

To do an elisp find-and-replace, do a regular replace-regexp, and set the replacement expression to \, (backslash-comma) followed by an elisp expression. You can use backreferences \1 through \9 as string variables, and you can use \# as an integer variable that is the total number of replacements made so far.

Steve has a number of great examples which I’m not going to repeat here, so I encourage you to go over there and eat ‘em up.

I was eager to try them out, and seeing as how Emacs 22 is over two and half years old, I figured my current Emacs install would be up-to-date. Not so – my MacBook was still running Emacs 21.2.1, which came installed when I bought it in 2006. Fortunately, with MacPorts installed (HIGHLY recommended for anyone running OS X), upgrading was almost as easy as running

sudo port install emacs

I did install instead of upgrade because my emacs install was the default one that came installed and I hadn’t migrated it into MacPorts yet. I said it was almost that easy because after it installed and I went to run it, the old Emacs 21 ran instead, even though the MacPorts binaries directory /opt/local/bin precedes /usr/bin in my $PATH. It turns out that bash uses a hash table, of which I was previously unaware, to cache where frequently used commands are located to avoid searching your $PATH frequently. To fix this, just run hash -d emacs to delete its binding for emacs (or hash -r to clear the entire table), and you’re good to go!

0

The Infamous Red Ring of Death

November 28, 2008

About two and half weeks ago, my Xbox 360 gave me a Red Ring of Death, indicative of a general hardware failure.

Red Ring of Death

It’s about two years old now, and there weren’t really any warning signs.  I went to turn it on, and….it didn’t.  Most RRoDs are caused by overheating; I generally keep my 360 well-ventilated, and I definitely don’t leave it running for long periods of time when I’m not playing it.  I’m going to chalk this one up to poor hardware design and workmanship.

I immediately called 1-800-4MYXBOX.  Boy were they unhelpful.  The automated voice-activated menus were a pain to work through, and I had to repeat myself several times to get what I wanted.  Why can’t we just have a plain old “Press 1″ instead of say “Three flashing red lights”?  It’s easier for everyone.

After wasting my time with that, I instead went to xbox.com/support and had a much easier time.  It took me less than five minutes to file a support ticket and print out a pre-paid shipping label (I also had the option of getting a box shipped to me, but that would have taken longer obviously).  No human interaction required.

The next morning I brought my 360 down to the UPS Store and had it shipped off to the repair center in Mesquite, Texas.  It took about a week to get there, a couple days to get fixed, and another week to come home.

Now it’s back to Mega Man 9!  I’ve completed all 12/12 achievements (200 points) and 34/38 challenges.  All I have left are “Beat the game without getting hit”, “beat the game while picking up only 8 energy capsules”, “beat the game 30 times”, and “beat every boss with 1 hit point left”.

The Green Ring of Life is back, but for how long?

1

Slashdot Easter Egg

October 11, 2008

Did you know that every time you view a page on slashdot, you’re given a random Futurama quote? Most people don’t, since they’re hidden away in the HTTP headers, so you’ll never see them via normal web browsing. I discovered this one time when I was playing around with cURL. Here’s a sample HTTP trace:

adam-rosenfields-computer ~$ curl -I slashdot.org
HTTP/1.1 200 OK
Date: Sat, 11 Oct 2008 04:16:23 GMT
Server: Apache/1.3.41 (Unix) mod_perl/1.31-rc4
SLASH_LOG_DATA: shtml
X-Powered-By: Slash 2.005001224
X-Bender: Boy, were we suckers!
Cache-Control: private
Pragma: private
Connection: close
Content-Type: text/html; charset=iso-8859-1

-I is the option for doing a HEAD request instead of a normal GET. So, a quick and dirty script to generate a random Futurama quote is:

curl -I slashdot.org 2>/dev/null | grep '^X-' | grep -v '^X-Powered-By'

This works since all of the quotes are under a header name beginning with X-, e.g. X-Bender, X-Fry, or X-Leela. I’m not sure how many total quotes there are in the database, but you could probably get a good estimate by sampling a large number of times and counting how many unique quotes and how many duplicates you get, and then extrapolating.

0

Even Sony uses Free Software

September 28, 2008

I just purchased a new 46″ HDTV, the Sony Bravia KDL-46V4100, and boy is it sweet. But I’m not here today to advertise TVs to you. I was reading through the various documentation that came in the box, and I came across a copy of the GNU General Public License and the Lesser General Public License. Even Sony uses Free Software in their televisions.

The 46V4100 includes the following GPL’ed software: Linux Kernel (no version number mentioned), busybox, and pump (no idea what this is). Under the LGPL, it contains glibc. Other software listed includes Independent JPEG Group Software, Software Developed by the OpenSSL Project for Use in the SSL-Toolkit (SSLeay License), Freetype2, Expat, cURL, and Popt.

0