WinCacheGrind timing fix Sat Sep 26 17:41:27 2009
There is a reasonably well known bug with WinCacheGrind; when using cachegrind.out files produced by XDebug the times are out by a factor of ten. While it's pretty easy to mentally multiply the times by ten, times below 0.1ms aren't displayed; meaning you don't actually see the times for anything that took less than 1ms to execute.
I originally intended to modify the source code for WinCacheGrind and host a fixed version, but it would seem there is a file missing from the source code - and I don't know enough about Delphi to hack around it.
My alternate fix is a little PHP shell script that I've put in /usr/bin/wcgfix on my development box. It just multiplies all the times by ten.
#!/usr/bin/php
<?php
if (!isSet($argv[1])) die ("Usage {$argv[0]} <filename>\n");
$file = $argv[1];
$fh = fopen($file, 'r');
if (!$fh) die("Could not open file");
while (!feof($fh)){
$l = fgets($fh);
if (is_numeric($l[0])){
$p = explode(' ', $l);
$p[1] = $p[1] * 10;
$p[] = "\n";
$l = implode(' ', $p);
}
echo $l;
}
fclose($fh);
The timing lines in cachegrind.out files are in the format <line number> <execution time> <unknown>. None of the other lines in the file start with a number, which makes them pretty damn easy to dig out.
Typical usage would be something like:
# wcgfix cachegrind.out.borked > cachegrind.out.fixed
I admit, it's still a little bit of a pain. But until I manage to get this damn Delphi thing sorted, it will have to do!
I originally intended to modify the source code for WinCacheGrind and host a fixed version, but it would seem there is a file missing from the source code - and I don't know enough about Delphi to hack around it.
My alternate fix is a little PHP shell script that I've put in /usr/bin/wcgfix on my development box. It just multiplies all the times by ten.
#!/usr/bin/php
<?php
if (!isSet($argv[1])) die ("Usage {$argv[0]} <filename>\n");
$file = $argv[1];
$fh = fopen($file, 'r');
if (!$fh) die("Could not open file");
while (!feof($fh)){
$l = fgets($fh);
if (is_numeric($l[0])){
$p = explode(' ', $l);
$p[1] = $p[1] * 10;
$p[] = "\n";
$l = implode(' ', $p);
}
echo $l;
}
fclose($fh);
The timing lines in cachegrind.out files are in the format <line number> <execution time> <unknown>. None of the other lines in the file start with a number, which makes them pretty damn easy to dig out.
Typical usage would be something like:
# wcgfix cachegrind.out.borked > cachegrind.out.fixed
I admit, it's still a little bit of a pain. But until I manage to get this damn Delphi thing sorted, it will have to do!
Dynamic callbacks for PHP's usort Thu Sep 24 16:41:28 2009
I recently wrote a blog post on a couple of PHP5.3's new features. As you may have noticed, I was really clutching at straws with my example use-cases. To make up for that, I have come up with a more realistic example of when you might want to use closures.
I seem to end up using multi-dimensional arrays quite often. Whatever the reason for that, sooner or later I need to sort them. In the past, I have just defined a callback function for use with usort(), but that has a lot of drawbacks.
If I am to successfully explain what the hell I'm on about, we will be needing some test data... Oh look! Here it comes now! Five different types of fruit in a multi-dimensional array.
<?php
$fruit = array(
array('number' => 1, 'name' => 'apple', 'color' => 'red'),
array('number' => 2, 'name' => 'orange', 'color' => 'orange'),
array('number' => 3, 'name' => 'pear', 'color' => 'green'),
array('number' => 4, 'name' => 'grape', 'color' => 'red'),
array('number' => 5, 'name' => 'peach', 'color' => 'peach')
);
Come to think of it: we will be needing a nice way to tell people what fruit we have and in what order. Here's a dead simple function for doing just that:
<?php
function printItems($items){
foreach ($items as $item){
echo implode(', ', $item) . "\n";
}
}
Let's give it a whirl!
<?php
printItems($fruit);
//Outputs:
//1, apple, red
//2, orange, orange
//3, pear, green
//4, grape, red
//5, peach, peach
Of course, when we print our original array it comes out in the order we defined it.
I'm a bit picky. I don't really want to tell people about my fruit in the order I thought of them. I'd much rather they were in alphabetical order. PHP doesn't have a native way to do that, so we need to define a sorting function and use usort() to do it.
<?php
function sortByName($a, $b){
return strCmp($a['name'], $b['name']);
}
The sorting function is used as a callback by usort(). It is given two elements from the array at a time; returns zero if they are the same, less than zero if the first one should come before the second, and more than zero if the second one should come before the first. Lucky for us, PHP's strCmp will do such a thing for us if we just want a string comparison; we just have to tell it which key we want to use.
<?php
usort($fruit, 'sortByName');
printItems($fruit);
//Outputs:
//1, apple, red
//4, grape, red
//2, orange, orange
//5, peach, peach
//3, pear, green
There is a problem with this however. If I wanted to then sort my fruit alphabetically by colour instead of by name, I would have to define a sortByColor() function. If I wanted to sort them by number, I would have to define a sortByNumber() function; and so on and so fifth.
What I need is a function that I can tell what I want to sort by. Before PHP5.3's introduction of closures that would have been possible, but tricky - maybe even ugly. PHP5.3 makes it trivial - maybe even elegant.
Behold, the sortBy() function!
<?php
function sortBy(&$items, $key){
if (is_array($items)){
return usort($items, function($a, $b) use ($key){
return strCmp($a[$key], $b[$key]);
});
}
return false;
}
The input array $items is taken by reference and sorted with usort(). The callback function is created on the fly with a closure, useing the $key provided.
Let's try it out!
<?php
sortBy($fruit, 'name');
printItems($fruit);
//Outputs:
//1, apple, red
//4, grape, red
//2, orange, orange
//5, peach, peach
//3, pear, green
sortBy($fruit, 'color');
printItems($fruit);
//Outputs:
//3, pear, green
//2, orange, orange
//5, peach, peach
//4, grape, red
//1, apple, red
It's alive! IT'S ALIIIVE! Well, it works anyway. There's still a little something missing though.
What if I want to sort my fruit in descending order instead of ascending? That's actually a pretty easy change. All I need to do is add an option to invert the output of the strCmp() function.
<?php
function sortBy(&$items, $key, $descending = false){
if (is_array($items)){
return usort($items, function($a, $b) use ($key, $descending){
$cmp = strCmp($a[$key], $b[$key]);
return $descending? -$cmp : $cmp;
});
}
return false;
}
sortBy($fruit, 'number', true);
printItems($fruit);
//Outputs:
//3, pear, green
//5, peach, peach
//2, orange, orange
//4, grape, red
//1, apple, red
Magic! I can now sort by any key I want, in any direction I want. I've never been so happy.
Those of you have been paying attention may have noticed the fatal flaw in my use of strCmp(); I know - I'm one of the people who have noticed. If you want to sort by a numeric value, strCmp() would tell you that 20 comes before 3, and that 70 comes after 400 etc, because it does a string comparison.
This is a problem I intend to address in a blog post coming soon. Stay tuned!
I seem to end up using multi-dimensional arrays quite often. Whatever the reason for that, sooner or later I need to sort them. In the past, I have just defined a callback function for use with usort(), but that has a lot of drawbacks.
If I am to successfully explain what the hell I'm on about, we will be needing some test data... Oh look! Here it comes now! Five different types of fruit in a multi-dimensional array.
<?php
$fruit = array(
array('number' => 1, 'name' => 'apple', 'color' => 'red'),
array('number' => 2, 'name' => 'orange', 'color' => 'orange'),
array('number' => 3, 'name' => 'pear', 'color' => 'green'),
array('number' => 4, 'name' => 'grape', 'color' => 'red'),
array('number' => 5, 'name' => 'peach', 'color' => 'peach')
);
Come to think of it: we will be needing a nice way to tell people what fruit we have and in what order. Here's a dead simple function for doing just that:
<?php
function printItems($items){
foreach ($items as $item){
echo implode(', ', $item) . "\n";
}
}
Let's give it a whirl!
<?php
printItems($fruit);
//Outputs:
//1, apple, red
//2, orange, orange
//3, pear, green
//4, grape, red
//5, peach, peach
Of course, when we print our original array it comes out in the order we defined it.
The old way
I'm a bit picky. I don't really want to tell people about my fruit in the order I thought of them. I'd much rather they were in alphabetical order. PHP doesn't have a native way to do that, so we need to define a sorting function and use usort() to do it.
<?php
function sortByName($a, $b){
return strCmp($a['name'], $b['name']);
}
The sorting function is used as a callback by usort(). It is given two elements from the array at a time; returns zero if they are the same, less than zero if the first one should come before the second, and more than zero if the second one should come before the first. Lucky for us, PHP's strCmp will do such a thing for us if we just want a string comparison; we just have to tell it which key we want to use.
<?php
usort($fruit, 'sortByName');
printItems($fruit);
//Outputs:
//1, apple, red
//4, grape, red
//2, orange, orange
//5, peach, peach
//3, pear, green
There is a problem with this however. If I wanted to then sort my fruit alphabetically by colour instead of by name, I would have to define a sortByColor() function. If I wanted to sort them by number, I would have to define a sortByNumber() function; and so on and so fifth.
What I need is a function that I can tell what I want to sort by. Before PHP5.3's introduction of closures that would have been possible, but tricky - maybe even ugly. PHP5.3 makes it trivial - maybe even elegant.
The easy way
Behold, the sortBy() function!
<?php
function sortBy(&$items, $key){
if (is_array($items)){
return usort($items, function($a, $b) use ($key){
return strCmp($a[$key], $b[$key]);
});
}
return false;
}
The input array $items is taken by reference and sorted with usort(). The callback function is created on the fly with a closure, useing the $key provided.
Let's try it out!
<?php
sortBy($fruit, 'name');
printItems($fruit);
//Outputs:
//1, apple, red
//4, grape, red
//2, orange, orange
//5, peach, peach
//3, pear, green
sortBy($fruit, 'color');
printItems($fruit);
//Outputs:
//3, pear, green
//2, orange, orange
//5, peach, peach
//4, grape, red
//1, apple, red
It's alive! IT'S ALIIIVE! Well, it works anyway. There's still a little something missing though.
What if I want to sort my fruit in descending order instead of ascending? That's actually a pretty easy change. All I need to do is add an option to invert the output of the strCmp() function.
<?php
function sortBy(&$items, $key, $descending = false){
if (is_array($items)){
return usort($items, function($a, $b) use ($key, $descending){
$cmp = strCmp($a[$key], $b[$key]);
return $descending? -$cmp : $cmp;
});
}
return false;
}
sortBy($fruit, 'number', true);
printItems($fruit);
//Outputs:
//3, pear, green
//5, peach, peach
//2, orange, orange
//4, grape, red
//1, apple, red
Magic! I can now sort by any key I want, in any direction I want. I've never been so happy.
Not quite...
Those of you have been paying attention may have noticed the fatal flaw in my use of strCmp(); I know - I'm one of the people who have noticed. If you want to sort by a numeric value, strCmp() would tell you that 20 comes before 3, and that 70 comes after 400 etc, because it does a string comparison.
This is a problem I intend to address in a blog post coming soon. Stay tuned!
Yes, No, Cancel Sun Aug 23 15:06:10 2009
I made one of the oldest mistakes in the book today; assuming that there is a big book of mistakes somewhere. When using Adobe(R) Photoshop(R) software I tried to merge a layer down with ctrl+E, and hit ctrl+W instead. I was presented with this dialog:

The problem is that my first thought was "NO! NO NO NO! I don't want to do that!". So I clicked 'No'. Duuuuuuh.
It wasn't anything important I was working on, so I just left it and went to get a sandwich.
While what I did was a stupid mistake, it did help me realise that even the parts of interfaces that we take for granted as 'fine' have room for improvement. It also made me realise how tasty peanut butter and Rocky Caramel sandwiches are. And finally, from following the link to Fox's Biscuits, I was reminded how annoying Flash-based websites are when you want to link to a specific part of them. ANYWAY...
I'm sure I'm not the first to make such a suggestion, but I think something like this would cause less headaches:

Would that be so hard? I know it's lazy to not want to read the whole message, but laziness is in our nature.
For the record, I'm not picking on Adobe(R) Photoshop(R) software specifically. Many, if not most, applications have the same problem. It just so happened that I was using Adobe(R) Photoshop(R) software at the time.

The problem is that my first thought was "NO! NO NO NO! I don't want to do that!". So I clicked 'No'. Duuuuuuh.
It wasn't anything important I was working on, so I just left it and went to get a sandwich.
While what I did was a stupid mistake, it did help me realise that even the parts of interfaces that we take for granted as 'fine' have room for improvement. It also made me realise how tasty peanut butter and Rocky Caramel sandwiches are. And finally, from following the link to Fox's Biscuits, I was reminded how annoying Flash-based websites are when you want to link to a specific part of them. ANYWAY...
I'm sure I'm not the first to make such a suggestion, but I think something like this would cause less headaches:

