Archive for the ‘Programming’ Category

Methinks it is [still] like a weasel

Friday, March 18th, 2011

Full screen version


A couple of years ago I created an online Javascript version of Dawkins’ Weasel program. I was poking around at the code today and realised that it wouldn’t be too much work to remove some of its limitations to allow it to replicate the full 28 character phrase that Dawkins used.

If you’re unfamiliar with why anyone would want to make an program like this, take a look at the original post where I explain how genetic inheritance combined with natural selection gives vastly different results to the mistaken creationist view of evolution being a ‘monkeys with typewriters’ kind of randomness. (by the way, if you change the settings so that there is only one child per generation the program will enter ‘monkeys-with-typewriters mode’).

The main differences in this version are:

  • You can now hide or show all the mutant children that were not selected
  • You can use up to 30 uppercase A-Z letter plus spaces
  • There’s a new column that shows how many letters matched (so you can see how it occasionally slips back with higher mutation rates – contrary to what William Dembski would have you believe)
  • I’ve improved the performance slightly.

Search and Replace PHP split() with Python

Tuesday, May 4th, 2010

A couple of days ago I upgraded to Ubuntu 10.04 which, in turn, upgraded my PHP version from 5.2 to 5.3. In PHP 5.3 they have completely deprecated the use of the split() function in favour of explode(). I did a quick search in my /work directory and it turns out that I have 832 files that are affected by this. All of them need to have split() replaced with explode() or the websites will throw errors every time they encounter it.

Here’s how I did it using an altered Python script I wrote a couple of years ago:

#!  /usr/bin/python
import os
import re

mydir = "/home/damian/work"

def doReplace(filePath):
	fin = open(filePath, "r")
	s = fin.read()
	fin.flush()
	fin.close()
	p = re.compile('(\s|\(|=)split\(')
	if p.search(s):
		fout = open(filePath, "w")
		s = p.sub(r'\1explode(', s)
		fout.write(s)
		fout.close()

for root, dirs, files in os.walk(mydir):
	for f in files:
		name, ext = os.path.splitext(f)
		if ext == '.php':
			doReplace(root + '/' + f)

(**UPDATE** I’ve switched the search and replace to use regular expressions because I found that ‘split()’ can be prefixed by a number of symbols but not others — i.e. don’t replace ‘preg_split()’)

Save multiple images to a PDF in Linux

Friday, December 4th, 2009

Place all the images you want in the PDF into a new directory and in the console run the following from within that directory:

convert * mynewfile.pdf

The powerful convert command uses the ImageMagick library which can be installed (in Ubuntu) with the following console command:

sudo apt-get install imagemagick

How to delete all .svn directories

Thursday, July 30th, 2009

In Linux, if you want to remove all .svn files and folders within a directory, navigate to the directory in your terminal and use:

find . -name ".svn" -type d -exec rm -rf {} \;

Credit

Programming with VIM

Tuesday, July 28th, 2009

vim

For years now I’ve used IDEs like Visual Studio and Eclipse occasionally falling back to plain text editors like GEdit or Notepad2 when making quick changes. I’ve been running Linux for almost three years now and, as you do when dealing with remote servers, have sometimes had to edit text files via the console using VIM.

VIM has been around for 18 years and is an extended version of VI which has in turn been around for 33 years. VIM = VImproved. It’s a console-based text editor designed on the assumption that you will only ever be using your keyboard (kiss your mouse goodbye) which means that much of the most common functions are based around the home keys (‘asdf’ and ‘jkl;’) and it’s packed with great programming features.

But the learning curve is about the steepest I’ve ever come across.

I decided a couple of months ago to make an effort to get to grips with it and it took a good four weeks before I was matching the programming speed I was used to with Eclipse. But now I’m finding that my speed is continuing to increase and there is no way I can go back now. It’s not the be-all-and-end-all though; if you are writing a document from scratch (like this blog entry) then VIM doesn’t really have much to offer but if you are editing an existing document (as you often are when programming) it’s streets ahead of IDEs and text editors.

One of the hardest things to get your head around is the fact that VIM is modal which means that you switch between typing stuff and doing stuff to existing text. By default you are not in ‘typing stuff’ mode and so when you type the letter w it’ll skip to the next word. If you want to add text you have to press i and then press Esc after you’ve finished to go back to ‘doing stuff’ mode. For example, to copy an entire line, paste it below, move to the new line, skip three words along, delete the remaining text on the line and start typing, in VIM you would type yy, p, 3w, c$ but the equivalent in a text editor would be to press Shift-End, Ctrl-C, End, Return, Ctrl-V, Home, Ctrl-Right, Ctrl-Right, Ctrl-Right, Shift-End, Delete and then start typing. Those key combinations may seem strange but, once you are used to them, they make a lot more sense than having to constantly move your hands away from the home keys. Especially on a laptop!

