Three progressively better ways to generate a random string in Python — March 23, 2010

Three progressively better ways to generate a random string in Python

Version 1 here is what I started with. Version 2 comes from a colleague, version 3 from another colleague.
Version 4 just makes things a little more succinct.

I enjoyed watching this simple function get cleaner as the days went by.

#!/usr/bin/python
import random
import string

def random_str_1(n):
“””
Generate a pseudorandom string of
length n.
“””
out_str = “”
letters = [‘a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’,’i’,’j’,’k’,
‘l’,’m’,’n’,’o’,’p’,’q’,’r’,’s’,’t’,’u’,’v’,’w’,’x’,’y’,’z’]
for i in xrange(n):
out_str += random.choice(letters)
return out_str

def random_str_2(n):
“””
An improvement, using the fact that Python
strings are iterables that iterate over their
characters.
“””
out_str = “”
letters = ‘abcdefghijklmnopqrstuvwxyz’
for i in xrange(n):
out_str += random.choice(letters)
return out_str

def random_str_3(n):
“””
A further improvement, using an existing
library attribute.
“””
out_str = “”
for i in xrange(n):
out_str += random.choice(string.ascii_lowercase)
return out_str

def random_str_4(n):
“””
Adding a bit of concision.
“””
return “”.join([random.choice(string.ascii_lowercase)
for x in xrange(n)])

def test_all():
“””
Not really much of a unit test. Just confirms that
each of the generated strings is as long as specified.
Doesn’t test that strings are sufficiently random.
“””
methods = [random_str_1, random_str_2, random_str_3, random_str_4]
for n in xrange(40):
for method in methods:
out_str = method(n)
assert len(out_str) == n

Stop going off about the public option — March 22, 2010

Stop going off about the public option

Sorry to be so negative, but really: people just shouldn’t be getting pissed about the absence of a public option, for at least three reasons:

1. Even with a public option, we always would have needed to address subsidies for those with low incomes. People are welcome to chime in with other information here, but the public option does not address affordability at all. It addresses the quality of insurance. Subsidies were always the bigger deal.
2. *We got coverage for 32 million people*. We got *affordable* coverage for 32 million people. We got coverage that *saves 32 million people from health-care-related bankruptcy*. Liberals of a certain stripe have gotten monomaniacal about their preferred policy, rather than focusing on the end goal — which is *to help people who couldn’t afford good health insurance to afford good health insurance*.
3. Now we have something that we can fix. Before we had nothing. New entitlements don’t disappear, as David Frum has now-famously pointed out. Entitlements get better. So let’s make this one better.

This has been, in some ways, a great hour for the Left. In other ways, it has revealed them to be monomaniacal public-option fetishists. Now is not the time to continue the fetish. Now is the time to consolidate our gains and *keep moving forward*. You want a public option? Great! You’re closer to a public option than you were a year ago. So go get it. Donate to candidates who support it. Call Bernie Sanders’s office and ask what tactical advice he’d give. Don’t act like an armchair quarterback and complain that the big bad U.S. Congress with its big bad traitorous liberals didn’t give you what you wanted.

History is written by the winners; history also exalts the winners — March 21, 2010

History is written by the winners; history also exalts the winners

If this health-care-reform thing happens, people will find Reasons Why It Happened. Look at what happened when Scott Brown won in Massachusetts: people tried to look for a Large Trend or whatever that explained why the Republicans were taking over. Brown won with 52% of the vote — certainly a solid lead, but not exactly a landslide. Many things could have caused a three-percent swing in votes. Coakley could have been a better candidate, for instance. But once Brown won, journalists had to opine on What It All Means — because it had to Mean Something.

Now here we are on the eve of what looks like the greatest progressive victory since Medicare. I, for one, am incredibly excited. I’m excited both because 32 million of the least fortunate Americans will have a safety net beneath them that’s a bit stronger; and because I hope that this will energize progressives toward future victories.

So now the press will have to come up with explanations. Health reform succeeded because Nancy Pelosi is one of the greatest Speaker in House history, for instance. The Republicans failed because the Tea Party movement, while important, was ragtag and ill-focused. Etc.

