Recently I found it useful to implement a round-robin tournament. Here’s a little Python generator that produces schedules for you, for your enjoyment.

from collections import deque
def round_robin(size):
  if size < 2:
    yield []
    raise StopIteration

  teams = range(1, size)
  rounds = size - 1
  if size % 2:
    rounds = rounds + 1
  roster = deque(teams)
  half = (len(roster) + 1)/2
  for round in range(rounds):
    positions = [0] + list(roster)
    backwards = positions[::-1]
    yield [(positions[i], backwards[i]) for i in range(half)]

Christ. Do some people really agree with hateful vitriol like this?

There are about forty-eight things wrong with the representative’s tweet. Here are two that struck me fairly immediately.

First, no one I know was cowering. Boston is a tough city. As someone more eloquent than I has noted, Boston was founded “by people so badass that they needed to buckle their hats to keep them on their God damn heads.” A million people obeyed officials’ requests to stay put to make the search for a sadly misguided 19 year-old more effective and safer for those of us at home and safer for the brave folks who are performing the search. Bostonians are patient, dignified, and humane. We are not hysterical, blood-thirsty, or craven. We do not need individual arms to maintain order.

Second, no one I know thinks an AR-15 with high-capacity magazines would make the situation safer. Instead, I’m glad that my tax dollars go to support the heroes we call police officers, fire fighters, and first responders. And I’m thankful that these well-trained, lion-hearted men and women are willing to put their lives on the line so that I don’t have to. I am proud to be from Boston and I am proud of how our state, its officials, and our civic champions are handling the situation.

So, Nate Bell, as far as I can tell, the answer to your profane question is zero. Nobody was cowering. Nobody wanted an AR-15 with high-capacity magazines.

I support mandatory universal background checks, a ban on high-capacity magazines, and compassion. I am against senseless violence, acts of terror, and simpleminded legislators.

I feel this way, Representative, because guns don’t keep people safe. That’s why it takes so much courage to be a police officer, firefighter or first responder. Situations involving guns are dangerous. Guns are designed to cause injury. It seems like no one explained to you how guns work before.

I hope that you never feel like you need to cling to a gun for safety. The lonely individualism of your Tweet makes me sad. I hope you and your constituents do not feel alone or afraid without a gun. I am confident that my neighbors, community, and government are working hard to keep one another safe everyday—not just in times of crisis. I wish the same for you and your constituents.

Further, nonviolent community vigilance works. It resulted in a peaceful arrest tonight. Had a scared, armed individual taken justice into his own hands instead of calling the authorities for help, we would certainly have had one or more deaths on our hands. I am very pleased that entire Boston community worked together, acted dispassionately, and ended this string of tragedies without further casualty.

In case you don’t read my blog, Representative Bell, I have written you directly and and plan to call your office Monday so that you don’t need to wonder any more. For anyone who wishes to join me, here is his contact information:

Phone 479-234-2092

Here’s hoping that this crisis ends quickly and peacefully.

Recently I’ve been working on a congressional tweet aggregator to get a handle on what our legislators are saying. To make that easier to see, I figured I’d start adding some charts and lists and other snazzy dataviz gizmos that are so hot these days.

I like D3.js as a graphing library. It makes clean, interactive, data-driven charts a snap to make in just a few lines of Javascript. Then it does its magic to render the data in crisp SVG, which I am quite fond of. On my site, I wanted to turn the crank on the back-end for charts that don’t update all that frequently, inject them into my templates, and spare the viewers of my site the heavy-lifting required for multiple charts—not to mention my poor server that has to execute several complicated queries to do the appropriate counting to generate the data to back the charts.

After a little poking around on the internet, I stumbled on to PhantomJS, which bills itself as a full-stack headless WebKit. Perfect. It can ping my website periodically, load the chart pages, and extract the SVG, I thought.

Not so fast. The Phantom is excellent at reading SVG, and it’s even good at rendering it to PDF or PNG. But that’s not what I wanted! I just wanted it to spit out the SVG for me after D3 was finished making it, untouched. And since SVG elements don’t have an innerHTML property, I needed to think harder to find a solution; i.e., ask Google. But Google didn’t seem to know, either. So I wrote a tiny script to extract page elements by ID. Maybe one of you will find it useful, too.

