Welcome ! This is the personal site / blog of Graham King. Most people come for the credit card generator, but I think the Categories (top right) are more interesting.

November 16, 2011

Pretty command line / console output on Unix in Python and Go Lang

Posted in Software at 02:17 by Graham King

There are lots of easy ways to improve the output of your command line scripts, without going full curses, such as single-line output, using bold text and colors, and even measuring the screen width and height.

The examples are in Python, with a summary example in Go (golang) at the end.

Single line with \r (carriage return)

Instead of printing a \n (which most ‘print’ methods do by default), print a \r. That sends the cursor back to the beginning of the current line (carriage return), without dropping down to a new line (line feed).

import time, sys
total = 10
for i in range(total):
    sys.stdout.write('%d / %d\r' % (i, total))
    sys.stdout.flush()
    time.sleep(0.5)
print('Done     ')

Read the rest of this entry »

November 3, 2011

On why hackers don’t work on large teams

Posted in Society, Software at 01:05 by Graham King

We’ve know for over 35 years that “adding manpower to a late software project makes it later”. Amazon has it’s two-pizza team heuristic: “If a project team can eat more than two pizzas, it’s too large”. The excellent Code Complete has a detailed explanation of how communication costs increase with team size. Yet we still need reminding.

Dhanji R. Prasanna has an excellent retrospective on his time on the Google Wave team. He sums up the problem with big teams very well:

And this is the essential broader point–as a programmer you must have a series of wins, every single day. It is the Deus Ex Machina of hacker success. It is what makes you eager for the next feature, and the next after that. And a large team is poison to small wins. The nature of large teams is such that even when you do have wins, they come after long, tiresome and disproportionately many hurdles. And this takes all the wind out of them.

For me, that’s really the crux of it. As a programmer, it kills you to not get stuff done. Large teams necessarily involve more communication, more complexity, and less getting stuff done. Large teams are a programmers equivalent of retirement.

November 2, 2011

Machiavelli on Occupy Wall Street

Posted in Society at 23:25 by Graham King

Reading Machiavelli’s The Prince, his advice seems just as relevant today. In On the civil principate he writes:

In every city there are two different humours, one rising from the people’s desire not to be ordered and commanded by the nobles, and the other from the desire of the nobles to command and oppress the people.

You cannot satisfy the nobles honestly and without harming others, but you certainly can satisfy the people. In fact, the aim of the common people is more honest that that of the nobles, since the nobles want to oppress others, while the people simply want not to be oppressed.

The Prince must always live among the same people, but he can do very well without a particular set of noblemen.

Substitute nobles with the 1%, and substitute Prince with President, and you get the advice he would probably give today.

October 25, 2011

Ad-blocking your iPad

Posted in Software at 01:01 by Graham King

Monitoring iPad network traffic, and blocking advert download.

An article on monitoring iPhone traffic by Craig Dunn got me wondering what the iPad is sending over the wire. That led me to blocking many of the adverts apps show. Here’s how.

1. Setup a proxy (squid on ubuntu)

First you need to setup a proxy, and send all your iPad’s network traffic through that. On Ubuntu squid is easy to setup: sudo apt-get install squid

Read the rest of this entry »

September 27, 2011

Finding memory leaks in Python with objgraph

Posted in Software at 01:37 by Graham King

After a frustrating time trying to find a memory leak in my Python code with guppy / heappy hpy, I tried objgraph and, wow, it makes it so easy! Here’s what you do:

pip install objgraph

At the relevant point in your code, add an import pdb; pdb.set_trace() to drop into the debugger. Then just follow the docs on finding memory leaks with objgraph. In short you do:

>> import objgraph
>> objgraph.show_growth(limit=10)   # Start counting

Ignore that output. Call the function that leaks memory, iterate once through you loop, whatever you need to do to make your program consume more memory. Now call show_growth again:

>> my_leaky_func()
>> objgraph.show_growth(limit=10)   # Stop and show change

This time it shows the difference between now and the last time you called it. Those extra objects are the problem.

Finally you need to find where the reference to those leaky objects is being held:

>> import inspect, random
>> objgraph.show_chain(
...     objgraph.find_backref_chain(
...         random.choice(objgraph.by_type('MyBigFatObject')),
...         inspect.ismodule),
...     filename='chain.png')

That generates a lovely graph in your current directory, showing the ownership chain. Now wasn’t that easy? Thanks Marius Gedminas!

September 26, 2011

DjangoCon 2011: Psychology for your webapp