VIM is free, open source and is available for AmigaOS, Atari MiNT, BeOS, DOS, MacOS, NextStep, OS/2, OSF, RiscOS, SGI, UNIX, VMS, Windows, FreeBSD and Linux. If you are a programmer or edit plain text on a regular basis I recommend you give it a go but be aware that the curve is about as steep as curves get. If you decide to try it out I can also recommend this website to get you on your feet.

The Monty Hall Problem

Thursday, March 19th, 2009

Monty HallIf you’ve never heard of the Monty Hall Problem before, here is a brief summary.

You are in a game show where you are faced with three closed doors. Behind one of the doors is a brand new car and the other doors hide a goat each. You then choose a door in an attempt to win the car but before the door is opened the host (Monty Hall) opens one of the remaining doors he knows contains a goat. You are then given the opportunity to choose whether to stay with your original selection or switch to the other, remaining closed door.

Intuitively most of us tend to think that it doesn’t really matter because we think there is a 50/50 chance either way but the reality is that statistically you have a greater chance of winning the car if you switch. In fact you stand a 2/3 chance of winning with the switch strategy as opposed to a 1/3 chance with the stay strategy.

If you remain unconvinced feel free to try it out for yourself with a friend or a die and a piece of paper.

Anyway, the point of this post is to say that in the two years or so that I’ve known about this I’ve never heard a concise and easy-to-understand explanation for why this is so. But now I have one…

You have a 2/3 chance of selecting a goat instead of a car. This means that two thirds of the time Monty Hall will reveal the last remaining goat which means that two thirds of the time if you use a switch strategy you will win.

To highlight how this works, imagine the same scenario but with 1000 doors and only 1 car. You have a 1/1000 chance of selecting the car or a 999/1000 chance of selecting a goat. If Monty Hall opens 998 other doors with goats behind them it is extremely likely (999/1000) that the last remaining door will have the car. (Thanks A3!)

You have two strategies: switch or stay. Using the stay strategy, if you accidentally choose a car first off (1/3 chance) you will win but if you choose a goat (2/3) you’ll lose. Using the switch strategy you’ll reverse these odds giving you statistically a 66.6% chance of winning every time.

Simple huh?

Disable WSDL caching in PHP

Monday, September 22nd, 2008

If you are finding that your SOAP web service isn’t updating when you make changes you have to add the line ini_set("soap.wsdl_cache_enabled", "0"); to both the Server and the Client.

i.e.

<?php
class SoapController
{
 function HelloWorld($name)
 {
  return "Hello ". strrev($name) ;
 }
}
ini_set("soap.wsdl_cache_enabled", "0");
$server = new SoapServer('http://example.com/soap.wsdl');
$server->setClass("SoapController");
$server->handle();
?>

and

<?php
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient('http://example.com/soap.wsdl', array('trace' => 1));
print_r($client->HelloWorld("Damian"));
?>

Escaping a Plus in Javascript

Friday, September 19th, 2008

I got stuck trying to send a string that contained a “+” via Javascript to a Flash component. Using “escape()” didn’t help as it continued to come through as a space. The workaround I discovered is to use “encodeURIComponent()” instead.

Pointy

Tuesday, September 16th, 2008

I do web development for a living. Almost two years ago I made the switch from being almost exclusively Microsoft and .NET to open source and along the way had to learn PHP (and a bit of Python for a while there too).

I’ve played around with many different web frameworks and been frustrated that they often force you to learn an alternative to SQL and/or some kind of restrictive templating language as well as the fact that most of them are too cumbersome for the types of sites that I’m generally required to produce.

So, for the last six months or so I’ve been refining my own MVC web development framework with the goal of keeping it lightweight, high performance and only using standard PHP and SQL where needed. And most of all, open source.

I present my baby, Pointy (the tiny but sharp development framework), which I’ve made available under a Creative Commons license. If you’re a PHP developer and you want to dabble with Pointy, please feel free to pay a visit, download it, play with it and if you find it useful go ahead and use it. I hope it’s as useful to you as it has been to me.

Calculate Your Blogging ROI

Friday, May 9th, 2008

Ever wanted to know what blog posts you write require the least effort and get the most comments? No? Well I did and I threw together a bit of SQL to help me identify the areas I can improve upon if I’m to become a serious challenger for the title of the Laziest Blogger Ever™:

SELECT p.post_title, ROUND((SUM(LENGTH(w.comment_content))/LENGTH(p.post_content))*100) AS roi, LENGTH(p.post_content) AS post_length, SUM(LENGTH(w.comment_content)) AS comment_length FROM blog.wp_posts p INNER JOIN blog.wp_comments w ON w.comment_post_ID = p.ID GROUP BY p.ID ORDER BY roi DESC LIMIT 10

It returns the top 10 blog posts ranked by the percentage return on a post measured by the number of characters invested in the opening post compared to the number of characters returned in the comments.

My top 3:

  1. Free Will (43,774% ROI)
  2. Last Western Heretic (5,304% ROI)
  3. The Location of Jesus (5,223% ROI)