Category Archives: Programming

Python: Associative Results with the MySQLdb library

This is more of a personal reminder as it’s not the default behavior as it is in most modern database libraries…

I’ve highlighted the important bits for associative results in white below

# Note the MySQLdb.cursors import statement
#    and the cursorclass declaration in the connect string.
import MySQLdb
import MySQLdb.cursors

oCursor.execute("select `field1`,`field2`,`field3` from `mytable`")

	LogString = ""
	oRow = oCursor.fetchone ()
	if oRow == None:
	sField1 = oRow["field1"]
	sField2 = oRow["field2"]
	sField3 = oRow["field3"]

The <pre> tag formatting above may be a bit difficult depending on your browser… but you should be able to copy and paste the entire codeblock with no difficulty.

Python Programming: Converting my old avi files to h.264

Here’s a little script that calls HandBrake‘s CLI interface to convert a whole directory full of media in a recursive manner.

No Instructions. No warranty. No guarantees. Your mileage may vary. Yadda Yadda Yadda.
Tested on Ubuntu and MacOS 10.6

Download it here or just read it (better to download it, since my blog removes the whitespace and hence the flow of the script):

# This script requires the HandBrake CLI program
# Download it at

# You’ll need to change this to fit where everything is on your system
sFromDirectory = “/home/jeff/Videos/”
sToDirectory = “/home/jeff/Desktop/converted_video_output/”
sFullPathToHandbrakeCLI = “/usr/bin/HandBrakeCLI”

# Don’t mess with anything below this…..
import os.path
import shutil

def ConvertFile(sPath, sFile):
global sToDirectory
global sFromDirectory
global sFullPathToHandbrakeCLI
sExtension = os.path.splitext( sFile )
sNewFileName = sFile.replace(sExtension[len(sExtension) – 1], “.m4v”)
sNewDirectory = sPath.replace(sFromDirectory, sToDirectory)
if sPath != “”:
sOldFullPath =  sPath + “/” + sFile
sOldFullPath =  sPath + sFile

if sPath != “”:
sNewFullPath =  sNewDirectory + “/” + sNewFileName
sNewFullPath =  sNewDirectory + sNewFileName

# Don’t re-encode if it’s already a m4v
if not os.path.exists(sNewFullPath):
if sExtension == “.m4v”:
# Copy it instead of re-encoding it…
shutil.copyfile(sOldFullPath, sNewFullPath)
sHandbrakeCommand = sFullPathToHandbrakeCLI + ‘ -i “‘ + sOldFullPath + ‘” -o “‘ + sNewFullPath + ‘” -v -m -E aac,ac3 -e x264 -q 0.65 -x ref=3:mixed-refs:bframes=6:b-pyramid=1:weightb=1:analyse=all:8x8dct=1:subme=7:me=umh:merange=24:filter=-2,-2:trellis=1:no-fast-pskip=1:no-dct-decimate=1:direct=auto’

def callback( arg, sDirectory, aFilenames ):
global sToDirectory
global sFromDirectory
print “Checking files in ” + sDirectory
sSubPath = sDirectory.replace(sFromDirectory, “”)
for sFile in aFilenames:
if sSubPath == “”:
sOldFullPath =  sDirectory + sFile
sOldFullPath =  sDirectory + “/” + sFile

if os.path.isdir(sOldFullPath):
sNewDirectory = sOldFullPath.replace(sFromDirectory, sToDirectory)
print “”
if not os.path.exists(sNewDirectory):
print “Making new directory: ” + sNewDirectory
print “”

if not os.path.exists(sToDirectory):
arglist = []

Updated (September 3rd): Fixed a directory recursion issue.

Tournament-Tracker.NET is in Release Candidate 1

Yesterday I went ahead and versioned up Tournament-Tracker to RC1. This was after I cleaned up the Stats pages, added the ability to add a “Free Game” with your Tournament-Tracker.NET Friends, and rudimentary support for campaigning (which I am running for our Warhammer Fantasy Build up here at Galaxy Comics).

Remember, anyone who joins now will have Comp Credit Accounts for creating Tournaments & Campaigns (and whatever is added in the future!)



Games Workshop FAQ Grabber (Python Script)

I’m nerding out on ya, sorry. Programmers and Script Monkeys only, as I’m not going to explain how to use this.

I’ve created a Python script that grabs all the latest 40K and Fantasy FAQ’s/PDF’s

Here’s the script:


import urllib
import sys,os