Posted in Behaviour at 17:32 by Graham King

I got to do a 5min lightning talk at DjangoCon 2011 in Portland. The full slides are in the BarCamp post.

I’m presenting a model for applying insights from psychology to your webapp users.

Psychology for your Webapp on blip.tvscroll to 15:45 for start of my talk.

September 18, 2011

Hostage Negotiation 101

Posted in Behaviour, Society, Strategy at 21:24 by Graham King

I recently finished Gary Noesner’s Stalling for Time: My Life as an FBI Hostage Negotiator, by the F.B.I.‘s former head of and founder of their hostage negotiation unit. The book is a great read (and I suspect heavily ghost-written). Here’s what I learnt:

Your goal as a negotiator is to get the target(s) (the person or people you are trying to arrest) to surrender peacefully to law enforcement.

Sometimes there are hostages, and then your priority is securing their release, but usually there are not. By getting them to put down their weapons and come out you are usually saving their lives, and also protecting your colleagues.

The last resort is an armed assault by the SWAT team. Prior to negotiation being taken seriously by law enforcement, this was the only option.

Make exclusive contact

First and foremost, you need to get in contact with them. Usually they are keen to talk, and most often you can use the phone line. Sometimes you have to get the SWAT team to bring them a field telephone. Sometimes you stand outside the window or at the foot of the stairs, and shout. And occasionally, as in the Beltway sniper case you have to ask the media to say things and hope the target hears.

Read the rest of this entry »

September 16, 2011

Cleaning up old git branches

Posted in Software at 20:14 by Graham King

After a while working with git, you end up with lots of branches, especially if you use git-flow inspired feature branches. Here’s one way to clean them up.

For any branch, I want to know whether it has been merged, when the last commit was, and ideally if the matching ticket in our tracker has been closed.

Switch to your main branch, usually develop or master: git checkout develop

List all the branches which have been fully merged into it:

git branch -a --merged

Read the rest of this entry »

September 15, 2011

Profiling Django for CPU bound apps

Posted in Software at 20:24 by Graham King

For most Django apps, indeed most webapps, the bottleneck is the database. The biggest gains usually come from reducing the number of queries used, and adding database indexes. django-debug-toolbar helps a lot here. After that, caching and de-normalization also help reduce database queries.

But what if your app is CPU bound? How do you find out where it’s spending it’s time? It’s easy with the runprofileserver from django-extensions – here’s how:

Read the rest of this entry »

August 11, 2011

Unicode in Python 2: Decode in, encode out

Posted in Software at 00:24 by Graham King

In Python 2 you need to convert between encoded strings and unicode. It’s easy if you follow these three simple rules:

Decode all input strings

name = input_name.decode('utf8', 'ignore')

You need to decode all input text: filenames, file contents, console input, database contents, socket data, etc. If you are using Django, it already does this for you, as much as it can.

Read the rest of this entry »

August 3, 2011

git: Resolving ‘git gc’ error: cannot lock ref

Posted in Software at 17:37 by Graham King

If you get an error like this from git::

Auto packing the repository for optimum performance. You may also
run "git gc" manually. See "git help gc" for more information.
error: cannot lock ref 'HEAD (xyz's conflicted copy 2011-06-02)'
error: cannot lock ref 'refs/heads/master (xyz's conflicted copy 2011-06-02)'
error: failed to run reflog

You just need to delete the offending files from .git/logs/ and run your operation again.

July 19, 2011

The death of Sean Hoare, whistleblower

Posted in Society at 06:53 by Graham King

The News International phone hacking scandal is the case of a British tabloid’s staff hacking into several thousand people’s voicemail, over a period of at least six years.

They listened to voicemail of the 7/7 terrorist attack victims, politicians, a murdered schoolgirl (including erasing some messages, leading the family to think she lived), the British Royal Family, various celebrities, and other journalists.

Read the rest of this entry »

July 7, 2011

Contributing to Django: quickstart

Posted in Software at 06:01 by Graham King

Instructions on how to setup a development environment to work on Django core, for example to review proposed patches, and prepare your own.

pip and virtualenv

Make sure you have pip, virtualenv, and virtualenvwrapper installed. On Ubuntu:

sudo apt-get install python-setuptools
sudo easy_install pip
sudo pip install virtualenv
sudo pip install virtualenvwrapper

Edit your .bashrc and add this line ABOVE any mention of /etc/bash_completion

source /usr/local/bin/virtualenvwrapper.sh

Close your terminal and re-open.

Django

