The Dark Balloon

A weblog by Hao Lian.
A journey into the soft of night.
A terrible secret guarded by golems.

§
Hello, world.

The Dark Balloon is proud to unveil its spinoff, bor.borygmus, a weblog devoted to the art of computer programming. Which is a phrase I coined and am owed millions of dollars, pending a settlement with Donald Knuth. Please show your support by subscribing.

[(2009 January 3) .]

Recent comments (HAO, Jammies.) • (Tim, Jammies.) • (Prashanth, Wedding.) • (Hao, Hands.) • (Prashanth, Hands.).

Recent posts (03/18, The Daily Show: Oscar Romero and textbooks.) • (02/03, Butter-related greetings.) • (01/18, Happy Martin Luther King, Jr. day.) • (01/18, Chances, part one.) • (01/02, Jammies.).

§
Meeting new people.

This is a retort—the best kind of retort—to Jeff Bone’s “Haskell is like ‘that girl’,” as seen first on reddit.

She knew there were girls before her. Flashy girls—flashy for their time anyway—who were all pizazz and flesh, possessing neither substance nor soul. To her credit, C forgave you, which was more than anybody in the world had done. You quit those popular girls that got around with everybody sooner or later, the ones whose names were written in all capital letters. Some even remembered your name as you broke up with them.

As you replaced the receiver for that last entry in your little black database table, you felt the click in your soul. The one of loneliness, crazy regret, and echoes. Echoes of “Did I do the right thing?” “Am I with the right person?” Penniless and broke, you ran on the pure fuel C’s forgiveness. You lived because she was there when nobody else was. You beat those demons back. With a tempest and a hiss, they capitulated and went away in some dark recess of your soul.

A decade went by and then another. It was the 90s. Girls dressed more provocatively than ever before. Those demons, always prodding your conscience for ever-beautiful hairline cracks, came back. When you got home to kiss your wife C and she kissed back, you started flinching. She realized that you changed first, and it broke her in a way she never showed it for fear they would break her. She believed in you, and sadly she thought belief was all you needed. She knew you would do the right thing.

But you broke, and her forgiveness and patience followed her heart and broke too. “New problems require new solutions,” you told yourself before drowning in the liquor, the excess, the automated memory management, and the string of never-ending girls willing to turn a trick for a cheap buck—Perl, Python, Ruby, PHP, Java, D, Erlang. Or if you were short on cash, you’d flag down a shell language and have your way. You stopped looking at your wife in the eyes; it was the only way to ignore her gentle, silent pleas. You ignored the ways she tried to change: C89, C90, C99, C1x. So you packed your briefcases and one day you never came home from work. If you had, you would’ve seen C sitting at the kitchen table waiting for the kiss on the cheek that would never come …

… a strange scene lit by the fluorescent light that would never drive away the darkness.

[(2008 September 3, 2!) .]

§
My own idiom? Please, you’re too generous.

The problem is this: You have a file of many lines and you want to delete all the newlines except the ones that precede lines matching, let’s say, /^id:/. However, “id:” might appear on lines that start with something different. For example, lines matching /^alt_id:/. Hao’s idiom: Replace all newlines with a dummy character that never appears in the text. Something akin to s/\n/:::/g. Then do s/:::id:/\nid:/g. For the love of pie, I can’t figure out a sane way to shuffle this into one regex. Note that if you could negate captures like you can for character classes—something like /^([match any two letters except]id:)/—this would collapse to one regex. (Of course, you can always expand that out to permutations of character classes, but that scales exponentially for longer captures.)

[(2008 July 16, 2!) .]

§
The dream is fading.

I spend too much time on Reddit.

from eukaryota.animalia.chordata.mammalia.primates.hominidae.homo import sapiens
from song.objects import *
import __main__

class Me(sapiens.Sapiens):
      def __init__(self):
            self.made_for = You()

      def love(self, receiver): ...
      def find(self, receiver): ...
      def adore(self, receiver): ...

      def receive_love(self, giver):
          if not given == self.made_for: raise Exception()
          ...

      def stare_at(self, object): ...
      def feet_hit(self, object): ...
      def check(self, object): ...

I = Me()
I.stare_at(Door())
I.feet_hit(Floor(cold = True))
I.check(Reflection(I))

mystery = False

for var in dir(__main__):
    if type(var) == Passion: print 'Found passion'
    if type(var) == Flame:
       if var.creates_more_feeling(I): print 'Found flame'

assert type(I.made_for) == You
I.love(I.made_for)
I.find(I.made_for)
I.adore(I.made_for)
I.receive_love(I.made_for)
[(2008 June 25) .]