sGWURL = ""
sWarhammerFAQURL = ""
s40KFAQURL = ""
sLocalFantasyFAQPath = "./" # I Normally just use the full filepath to my Dropbox Folder on my Ubuntu box
sLocal40KFAQPath = "./" # I Normally just use the full filepath to my Dropbox Folder on my Ubuntu box

def GetData(sURL):
        oPage = urllib.urlopen(sURL)
        sPageData =
        return sPageData

def FilterOutFAQLines(sData):
        FAQs = list()
        aLines = sData.splitlines()
        for sLine in aLines:
                if sLine.lower().startswith("<a href"):
                        if sLine.lower().find(".pdf") > 0:
        return FAQs

def downloadFile(url,localfilename):
        webFile = urllib.urlopen(url)
        #olocalFile = open(url.split('/')[-1], 'w')
        localFile = open(localfilename, 'w')

def GetFile(sHREFLine, sDir):
        global sGWURL
        sURL = sGWURL + sHREFLine[sHREFLine.find('"') + 1:sHREFLine.find('"', 10)]
        sFileName = sHREFLine[sHREFLine.find('>') + 1:sHREFLine.find('<', 10)]
        downloadFile(sURL, sDir + sFileName)
        return sFileName

def DeleteFolderContents(folder):
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
                if os.path.isfile(file_path):
            except Exception, e:
                print e

aWarhammerFAQs = FilterOutFAQLines(GetData(sWarhammerFAQURL))
a40KFAQs =  FilterOutFAQLines(GetData(s40KFAQURL))

for sLine in aWarhammerFAQs:
        sFile = GetFile(sLine, sLocalFantasyFAQPath)
DeleteFolderContents( sLocal40KFAQPath )
for sLine in a40KFAQs:
        sFile = GetFile(sLine, sLocal40KFAQPath )

Feel free to download it here in case your copy/paste doesn’t work.

This won’t be very useful to non-programmer types, but it might save someone an hour or so if they wanted to do the same thing.

Ok I’m being drawn to Ruby (over Python)…

Lately I’ve been dabbling (and enjoying!) Python, but as of this weekend I’m being drawn to Ruby mainly because of several reasons (over Python):

  • The ability to easily set up and run a full blown MVC web application on Apache
  • I like the MySQL database interface better (I just finished a test and it was much more elegant than having to define a cursor, etc).
  • The ability to command line script is about the same, but I’d rather marry myself to as little programming languages as I can this late in life.
  • When I do return to the Mac platform Cocoa for Ruby has been praised
  • I’ll be eventually migrating my current Python projects to Ruby to see how much different or harder or easier it is to read and maintain the code.
  • My biggest beef with Python is having to define the functions before the code is run (I like to have my user functions at the bottom of the script and the logic at the top). Update: It seems as if Ruby has this limitation too….. 🙁 So it appears that I’ll just have to work on my coping skills.
  • If Python had a module similar to Passenger (for Apache module for Ruby) I wouldn’t be so quick to look at Ruby as I really like the language.


It seems that Passenger supports Python web development as well! *rubs chin* verrry interesting…

WARMACHINE: A little programming exercise….

This is a cross-post from my Miniature Wargaming side and my programmer side. Over the last week or so I’ve been stretching my Javascript & CSS muscles and basically made a mini-game loosely based on the WARMACHINE/HORDES mechanic.

There are more limitations than features at this point, and I’m not looking to make this a product so I don’t plan for it to go much further than what’s there now.

I used this little experiment to learn Javascript/DHTML interactions a little more familiarly–plus it helped a bit on my math skills as well.

What works perfectly: Nothing…maybe loading the page 😉

What sort of works: Movement, Targeting, Melee Attacking, Ranged Attacking, displaying info

What doesn’t work and I want it to before I’m done with the exercise: filling in of damage boxes, disable model when damage boxes are filled. Ability to add/edit/remove the default models with custom stats (saving is not an option as I’m not hooking it up with a backend).

What I don’t plan on doing: Boosting, cortex & weapon damage.

This won’t really teach anyone anything but the rolls of WARMACHINE, and there are no “turns”… it’s pretty free-form.

This only works in Firefox, Chrome and Safari as MSIE and Opera don’t support moz-transform and webkit-transform CSS for the image rotation. It does work on the iPhone but due to the touch interface and tiny screen, YMMV. If you get Javascript errors it may be me working on the code.

This was inspired by my WARMACHINE Mathhammer page mention on a previous blog post

The link to the mini game/environment is here

Addendum: This works great on an iPad (I don’t have one , but it’s getting more appealing every day). It’s a little wonky with the movement and rotation due to the touchscreen vs. mouse events, but it’s pretty freakin’ cool.