Create a virtualenv for your Django development, and switch into it (your prompt should change):

mkvirtualenv --no-site-packages django-dev

Read the rest of this entry »

June 30, 2011

Kobo eReader Touch on Ubuntu Linux

Posted in Misc, Software at 22:22 by Graham King

Ten days ago, I received a Kobo eReader Touch for father’s day. It’s a lovely device. Here’s my impressions.

It’s a USB device.

  1. Plug it in to your Ubuntu machine (or probably any modern Linux distro). It shows up as a USB storage device.
  2. Drag and drop books in any supported format onto it.
  3. Unplug, switch on, read books.

It’s that simple. If you had a solid-state MP3 player (before your phone played them), this will feel familiar.

Read the rest of this entry »

May 20, 2011

Django class-based views are easy

Posted in Software at 16:49 by Graham King

Since version 1.3, Django has class-based views built-in. Here’s how to do it:

views.py

from django.views.generic.base import View
from django.http import HttpResponse

class MyView(View):
    def dispatch(request, *args, **kwargs):
        return HttpResponse('Hello World!', mimetype='text/plain')

urls.py

from myproj.myapp.views import MyView

 urlpatterns = patterns('',
      url(r'^$', MyView.as_view()),
  )

Tell me more

Docs are here: Official Django class based views documentation

Internally the as_view method creates a new instance of your class (thereby making things thread-safe), and passes the __init__ method anything you passed to as_view.

Instead of over-riding dispatch you might prefer to use the get and post methods, which get called when you’d expect.

What had me confused initially, is that they are refered to as class-based generic views. Yes the generic views are implemented like this, and you may benefit from sub-classing one of those instead of the bare-bones View, but you don’t have to.

April 30, 2011

My experience with django-mptt

Posted in Software at 00:57 by Graham King

In the past few months, I’ve inherited two projects which used django-mptt, a toolkit for adding trees to Django models. Here’s my experience so far:

mptt is full of magic

That’s both good and bad. Good because it does a lot for you. Bad because it’s difficult to find out what that is. By becoming an MPTTModel you magically get four new database fields, tens of methods, and a whole new manager, grafted on to your model.

The project is making an effort to reduce the magic, for example by switching from signals to method overrides, which simplifies things significantly.

Read the rest of this entry »

March 15, 2011

Improved Ubuntu notifications: gnome-stracciatella-session

Posted in Software at 19:34 by Graham King

If you are an active user of Ubuntu’s notifications, for example via lintswitch you may of noticed that they have two key problems, which are easily solved:

March 7, 2011

Elizabeth Yin: You don’t need a programmer, you need a market survey

Posted in Software at 07:24 by Graham King

These days, for most internet businesses, the number one challenge is customer acquisition and marketing — not building a website. The overwhelming majority of startups that fail don’t fail because their website didn’t work. They fail because not enough people used it. This means that as entrepreneurs, we need to do a better job of vetting our markets before even building anything. It’s just too much of a waste to build out things that people don’t want.

From Elizabeth Yin’s talk at Web 2.0 Expo.

The crux of her talk (the talk hasn’t happened yet, I’m extrapolating from the linked interview) looks to be that you probably don’t need to start building yet, and what that means is you don’t need a technical co-founder yet. You need to vet your market first. Here’s what she suggests:

Read the rest of this entry »

March 1, 2011

Running a Tor relay / node / server on Ubuntu

Posted in Society, Software at 07:29 by Graham King

Right now, for people like me who have access to servers, the single biggest benefit we can provide to society at large is by running a Tor relay. Tor provides anonymity to users of the Internet.

This page is about contributing to the network by running a relay (or server, or node – same thing). If you want to use Internet services anonymously, you probably want the Tor Browser Bundle.

There’s also general instructions on running a relay. Mine are specific to Ubuntu / Debian.

Install it from the official repository

Edit your sources list: /etc/apt/sources.list

Read the rest of this entry »

December 20, 2010

No managers, no meetings: Why working from home is so much more productive

Posted in Behaviour at 23:09 by Graham King

Jason Fried at a TEDx event, 17minute video.

The key concepts:

Ask people where they go to “get work done”, where they are at their most productive: They almost never say ‘the office’. Or if they do, it’s before or after hours.

Work is like sleep, it proceeds in cycles. You have to go through the light-sleep / light-work cycles to get to the meaty stuff. Every time you get woken up / interrupted, you start from scratch.

Read the rest of this entry »

« Previous entries Next Page » Next Page »