Would that be so hard? I know it's lazy to not want to read the whole message, but laziness is in our nature.
For the record, I'm not picking on Adobe(R) Photoshop(R) software specifically. Many, if not most, applications have the same problem. It just so happened that I was using Adobe(R) Photoshop(R) software at the time.
Songs in code Fri Aug 21 13:56:10 2009
Yesterday morning (20th August), a few of my fellow developers and I started a little in-joke on twitter: #songsincode. It is currently hovering around the #3 trend on the Twitter homepage.
It's been great fun to see it rise up to this point, and thought the people involved in setting the ball rolling deserved credit: @proxymoron, @scawp, @asmitter, @_SteveWilson_, @lingmops and myself @tomnomnom. Between us, we make up the development team at FrogTrade Ltd in Halifax, UK.
It all started with three tweets.
Firstly from @asmitter at 0958 GMT:
$hiphip = array();
And then one from @scawp at 1010 GMT:
name the singer :-p $val = array(); if(!comeOnOver($val)) { echo 'why?'; }
Finally, one from @proxymoron at 1033 GMT, with the addition of the hashtag:
class me { function say($what) { if($what) == 'goodbye'; { die('A little'); } } #songsincode
After that, @lingmops, @_SteveWilson_ and myself got involved, and it started to snowball.
I think it was one of the more productive days we've had as a team.
Yes. We are a little mad; but if you're interested in working with us, we are hiring.
Update: @asmitter has provided a far more in-depth (and more amusing) analysis here: http://docs.google.com/View?id=dcg768xk_4ff83ftcd
It's been great fun to see it rise up to this point, and thought the people involved in setting the ball rolling deserved credit: @proxymoron, @scawp, @asmitter, @_SteveWilson_, @lingmops and myself @tomnomnom. Between us, we make up the development team at FrogTrade Ltd in Halifax, UK.
It all started with three tweets.
Firstly from @asmitter at 0958 GMT:
$hiphip = array();
And then one from @scawp at 1010 GMT:
name the singer :-p $val = array(); if(!comeOnOver($val)) { echo 'why?'; }
Finally, one from @proxymoron at 1033 GMT, with the addition of the hashtag:
class me { function say($what) { if($what) == 'goodbye'; { die('A little'); } } #songsincode
After that, @lingmops, @_SteveWilson_ and myself got involved, and it started to snowball.
I think it was one of the more productive days we've had as a team.
Yes. We are a little mad; but if you're interested in working with us, we are hiring.
Update: @asmitter has provided a far more in-depth (and more amusing) analysis here: http://docs.google.com/View?id=dcg768xk_4ff83ftcd
I need closure Tue Jul 7 20:47:49 2009
The recent release of PHP 5.3 has got me all excited. There's a whole bunch of new features such as namespaces and late static binding. Sure, namespaces will be great for organising code at work, but the thing I'm most excited about is the addition of Lambda/anonymous functions and Closures (hurrah!).
I've had a few conversations recently about what Lambda functions and Closures are good for. Because I'm such a nice guy, I've prepared a couple of examples.
There are a whole bunch of PHP functions that accept a callback function (or rather, the name of a callback function) as an argument; array_filter and preg_replace_callback spring to mind. The problem with said functions is that you have to pre-define a function for use as a callback. I always thought it was an ugly solution that impeded the geneal flow of the code; it made it more difficult to read. It also means that you're taking up valuble scope with a function that's probably only going to be used once.
Enter closures! (HURRAH!) Now you can just pass in your function code as an argument:
<?php
//These are the people I know
$people = array(
'Jim', 'Bob', 'Sam',
'Barry', 'Tom', 'Harry'
);
//I no-longer like people who's name starts with 'B'
$people = array_filter($people, function($person){
return (substr($person, 0, 1) !== 'B');
});
This sort of construction should look pretty familiar to anyone who's written any non-trivial JavaScript; particularly if you've used the JQuery framework. Sure you could have made the code almost as readable by pre-defining a function with a meaningful name, but a function called 'removeBPeople' sat all by itself would confuse anyone who hasn't seen the bit of code that uses it.
Useful as this is, using closures as parameters in PHP's built in functions is really only syntactical sugar. What's really good fun is defining your own functions that accept a closure as an argument.
Something you may do quite often is open a file, read through each line and then close the file. But isn't it a pain always having to remember to close the file? What could be done about that? I know! Let's wrap that logic (and then some) into a function. But how do we tell the function what to do with the file while it has it open? CLOSURES! HURRAH!
<?php
//Read a file line by line
function readLines($filename, $fn)
{
if (!file_exists($filename)) return;
$fh = fopen($filename, 'r');
if (!$fh) return;
while (!feof($fh))
{
//Roughly equivlent to a 'yield' in Ruby
$fn(fgets($fh));
}
fclose($fh);
}
This function accepts a filename and a function. It checks the file exists, opens it, checks it was opened, iterates over the lines in the file and then closes it. But that's not all! For every line it iterates over, it executes the closure $fn, passing the line to the closure as an argument.
Note the comment about Ruby's 'yield'. If you've ever played with Ruby, this may all seem very familiar.
Now we need to use it. For the purpose of this example, I have created a file called input.txt that contains the following:
line one
line two
line three
line four
Let's say that we just want to display each line in the file. That's easy!
<?php
readLines('input.txt', function($line){
echo $line;
});
The output of this code would be exactly the same as the input file. Magical!
This is all well and good; but closures, like regular PHP functions, have their own scope. What if you want to use or affect the value of a variable defined outside the closure's scope? The lovely people who write PHP added the use statement for such a scenario.
<?php
//Capitalise the first letter of each line and add it to the output
$output = '';
readLines('input.txt', function($line) use(&$output){
$output .= ucfirst($line);
});
echo $output;
Note that the variable $output is passed by reference in the use statement; this allows us to change the value of $output rather than just use it.
These are only a couple of very simple examples. There are lots of wonderful ways to use closures. A lot of those uses are far too complicated for my tiny mind to comprehend; (just looking at the number of math-y looking symbols in the Wikipedia article on function Currying made me cry) but don't let my tiny mind deter you from the wonderfulness of CLOSURES! (HURRAH!)
I've had a few conversations recently about what Lambda functions and Closures are good for. Because I'm such a nice guy, I've prepared a couple of examples.
There are a whole bunch of PHP functions that accept a callback function (or rather, the name of a callback function) as an argument; array_filter and preg_replace_callback spring to mind. The problem with said functions is that you have to pre-define a function for use as a callback. I always thought it was an ugly solution that impeded the geneal flow of the code; it made it more difficult to read. It also means that you're taking up valuble scope with a function that's probably only going to be used once.
Enter closures! (HURRAH!) Now you can just pass in your function code as an argument:
<?php
//These are the people I know
$people = array(
'Jim', 'Bob', 'Sam',
'Barry', 'Tom', 'Harry'
);
//I no-longer like people who's name starts with 'B'
$people = array_filter($people, function($person){
return (substr($person, 0, 1) !== 'B');
});
This sort of construction should look pretty familiar to anyone who's written any non-trivial JavaScript; particularly if you've used the JQuery framework. Sure you could have made the code almost as readable by pre-defining a function with a meaningful name, but a function called 'removeBPeople' sat all by itself would confuse anyone who hasn't seen the bit of code that uses it.
Useful as this is, using closures as parameters in PHP's built in functions is really only syntactical sugar. What's really good fun is defining your own functions that accept a closure as an argument.
Something you may do quite often is open a file, read through each line and then close the file. But isn't it a pain always having to remember to close the file? What could be done about that? I know! Let's wrap that logic (and then some) into a function. But how do we tell the function what to do with the file while it has it open? CLOSURES! HURRAH!
<?php
//Read a file line by line
function readLines($filename, $fn)
{
if (!file_exists($filename)) return;
$fh = fopen($filename, 'r');
if (!$fh) return;
while (!feof($fh))
{
//Roughly equivlent to a 'yield' in Ruby
$fn(fgets($fh));
}
fclose($fh);
}
This function accepts a filename and a function. It checks the file exists, opens it, checks it was opened, iterates over the lines in the file and then closes it. But that's not all! For every line it iterates over, it executes the closure $fn, passing the line to the closure as an argument.
Note the comment about Ruby's 'yield'. If you've ever played with Ruby, this may all seem very familiar.
Now we need to use it. For the purpose of this example, I have created a file called input.txt that contains the following:
line one
line two
line three
line four
Let's say that we just want to display each line in the file. That's easy!
<?php
readLines('input.txt', function($line){
echo $line;
});
The output of this code would be exactly the same as the input file. Magical!
This is all well and good; but closures, like regular PHP functions, have their own scope. What if you want to use or affect the value of a variable defined outside the closure's scope? The lovely people who write PHP added the use statement for such a scenario.
<?php
//Capitalise the first letter of each line and add it to the output
$output = '';
readLines('input.txt', function($line) use(&$output){
$output .= ucfirst($line);
});
echo $output;
Note that the variable $output is passed by reference in the use statement; this allows us to change the value of $output rather than just use it.
These are only a couple of very simple examples. There are lots of wonderful ways to use closures. A lot of those uses are far too complicated for my tiny mind to comprehend; (just looking at the number of math-y looking symbols in the Wikipedia article on function Currying made me cry) but don't let my tiny mind deter you from the wonderfulness of CLOSURES! (HURRAH!)