§
The carefully woven ack duality amid the surreptitious cloak of night.

Update: Thanks, AndyArmstrong! This magic is specific not to ack but to pl2bat, and unfortunately I can’t track down the person who wrote that sexy voodoo, so I am removing the attribution below. There are similar tools for Python (by Christian Schaller) and Ruby.

How does Ack on Windows work? After all, Windows’ command prompt doesn’t support shebangs or any other terminal features invented in the last century. Once you type ack, it actually matches to the ack.bat file in your PATH. And when you open that, you get a huge surprise because somebody has smuggled an entire Perl program into a batch script. Furthermore, Emacs is in Perl mode for no apparent reason. What the hell is going on?

@rem = '--*-Perl-*--
@echo off
perl -x -S %0 %*
goto endofperl
@rem ';
#!/usr/local/bin/perl
#line 15

use warnings; use strict;
our $VERSION = '1.84';
use App::Ack ();

[rest of the code]

:endofperl

These are the edited first lines to ack.bat, the executable for Windows. It’s part of the infinitely superior grep alternative, Ack. (To install, type cpan App::Ack into your terminal unless you’re using ActiveState Perl. In that case, you should switch to Strawberry Perl to preserve sanity.)

Why is this terribly clever? The @rem = '--*--Perl-*-- should tip you off. It’s a MS-DOS comment (that is, cmd.exe totally ignores that line), but it’s also a Perl array assignment. In fact, the single quotation mark starts a string that doesn’t end until the semicolon at which point the ack script takes over.

Now the big picture emerges: When you run ack, you run cmd.exe ack.bat. That, in turn, it runs perl.exe ack.bat %*, where %* is a list of arguments you passed to ack.bat. And, boom, the rest follows: cmd.exe ignores the Perl bits thanks to goto endofperl and @rem. Perl ignores the command prompt bits with an assignment to the fake array @rem.

Two more juicy and more obvious bits: The assignment to @rem doesn’t throw a warning because it happens before use strict. And the --*-Perl-*-- tells Emacs, vim, and your favorite text editor to switch to Perl mode.

[(2008 June 21, 3!) .]

§
Most unique.

If set to TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which should make the results more unique.

“uniqid,” PHP documentation

It’s a weird clause. Adding additional entropy already has a highly specific, mathematical meaning, none of which is conveyed by something more unique. In fact, that would probably confuse the people who are not vaguely aware of entropy and cryptography. If it’s set to false, is it less unique? Will it somehow duplicate itself? Existential crisis, existential crisis, et cetera. All well. Without PHP, the English language would just sit there, unmolested by grammatical atrocities like these.

[(2008 June 6) .]

§
If it were a cat, it would be urlgogetiturself.

What follows is part of a patch against the twitter.py file from the awesome python-twitter project. You can download the entire patch if you so choose. With it, you can have read from Twitter from Google App Engine. I have not experimented with writing (posting) yet. By default, you get problems using urllib2 on GAE, which I bypass here like a stealthy lightning ninja greased with the body fat of my enemies. It’s part of my Quo Quo status project, which I’ll release soon enough.


+    method = urlfetch.GET
+    data, params, headers = {}, {}, {}
+    if post_data:
+      method = urlfetch.POST
+      data.update(post_data)
+
+    for x in (parameters, self._default_params):
+      if x: params.update(x)
+
+    url = self._BuildUrl(url, extra_params = params)
+    if method == urlfetch.POST:
+      mime = 'application/x-www-form-urlencoded'
+      headers.update({'Content-type': mime})
+
+    # Skip the cache, we're on GAE. This hack by shadytrees.
+    data = urllib.urlencode(data)
+    url_data = urlfetch.fetch(url, payload = data,
+                              method = method,
+                              headers = headers,
+                              ).content
[(2008 May 26, 1!) .]

§
Bioinformatics.

  • reddit post title: “A C compiler written in Python (yes, Python!)”
  • berlinbrown: Why is that shocking?
  • orbhota: Python the animal :o
reddit
[(2008 May 26) .]

§
And now: Queer Quotes.

On a Windows API tutorial about dragging text between applications:

Pre-emptive Igor Levicki comment: “Windows Vista should be dragged and dropped to the trash can.

“What a drag: Dragging text,” The Old New Thing by Raymond Chen
[(2008 March 13) .]

§
Perls.

Would you like to changes your singular nouns to plural? You can do that and much much more, in Perl (via). Note the authors have struggled with people over octopuses and viruses. Clearly they have yet to meet real grammar nazi-quibblers.