var system = require('system');

if (system.args.length != 3) {
    console.log("Usage: extract.js  ");

var address = system.args[1];
var elementID = system.args[2];
var page = require('webpage').create();

function serialize(elementID) {
    var serializer = new XMLSerializer();
    var element = document.getElementById(elementID);
    return serializer.serializeToString(element);

function extract(elementID) {
  return function(status) {
    if (status != 'success') {
      console.log("Failed to open the page.");
    } else {
      var output = page.evaluate(serialize, elementID);
}, extract(elementID));

I’m starting to aggregate tweets from Congress on my own. Suggest some ways to organize and view the data here: Or at least hover over the map of the US. The states change color. And change is good.

Since I couldn’t find a list of twitter feeds from the US Congress, I made one today.

Now you can get a snap-shot of our legislators highest priorities, as captured in 140 characters at a time, at

In case you’re curious how I did it without painstakingly searching each congressperson’s name and username to add to my list by hand, I’ll let you in on my little my secret: I relied heavily on a few open source projects to automate the process. To find the Twitter IDs, I simply looked them up from the very excellent Github project unitedstates/congress-legislators. Then I used the Python Twitter Tools module to chat with the Twitter API to create the list and add all the legislators in bulk.

Life wasn’t exactly as easy as all that, though. I had to make a little tweaks in order to gather all the tweets. First, there is an easy-to-fix bug in the Python Twitter Tools package. You need to make sure it knows how to POST to lists/members/create_all command. Right now employs a GET request—and that doesn’t work. It looks like at least one other person has run into the same problem. If you run into the problem, you can read how I fixed it.

But Twitter didn’t handle my create_all request as they promised. The documentation claims you can add up to 100 users to your list at a time, but that wasn’t my experience. Instead, I could only get the API to add legislators 25 at a time. But that’s a small price to pay for democracy.

And this list is active! In the time it took me to write this post, the list reported 13 new tweets. Your tax dollars hard at work.

Wiser not wetter

While I’ve been training for the 1000-meter flatwater sprint all week, sadly, all of my workouts have been on land. The rental facility that I use stops issuing kayaks after 6pm this time of year. My work schedule keeps me from Cambridge into the mid-evening and therefore quite dry. I’ve been scheming ways to get onto the water in the early morning or later after I get back home, but until then, I’m bound to the gym. The weekends are another story, however. And to ready myself for tomorrow’s lesson, I returned to the river to practice on my own.

There was a bustle at Paddle Boston when I arrived around 11:30 am. A line emanated from the tent which guards the entrance to the dock where newcomers must sign waiver forms and hand over IDs. Another line wrapped around the small cabin that houses the cash register for paddlers who had just returned. No one looked too wet. And as a matter of course, a third line filled the docks which are already crowded by life jackets, paddles, and boats. Despite all of the people there, very few of them were workers. School is about to start and many of the staff are college students on summer vacation. With September just a few days away, most of the attendants have quit, leaving one exasperated woman to man the boats with only occasional help from her tiny dog.

Initially she told me to hop into a recreational kayak. I felt bad asking for a sea kayak instead; I didn’t want to be trouble. She let out something between a sigh and huff and disappeared for a moment. When she returned, I had a sky blue sea kayak. The fin on the bottom was exposed. She reached for the cord to retract it and mentioned to me, “This is how you pull in the.”

Skeg,” I interrupted to let her know that I was an insider, too.

“Yeah,” she replied. Her pace was a little slower and tone a little warmer than before. “Well, get in. I’ll push you in water from here since there’s such a line.” Trying not to sour my new friendship, I did as she said silently and swiftly. I signalled my readiness with a brief nod.

“Well, aren’t you going to adjust your foot pegs?” she asked. To be honest, I didn’t remember how far down the pegs were supposed to be. During my lesson the week before the instructor had adjusted them for me. My feet were on them. And that seemed right. So, I replied quickly, “They feel good.” What a mistake.

Once I was in the canal, the winds seemed to kick me side to side. The boat tottered beneath me in reponse. My abs clenched. For a moment, I forgot to breathe. And then I began what I could remember of the forward stroke. Toe-to-hip. Turn to the other side. Toe-to-hip. Turn and repeat. Somehow I was more unsure of myself than I was my first time out. The water was less familiar and I was more afraid of falling in. Still, I inched out of the canal.

Now in the open Charles, I suddenly realized that my right foot was up further than my left. And I remembered how I was supposed to sit in the kayak: somewhat frog-legged, with knees pushing on the braces on either side of the hull under the coaming. Damn. My foot pegs were too far down and uneven, and I could already feel my hips straining. I headed upstream under the Longfellow Bridge toward the only landing I could remember, up near the Harvard River Houses and Week’s footbridge, where I could stop to rearrange the pegs.

The entire time, my boat kept lurching to the right. I thought it might be the wind pushing me to one side. The week before, the entire class kept floating to toward the shore as a pack. I put my paddle down to check which direction the currents would take me. To the left! “Ah, so it is me,” I thought. My paddling was so lopsided, it overcame the wind. Every few strokes I paused to right my course. It was those mismatched and misplaced pegs. I picked my knees up higher against the boat. That seemed to help. I looked around at the other craft on the water. Everyone else appeared to be going straight. Then the wind picked up again.

It’s really amazing how low to the water you are in a kayak. Waves that you would never bother to notice from land suddenly command your attention by force. It was hard for me to gauge their size, a few inches, possibly a foot but probably less. But when you’re only three feet above the water, ripples become mountains. After being batted to the side by a small caravan of waves, an old Anglo-Saxon poem the Seafarer popped into my mind. When I discussed it in a waterless meeting room for a college course on Old English poetry years ago, my analysis was sharp. With all the comfort and courage that only cowards could have, I judged the author and his culture as small and afraid. They believed in monsters; I did not. But there, floating alone in my 13-foot boat, all that dross about the grim cold ocean and terrible tossing of the waves and unforgiving gale started to make sense—despite its being a tame New England summer day.

I turned around and headed home, still lurching to the right. This time with help from the wind.

Class is at 8:30 tomorrow morning.

Love that Dirty Water

Today marks the beginning of my Olympic career. This morning I went to Charles River Canoe & Kayak for the first of two introductory lessons on paddling. The class began at 8:30am on one of the small lawns that punctuate the Kendall Square biotech ghetto. There our instructor, Bob, led eight nervous adults through basic kayaking anatomy, including rudimentary rescue techniques.

Before long we were on the docks and in our boats. After a quick adjustment of the foot rests we were in the water practicing our forward strokes, side sweeps, backward sweeps, J-leans, bracing and edging. Our three-hour tour of the canal ended with three water rescues. I demonstrated flipping and re-entry first. Soon enough, I want to learn to roll. (I may need stronger obliques, though.)

With enough practice, hard work, and friendly support, I think I can make my splash in the world of competitive paddling within three years. Dear readers, kindly keep me honest. Look for me on the River again, tomorrow after work but before sunset.

All this Olympics has inspired me. I’ve decided to train for the summer games in Rio and to pursue my hobbies in full force. The former requires me to learn to kayak; the latter, to program, program, program.

I’m building a fun web-app game on top of Django. And I want to make it dance with a little Javascript. I really like that I can look up the URLs of my pages by an internal name in templates using the {% url %} tag, but unfortunately that functionality isn’t available to me inside my static media—particularly, I’d like to be able to reverse look-up URLs in my site’s javascript, but I don’t want to have to render the file each time it gets served.

After hunting around for a while, I figured, “Why not just render to Javascript once, fill in all the links, and be done with it?” So that’s what I did. And it doesn’t take much.

I wrote a custom command called populate_urls that consumes a template (in this case, my Javascript) and spits out the finished product with all the holes filled in by Django and its handy URL resolvers. Then I stash its output in my static directory and pretend the whole thing never happened.

from __future__ import print_function

import sys

from import BaseCommand
from django.template import Template, Context

class Command(BaseCommand):
from __future__ import print_function

import sys

from import BaseCommand, CommandError
from django.template import Template, Context

class Command(BaseCommand):
  args = '<input.template> <output.ext>'
  help = 'Populates the URLs in the template. If no output filename is supplied, renders the template to standard out.'
  traceback = True
  def handle(self, *args, **options):
    if len(args) < 1:
      raise CommandError("You must supply a template.")

    with open(args[0], 'r') as templatefile:
      template = Template(
      context = Context()

    with sys.stdout if len(args) < 2 else open(args[1], 'w') as output:
      print(template.render(context), file=output)

Happy new year. Here’s the latest politically-minded letter I’ve sent: it’s to Richard Cordray, the new director of the Consumer Financial Protection Bureau. You’ve missed several other letters since my last post. I’ll try to be more faithful about recording them here.

You can send a letter of support, inquiry, or disdain through this form. I sent my message in a card from Elizabeth Warren, though.

Dear Director Cordray,

I’m glad your appointment to the CFPB went through. Please accept my warmest congratulations.

I hope you will direct this agency to take action on behalf of all Americans—be they poor or wealthy, young or old, unemployed or working. All of us need people in a position of action to represent our best interests and redress large, national damages caused by greed and deceit run out of control.

I would be especially happy if your agency would think of and suggest ways the public can be more civically involved in consumer financial protection. Washington and those that work there seem far away to many Americans. Please include us in the process; bring Washington nearer to the people.

To a happy a new year,
Joshua Reyes
A concerned but optimistic citizen

Recently this morning, Chris Hayes reported on a memo to the American Bankers Association, a lobbying group which aims to influence law-makers to make laws that favor, well, the banks. Read a copy of it for yourself. (A scanned PDF courtesy Chris Hayes, a searchable plain-text version.) This thing sounds like something straight out of a conspiracy theory story, but the ABA confirm they’ve received it. So, sadly, I guess this is the real deal.

The memo summarizes in very plain language how big-time propaganda systems work. You pay us a lot of money to cook up dirt, spin our cause until it’s palatable for the majority, and then mobilize the masses against their own interests to support ours, stamping out grassroots campaigns and bullying politicians who might stand in the way as we go.

The point of this memo is clear: the Occupy Wall Street movement reminds people who were hurt by the financial crisis that the banks and their lobbying for massive deregulation are very responsible for the economy’s sorry state—a fact attested by the Financial Crisis Inquiry Report; consequently the banks need to protect their political interests and get ready to for the upcoming elections.

There were a few things that stood out to me. First, the entire tone of the memo pitches a clear the-banks-and-our supporters-versus-everyone-else mentality. The memo explicitly names who the “and our supporters” are. According to this memo, bankers could, for some indefinite period of time, count on members of the Republican party to defend the interests of Wall Street companies. They’re worried that political pressure from groups like Occupy might change the tide. Here’s the full paragraph that reads all too transparently. (The emphasis is my own.)

It shouldn’t be surprising that the Democratic party or even President Obama’s re-election team would campaign against Wall Street in this cycle. However the bigger concern should be that Republicans will no longer defend Wall Street companies—and might start running against them too.

As it’s stated, you might think that it’s common knowledge that the Republicans have been defending the banks. The danger is that they might stop. That is, unless you pay us to manipulate the American people. What’s worse, though, is how entirely remorseless these guys are. They even go out of their way to point out that many Americans who were hit hard by the recklessness of the banks are going to have a lean holiday season. Why is this bad? It might alter their vote.

This combination [of frustration on the political left and right] has the potential to be explosive later in the year when media reports cover the next round of bonuses and contrast it with stories of millions of Americans making do with less this holiday season.

Yikes. Which is more important, banker bonuses or the millions of Americans who are suffering because of a economic collapse created by large financial institutions aided by intense governmental deregulation? The authors say which side they’re on and they presume the reader feels the same way.

The second thing that’s really interesting to me in this memo is actually somewhat prophetic, and not just because they dated the memo by about a week in the future. The quotes I gave above already hinted at this point: right, left, it doesn’t matter, everyone is upset with the banks. And everyone is a lot of people. That’s Occupy’s mantra, right? We are the 99%. And in case you forgot, that’s a big number.

Well-known Wall Street companies stand at the nexus of where OWS protestors and the Tea Party overlap on angered populism. Both the radical left and the radical right are channeling broader frustration about the state of the economy and share a mutual anger over TARP and other perceived bailouts.

So this recent op-ed by Sarah Palin in the Wall Street Journal must have been terrifying. (I suggest you read it, it’s surprisingly sane even if it is essentially a plug for one of her staffer’s books.) Palin basically decries lobbying, or at least wants to make the process more transparent, and suggests specific solutions— make Congress subject to the Freedom of Information Act, for example. I can’t tell if she actually believes what she’s written, but many of her ideas have good potential.

By the end of the editorial, Palin starts to show her “maverick” roots and this time in a somewhat profound way. She reaches out to the Occupy movement to say, look, we’re not so different. Wall Street is bad. Their deep pockets can buy votes. Their predatory lobbyists are good at their jobs. They fight for big corporate interests that aren’t aligned with American people. Turn your attention on the politicians who receive these gifts. You have the power to act. I wish she had gone a little further and actually said, “Vote.” In Palin’s own words:

This call for real reform must transcend political parties. The grass-roots movements of the right and the left should embrace this. The tea party’s mission has always been opposition to waste and crony capitalism, and the Occupy protesters must realize that Washington politicians have been “Occupying Wall Street” long before anyone pitched a tent in Zuccotti Park.

And that’s exactly the sort of message this CLG&C memo warns against: political action from all sides for financial reform and regulation. It seems the Occupiers have caught on, too. They’re running commercials on ESPN and, wait for it, the O’Reilly Factor. I wonder whether these two groups will coalesce. Until then, watch the commercial here.

The third thing that jumped out at me is that the banks shouldn’t just be afraid of the ideas of Occupy, but of Occupy itself.

It may be easy to dismiss OWS as a ragtag group of protestors but they have demonstrated that they should be treated more like an organized competitor who is very nimble and capable of working the media, coordinating third party support and engaging office holders to do their bidding. To counter that, we have to do the same.

Clark, Lytle, Geduldig & Cranford promise to dig up dirt on Occupy leaders and undermine them, and therefore the movement they stand for, with a smear campaign. This might be trickier than they let on. The Occupy movement doesn’t, at least to me, appear to have a central leadership that outsiders like me can point to. Every time I see or read an interview I get a new face. It’s easier to discredit a handful of well-known, well-associated leaders. It’s next to impossible to pull records on an amorphous collection of anonymous demonstrators. Isn’t what that V movie was all about, after all? I hope the folks at Occupy resist the urge centralize their PR. Their relative anonymity is one of their strongest assets. That and the fact that the general tenets against corporate and political corruption are right.

So this memo suggests conventional print, radio and TV ads to combat negative bank press, as well as monitoring and leverage of social media sites. Sure. That’s usual, but they had one more idea that was a little shocking to me. It goes by the name of coalition planning. Since no one will trust the banks, these guys will hire and plant community leaders to plan and organize public support for the banks, but secretly. No one should know that they’ll be taking orders from the banks and doling them out to their unsuspecting supporters. It’s like making prisoners dig their own grave and smile about it! Here’s what ABA would get if they signed up with these guys:

Individual companies under threat by OWS and its adoption by Democrats likely will not be the best spokespeople for their own cause. A big challenge is to demonstrate that these companies still have political strength and that making them a political target will carry a severe political cost.

We will produce a report identifying traditional and non-traditional allies, intellectual support and politically important economic footprints that could ultimately form the basis of a broad coalition (rather than the narrow D.C. definition of a coalition) who can help carry our messages and organize supporters.

Notice how threatening their language is. These guys are not fooling around.

A strong placement [of paid advertisement that "combat OWS messages and provide cover for political figures who defend the industry"] early in a transition to adopt the OWS movement will send a powerful political signal about the risks of carrying that through.

We need to show politicians that if they stand for the American people and against corporate greed, we will stand for them during elections. Write to your senators and congresspeople to tell them what is important to you and why you will vote.

« Older entries