But we were all alive over the last year. We saw where this could have failed any number of times. It could have failed if House Democrats had fallen apart after Scott Brown’s victory, as it looked like they would. It could have failed last summer if the Tea Party thing had freaked people out more than it did. Had it failed at any of those moments, the press would be looking for reasons. Nancy Pelosi would still be the Speaker, but now she’d be the worst Speaker in House history — squandering a massive lead, etc., etc. Flip a few Congressmen the other way, and suddenly the narrative changes massively.

I’m not saying that this victory — should it happen — is entirely arbitrary; of course it’s not. What I *am* saying is that, if it were as inevitable and foreordained as the narrative will make it out to be, then no one would have panicked over the last year.

I like simple explanations as much as anyone else. I like, for instance, the Larry Bartels model that predicts presidential elections on the basis of macroeconomic factors like the unemployment rate. So far as I know, there’s no such model predicting victory in this health-reform debate. The only explanations that people can advance are post-facto ones.

Which doesn’t bother me a bit, in this case. My side looks like it’s going to win. (If it doesn’t, I will do the appropriate amount of crow-eating.) If this will have any effects, they will be positive effects for my side. Victory is like that.

What I’m curious about is how long-lasting the effects of a victory — any victory of this magnitude — are. It’ll help us, but for how long?

What would people like to attack after this? Financial-system reform?

The abridged O Ya report — March 18, 2010

The abridged O Ya report

Stephanie and I went to O Ya last night, one of the items on the Laniel 2K10 Post-Full-Time World Dominance (aka Y’All Just Rentin’ This World From Me) Tour. [1] [2] I hope it’s not gauche of me to sum it up as “good, but not $267.56-per-person-with-drinks-and-tax-and-tip good.” I mean, a meal has to be pretty over-the-top good to be worth that. I’ve not yet had a meal at that price range that justified itself.

The last time I was in that price range was at L’Espalier, where the meal ended up costing about $750 in total for two people — so far above and beyond the realm of the comprehensible that we could only laugh. In fact Stephanie and I laughed about that one for the next 20 minutes as we walked away from the place. And the food wasn’t even that outstanding: of the 10 or so courses that L’Espalier brought us, two were really outstanding; they overwhelmed us with tastes and textures flowing over our palates more quickly than we could process them. There was smoky, crunchy, popping, astringent, smooth, fatty, liquid, and dense, all at once. This little one-ounce morsel was something I wanted to spend the next hour eating, though it would still have left me in the same dazed state.

But still, I must return to the moral: $750 for a meal that was 20% overwhelming?

O Ya was similar, though less absurd for a couple reasons. First, I knew going in that it would cost about what it came to. Second, O Ya doesn’t try as hard to make you think that you’re having a Fine Dining Experience: rather than L’Espalier’s sumptuous opulence, O Ya looks like a relaxed Japanese bar. O Ya’s exterior door is, on first glance, so dingy-looking that I assumed it was the entrance to a run-down warehouse rather than to an exalted restaurant. (On closer inspection, the door is supposed to remind you of the entrance to a humble Japanese home. It’s a very nice touch, in retrospect.) Inside, they’re playing rock music, and the chef is bouncing his head in time with the music.

The chef, I should note, isn’t doing all the things you expect a sushi chef to do: he’s not assembling rice balls or cutting large filets of fish from a newly dead animal; those jobs are left to the servants, who are off in a mostly obscured kitchen. They would periodically come out and receive a scornful glance from the chef, who clearly functions as the [foreign: prima donna] in this opera.

Anyway, to the food: 16 courses, each two bites (one for me, and one for my lovely dining companion). Most were standard sushi-sized pieces of fish, drizzled with oils, topped with preserved Japanese oranges, and so forth. They were delicious. But (and again, I feel like a clod for saying this) not $500 delicious. One particular dish was a few pieces of Japanese beef, seared, dressed with just the right amount of salt, and served atop a special (artisanal? heirloom? [foreign: sous vide]?) potato chip. This dish on its own was $61. There is just no reason for that.

I wish I didn’t have to spend this much time discussing the money aspect. I actually didn’t spend much time during the meal thinking of it: I knew going in that it would cost that much, and I didn’t want to spoil the mood. Plus I was there with my girlfriend, who is my favorite dining partner in the world [3]. And in one or two cases, the dishes were so good that my eyes actually rolled back into my head. But for $500, your eyes should do something even more awesome, like evaporate and re-coalesce, or colonize Mars.

