A few weeks back, I was talking with my friend Molly about personal domains and realized that her nickname, Bierface, was available. The exchange basically went like this:
Me: I should buy bierface.com and just put up a ridiculous picture of you.
Molly: You would have to do a slideshow. Too many gems.
So I did just that, switching randomly between 14 pictures every time the page is loaded. The laughs from it have been well worth the $10 spent purchasing the domain.
She started to question the randomness though. Here's what the code that loads each image looks like:
All we're doing is creating an empty
<img> element to use that path as the src for the image.
Since the image is loaded by your web client, this seemed like a great opportunity to learn the very basics of grabbing client-side data - I could write some code to repeatedly get which image was loaded in order to determine how random Math.random() truly is.
We're going to be using Ghost.py to simulate a WebKit client. Ghost.py requires PyQt or PySide, so you'll want to grab one of those, too. I'm on OSX 1.8.2 and using PySide 1.1.0 for Python 2.7, which you can get here. You'll also need to grab Qt 4.7, which you can find here.
Let's walk though the code:
- Load our libraries and create an instance of the Ghost class.
- The comment should explain this one - we're initializing a zero'd out dictionary called counts so that our first plot doesn't have an x-axis with just one value. Each key of the dictionary will correspond to one of the images.
- The for loop is used to run 1,000 simulations. My xrange usage is a little wacky because I'm using it to title and name the plots - typically xrange starts with 0 and runs up until the number specified (e.g. 1,001 will be the last loop, not 1,002).
This is the section that grabs which image was loaded by simulating a WebKit client with Ghost.py. This section does not get run on the first pass since we want to start with an empty plot.
- Load bierface.com into our page variable.
- Split the image string so that we just grab the image number loaded.
- Update our dictionary of counts for the given image.
- Finally, use ffmpeg to stitch our plots together into a video.
Math.random() is pretty random (though #7 is the clear loser in the video below). It's easy to think it's not when working with a small sample size, but it's clear the numbers start to even out as the sample size increases.