[(2008 January 21, 3!) .]

§
Tunisia, you know what you did.

All these links are fascinating because I'm a fascinating person.

del.icio.us has a little-exploited JSON API. Besides the lack of documentation, it also has one other catch: It automatically backslash-escapes single quotes and turns the quotation mark into ", possibly among other characters. I can only assume the API assumes you will immediately eval the output and then spit it out onto a web page. Hilariously, del.icio.us converts to character entities again, leading you to actually see " strewn around on that demo as pictured above from my links. Anyway, the point is PHP’s json_decode, being the black box Exception-less and soulless monster it is, will silently fail on trying to parse the mess. The solution? Below.

$s = file_get_contents("http://del.icio.us/feeds/json/hao2lian?raw");
$posts = json_decode(stripslashes($s), true);

Getting rid of the automatic character entitification is left as an exercise to the people of Tunisia, who have had it too good for far too long.

[(2008 January 7) .]

§
How to install ParseTree and RubyInline on Windows and, gasp, get them to work

ParseTree converts Ruby code to a sex expression. RubyInline is magic.

First, gem install rubyinline and gem install parsetree.

Install Visual C++ Express and the newest Microsoft Platform SDK, which is Vista SDK currently. If you wait for 2008 edition, VC++ Express will automatically install Platform SDK for you. This takes a while to download, so kidnap and chloroform a friend with spare bandwidth.

Modify C:\Ruby\lib\ruby\1.8\i386-mswin32\rbconfig.rb, which will vary depending on where you installed Ruby. If your platform is not i386-mswin32, navigate to the correct directory. Change the CONFIG["CFLAGS"] line to CONFIG["CFLAGS"] = "-MD -Zi -O2b2x".

Open up a Windows 32-bit debugging console from Platform SDK’s many Start Menu subdirectories. In addition, drag the file Microsoft Visual Studio 8\VC\vcvarsall.bat in your Program File to the console, which will paste the full file path. Press Enter. Now you have the necessary bin, include, and lib variables.

Navigate to the highly redundant C:\Ruby\lib\ruby\gems\1.8\gems path. Go into RubyInline’s folder and edit lib\inline.rb. Around line 379 and 392, manually patch the file per my poorly generated diff using a text editor or SNOBOL, which will fix quotation marks, a method call, a compiler flag, and manifest molestation.

In Inline#generate, change the file, line = line per my poorly described bug.

Now, in your console, cd to ...\gems\RubyInline-version\demo and type ruby hello.rb. You should see Hello World. If not, search Google. Common problems include missing bin/include variables, in which case use set var=%var%;c:\new\directory for the path or include variables. If the C++ compiler screws up, Google and try modifying rbconfig.rb.

OK, you have RubyInline working now. ParseTree is much simpler now that the hard part is finished. Simply wrap every builder.add_compile_flag call around line 258 of ...gems\ParseTree-version\lib\parse_tree.rb with an if /win32/ !~ RUBY_PLATFORM ... end except the -Wall since that’s the only one that works with VC++. Now run ruby ...\demo\printer.rb to make sure it works.

Congratulations. You have conquered the dragon that is compiling on Windows.

[(2007 August 8, 4!) .]

§
Bites from a larger cake, (

  • Wired magazine kisses and makes up with Wired News right after I post a comment on Slashdot about distinguishing between Wired News’s and Wired’s credibility.
  • How is Reddit better than Digg? Reddit users ask “Why is this on the front page” at an alarmingly sane frequency—close to never.
  • There’s something intrinsically hilarious in Calvin using the word Weltanschauung in his artist’s statement.
  • Things that sound cooler than they actually are: industrial rock. Thanks to Donkey Kong Country, the word industrial will always remind me of dimly lit, claustrophobic bridges.
  • Donkey Kong Country (one) had the most eclectic level designs. From jungles (first world) to Greco-Roman white stone architecture (second world) to pirate ships (end boss) to mines (above). As an SNES game, the level designs remain cool today.
  • Animaniacs and Pinky and the Brain DVDs came out on Tuesday (2006-07-24).
  • MSBuild files are the poorly documented. The only documentation (i.e., list of useful Properties) are the two XML Schemas that come with .NET … whose only mention I found on the MSBuild MSDN weblog. And even that’s incomplete: cursory examination shows that properties like IntermediateOutputPath and OutDir are missing.
  • Whee; people are making Neil Gaiman’s Stardust into a film. Excellent book.
  • Fun things to do #128: Reading all the compiler warnings on MSDN.
  • Calvin and Hobbes
[(2006 August 5) .]