Honestly, if you’re looking to have a really special meal around here with a loved on, there are better bets: Craigie on Main for extraordinary food (Excuse me? 10-course *vegan* tasting menu?) in a boisterous atmosphere with some of the best cocktails in the city; Oleana for a more subdued, self-consciously exquisite meal; or Number 9 Park if you want to go all out.

When O Ya sets its prices that high, it gives itself an entrance exam that it then proceeds to flunk.

[1] – Uh, yeah, I might could have mentioned that they hired me full-time.

[2] – We’re going to the Bahamas at the end of this month — the second bullet on the Y’all Be Rentin’ Tour.

[3] – You also will never find a better person with whom to watch a movie on the big screen. There’s a particular “Stephanie’s jaw agape” photo that I’ve surreptitiously taken five or ten times now in the theatre; it never ceases to make me smile.

Vindication, then and now —

Vindication, then and now

On the elevator up to work today, I saw a headline that Obama says he’ll be vindicated for the choices he’s made on health care and financial reform.

To review: President Bush starts an unnecessary war in which thousands of Americans die and we literally detonate $3 trillion. Obama picks up a financial crisis that started on Bush’s watch, then helps to push through health reform that will cover 30 million of the country’s least fortunate while reducing the long-term deficit.

Now then: which of these two would you guess has to worry about how history will view him?

The MBTA doesn’t want my money — March 15, 2010

The MBTA doesn’t want my money

One thing I’ve always found weird about the T is that you can’t buy a monthly pass whenever you want. Suppose that on the last day of February, I decided that I wanted to get a monthly pass for February. That’s $60. Surely no one in his right mind would do that, right? But suppose I wanted to. Why would the MBTA stop me from giving them $60 for a day’s worth of rides?

Likewise, I have this habit where, if I get a small windfall (a particularly large contracting check, say), I try to find upcoming expenses that I should pay so that the money doesn’t burn a hole in my pocket. So I was in the T station the other day and decided that I’d put April’s T pass on my CharlieCard. The machine told me that I couldn’t do this, because only tickets up to March were available.

Suppose I wanted to buy passes a year in advance. Why wouldn’t the MBTA want that? They’d get about 720 of my hard-earned dollars, which they could put in a bank and earn interest on. I guess they’d have to add a bit more code to their kiosks, but that seems like a small price to pay.

While they’re at it, how about allowing recurring payments through their website, so that I don’t even *have to* interact with their kiosks?

Oh, and also: how about having their commuter-rail-ticket-dispensing machines ask you which *town* you’re going to, rather than which *zone?* I have no idea which towns are in which zones.

Arguing the World — March 12, 2010

Arguing the World

I just watched this; terrific stuff. It follows four New York intellectuals — Irving Howe, Irving [father of the omnipresent William] Kristol, Daniel Bell, and Nathan Glazer — from their meeting at City College of New York in the 40s to the present day. Glazer, Kristol, and Bell all curved off into one form or another of conservatism, while Howe remained until the end the strident liberal. But what’s spectacular about this film, and really sets it apart from any other movie I’ve seen, is that it refuses to take sides against any of these men. It wants to trace their failures and their achievements to their roots as disputatious New York Jews, while still trying to understand how men could come out of the Sixties with such different feelings toward politics and ideas. Really a terrific film. (And I submit that it’s impossible to come away from [film: Arguing the World] without a little crush on Irving Howe — particularly given the impish smirk he gives the camera just before we find out that he’s died.)

__P.S.__: Hat tip to Hendrik Hertzberg, from whom I learned about this excellent movie a few months back; it just floated to the top of my Netflix queue recently.

An update on Diamond DVI-to-USB adapters and Belkin USB hubs —

An update on Diamond DVI-to-USB adapters and Belkin USB hubs

All is not rosy in the land of multi-monitor MacBook Pros. As I mentioned there, I’m driving two large external monitors through USB, using Diamond adapters to connect USB to DVI; the USB plugs run into a Belkin USB hub, which runs into a single USB port on the side of the MacBook Pro with which my employer generously supplied me. (I will give you guys an iPhone app very soon; promise.) The dream is then that I can then run a bunch of other USB devices off the hub as well: iPhone, mouse, camera, etc.

It sadly hasn’t worked out that well, for reasons that illustrious Stevereads commentator mrz explained in comments to that post:

1. There’s just not enough bandwidth in USB — much less in a USB hub, which has to split one USB port’s worth of bandwidth across seven devices — to power a high-resolution monitor (much less two high-resolution monitors). My monitors would periodically slow to a crawl, and would slowly repaint the screen from top to bottom. I had to unplug the USB hub at this point, so that OS X could shift everything onto the built-in monitor; once it did that, the speed returned to where it should have been.

2. The USB hub — possibly because of item 1 — has died. None of the components plugged into it work, individually or together. When I unplug any of them — say, the mouse or a monitor — and plug them directly into the MacBook Pro, they return to life.

I can live with item 1: sure, I move windows around, and the rendering doesn’t really keep up with the movement, but it’s better by far to have two slow monitors than only a built-in MacBook Pro screen. Obviously I can’t live with item 2: I can’t stand to have a hub die after only a few days of use.

I tried to call Belkin support, but it’s another Indian call center. I find few things more disheartening than finding Indian tech support on the other end of the call; it speaks of a tech company that wants to save money (hmm: flimsy, cheap product?) and doesn’t care at all about helping its customers.

I may try to find another, better, more reliable USB hub, but the Belkin one gets fine reviews on Amazon. I’ll have to look around more closely.

Driving two external monitors off a MacBook Pro — March 8, 2010

Driving two external monitors off a MacBook Pro

Thanks to my employer for hooking me up with a beautiful MacBook Pro and two huge external monitors.

If you’re trying to do the thing mentioned in the title of this post, you’ve probably already found the perfectly comprehensive post I’m going to link to. If not, it’s this guy right here. The Cliffs Notes version is as follows:

* Your MacBook Pro has one Mini-DVI port. You want to drive two external monitors. *Problem*.
* So buy two Diamond BVU195 USB display adapters. These allow you to connect DVI cables to USB cables, of which your MacBook Pro has a few.
* “But wait!” you might say here, “I only have two or so USB ports, and I want to drive two external monitors. How will I plug in an external mouse *and* an iPod/iPhone, *and* those two monitors?” Fear not: here’s where you buy a USB hub. I got a 7-port Belkin external USB hub for $28. I run a cable from there to a USB port on the MacBook Pro, and I’m done.

To review: up to here, you’re running one DVI cable from each of your monitors into a DVI-to-USB adapter from Diamond. Then you run the resulting USB cables into a USB hub. Then you run one cable from the hub into your MacBook Pro. Now both your monitors, in summary, are being run off a single USB port on your MacBook Pro. *Sexy*.

The final step, again as detailed in that article, is

* Download and install the DisplayLink OS X drivers. Now you can use System Preferences to arrange your three monitors — two external, one built-in — in any configuration you like.

[foreign: FIN].

I would include pictures of how these things all work on my end, but the fellow who wrote that piece included everything I would have.

My only question now is how to get control of the ridiculous quantities of cabling I have laying on my desk at work as a result of these contortions:

Messy desk, lots of cables

Haruki Murakami, Dance Dance Dance — March 6, 2010

Haruki Murakami, Dance Dance Dance

Cover of Dance Dance Dance: at the top of the cover, a seductive Japanese girl's eyes, staring at the reader; in the middle 2/3 or 3/4, an apartment complex viewed at night with the title overlaid; at the bottom, the author's name and a blurb

Now that is what I’m talking about: a classic Murakami novel, with

  • a disaffected narrator fumbling vaguely through his days
  • the wall between our world and a much darker one — a world which may be within our own souls OMG — falling away
  • some sex (though less than you might expect from Murakami)
  • a semi-pulpy story that pulls you along effortlessly

In The Wind-Up Bird Chronicle, the dude’s cat disappears, and then shit gets real. (Oh, and by the way: he spends a lot of time at the bottom of a well. So there’s that.)

In Kafka on the Shore, cats start disappearing from this one neighborhood, and a retarded guy with special powers chats up the cats’ cat friends, and then shit gets real.

In After the Quake, people’s empty lives contribute in some undefined way to the Kobe earthquake; at the very end we see that our characters are tentatively bringing themselves out into the world again, becoming the sort of people they know they should be.

In After Dark, the boundary between the Dark World and this one is paper thin, and sometimes disappears altogether. Sometimes that boundary exists on a physical device that gets left in a convenience-store refrigerator (for instance).

So you see a pattern forming. There may have been a time in my life when I would have derisively called Murakami “formulaic,” but that word is actually an insult to the power of a good formula. Philip Roth succeeded for a good forty years by adhering to the Jewish-author-with-inexplicable-sex-appeal-exploring-masculinity formula. (All right, that’s kind of a complicated formula. Roth was a [foreign: sui generis] author.) Jazz music has evolved from one formula to another. Country music, from what I can tell, has been the same formula interpreted in different ways for half a century (cheatin’ woman, lonesome highway, etc.). I’ve listened to a lot of Frank Sinatra, and it was all — down to particular trills — the same formula. But man was that a good formula. The formula is essentially arbitrary; I have a book in queue — Georges Perec’s A Void — whose guiding premise, if I’m not mistaken, is that all such formulas are arbitrary, so why not pick one that’s truly arbitrary (don’t use the letter ‘e’ at all) and see what you can do within it.

As ever, it’s what you do with the formula. Murakami knows how to fold, spindle, mutilate, and combine genres like no one else. Dance Dance Dance should maybe be called a supernatural mystery novel, in a way that really only makes sense if you’ve read a bunch of other Murakami. Our narrator — really a pretty excellent guy, which you can’t often say about Murakami protagonists — wakes up more than a little freaked out one day after an old lover calls to him in his sleep. She haunts him, but from where? From beyond the grave? Is she dead? Is that her ghost?

Anyway, this woman — Kiki is her name — is calling to him, and he knows exactly what he has to do: he must return to the hotel where he and Kiki spent the formative months of their relationship. It is a creepy, bizarre hotel, where everything is just a bit askew. I couldn’t help picturing an old ramshackle house, lightning flickering behind it during deepest nighttime. Our narrator returns to the hotel to find that it’s been replaced with a gleaming skyscraper of a hotel whose name is the same as the old one it replaced. Why would they bother to keep the name the same?

Here we spin off in a few directions. First of all, we run down the “I don’t know what this monkey business is, gumshoe, but I’m sure as George Peppard gonna find out what happened to that old hotel” direction. Might there be a [foreign: yakuza] connection? Only time will tell.

(Actually time won’t tell: it’s a Murakami novel, and I still have no idea by the end whether the mafia were involved. Just throwing that out there so that I don’t mis-set expectations.)

Second, our narrator sees a beautiful 13-year-old girl sitting in the bar with her mother. Hijinx ensue. Turns out that the mother is brilliant but spacey, and leaves her daughter all over the world while she — the mother — hops on planes to Kathmandu or wherever. The daughter is left to fend for herself. She is, as you might expect, world-weary and vulnerable and … well … motherless.

The friendship that develops between the narrator and this girl is the most convincing character development I’ve found in Murakami. He feels tenderly toward her — sort of fatherly, but more like a wise older friend. She’s a classic teenager: sullen, believing everyone else is so lame, smacking gum loudly and wearing her headphones whenever everyone else just gets too lame for words. Their relationship is very captivating, perhaps because I put myself back in the mode of a teenage boy who absolutely would have fallen in love with this gorgeous girl; back in those days, I wanted so badly for the uninterested girl to be interested. The narrator puts himself in that mode, too. Somehow it’s never creepy: our 34-year-old narrator doesn’t lust after a 13-year-old girl at all. They’re Butch Cassidy and the Sundance Kid, with a window into the underworld.

We start out wanting to know where Kiki is, but we end up wanting to know so much besides. The old hotel, for instance, seems to have been reincarnated on the 16th floor of the new hotel, but you can’t always see it; what’s that about? To take another example, our narrator has transcendent — may I say otherworldly? — sex with a beautiful, high-priced prostitute (oh Haruki, I can’t quit you), who subsequently ends up dead, strangled with a black stocking. How does our narrator — a journalistic hack, who describes his job as “shoveling cultural snow” — afford such an exclusive call girl? Well, turns out he’s reconnected with a high-school friend of his who’s become a big movie star. (I pictured my friend Ben in this role — Ben of the million-watt smile and charm to match.) They’re hanging out, drinking, when the movie star suggests that they “get a couple of girls.” Yadda yadda yadda, so on and so forth, our narrator and the escort are washing up together. Soon enough she’s dead. What’s that about?

Often in these sorts of situations, Murakami would take the lazy route out: put some balls in the air, then walk off to see what’s on TV. Here he finishes the juggling routine. The result is an uncannily gripping story that’s also emotionally affecting. I can’t recommend it strongly enough.