Tag Archives: code

Quick note working with child themes and WordPress

Continuing my adventures in the world of WordPress theming today, I stumbled across a minor gotcha when working with Child Themes and writing code using functions.

When you're using Dimas Begunoff's WPAlchemy framework for making metaboxes, the code examples refer to creating a sample meta box like so:

 
  $custom_metabox = new WPAlchemy_MetaBox(array
  (
    'id' => '_custom_meta', // underscore prefix hides fields from the custom fields area
    'title' => 'My Custom Meta',
    'template' => TEMPLATEPATH . '/custom/simple_meta.php',
  ));

This won't work with child themes, because the TEMPLATEPATH will be pointing to the template path of the parent theme. As all your code is (or should be...) in the child theme, you won't be able to get to the template.

You need STYLESHEETPATH

If you're using a child theme, you'll need to use a different constant instead, called STYLESHEETPATH, which rather confusingly gives you the equivalent path, for the child theme:

 
  $custom_metabox = new WPAlchemy_MetaBox(array
  (
    'id' => '_custom_meta', // underscore prefix hides fields from the custom fields area
    'title' => 'My Custom Meta',
    'template' => STYLESHEETPATH . '/custom/simple_meta.php',
  ));

Found via nabble.

The ForkBomb Tattoo

This doesn't count for much, but I think this is one of the cleverest, geekiest, most elegant tattoos I've ever seen. Carving an Apple, Cisco or Nike Logo onto your body? That's really quite sad. But this is something different:

Why do I like it?

I think it's about as attractive as a code type tattoo is going to get

The proportions are well balanced, and there's a nice visual rhythm in there - this is largely down to the choice Bitstream Sans Mono, the typeface used for this. This typeface is a well loved font in programmer circles, who spend hours staring at monospace fonts - a lovely touch.

It's actually executable code

This particular incantation has its own story too - this cryptic combination of symbols is a working example of a forkbomb, and was presented as a piece of open source art back in 2002, by Denis Jaromil Rojo, an Italian Rastafarian developer and media activist now residing in Amsterdam. A forkbomb is a piece of self replicating code that when called, start forking itself relentlessly, until it consumes all the resources on a computer system, rendering it unusable.

For the terminally curious, here's how it works:

 
:()      # define ':' -- whenever we say ':', do this:
{        # beginning of what to do when we say ':'
    :    # load another copy of the ':' function into memory...
    |    # ...and pipe its output to...
    :    # ...another copy of ':' function, which has to be loaded into memory
         # (therefore, ':|:' simply gets two copies of ':' loaded whenever ':' is called)
    &    # disown the functions -- if the first ':' is killed,
         #     all of the functions that it has started should NOT be auto-killed
}        # end of what to do when we say ':'
;        # Having defined ':', we should now...
:        # ...call ':', initiating a chain-reaction: each ':' will start two more.

More on Forkbombs here.

Frustrating and Cryptic Ruby Idioms (#1 of a series)

I keep coming across these FACRI's (Frustrating and Cryptic Ruby Idioms) in my work, so I'm jotting them here in the hope that I'll remember them better in future.

Ruby idioms

Ruby is a wonderful, if somewhat slow and memory hungry language, with an incredibly flexible and expressive syntax. However this flexibility leads to the creation of idioms that initially look totally opaque, if you don't know what to look for.

Case in point: the object{:&method} idiom

If you want to take an array called names , want to create a new array by running a text manipulation on every member of that array, a terse, but readable way to do this would be:

result = names.map { |name| name.upcase }

The intent is pretty clear here, and what happens programatically is also very readable. Another way to do this though is write it like:

result = names.map {&:upcase}

Something called type coercion is occurring here; you normally pass the map method a Proc object to execute, with a placeholder name for each iteration, and the code to run and return. However because you're not passing a Proc object here, Ruby tries to convert it on the fly into a Proc object using a method called to_proc:

def to_proc
proc { |obj, *args| obj.send(self, *args) }
end

So in this case, it's passing in names, and the method in the *args is upcase. I wasn't familiar with the send method here either, so the documentation for it from ruby core may help here:

class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"

An expensive idiom, by rockstars, for rockstars.

Th end result of all these examples is a saving of about 12 characters, at the expense of readability, and a huge performance hit as each member in names of passed around and type coerced like there's no tomorrow.

If you're a coding savant, the elegance of this will probably make you weep tears of syntactic joy, and the clever brevity of this isn't lost on me.

However, coming to this, without too much knowledge of the Ruby extensions project, or someone to talk you through what's happening is likely to be a frustrating experience.

Hope fully this will save time for someone else in future.

Tea, Arduino and Dynamic Demand

It’s the next HomeCamp tomorrow. And in a spectacular feat of bad calendaring, I’ve managed to organise the Letter Lounge to take place on the day I’ve been looking forward to for the last few months are coming away from the initial HomeCamp, utterly inspired by what I saw there.

So to make up for not being able to attend, the least I can do is finally get round to writing about the Tealight, a fun, Homecampy little project James Gardner and I built one evening in the Hub recently.

We did it partly to learn about the Arduino platform, and partly to explore how to make something as complex as demand response intelligible to people who don’t think about this for a living, and well here it is, in all it’s janky, low budget hackish glory:

This green orb constantly polls the national power grid to see how it’s keeping up with demand from everyone watching The Apprentice, and subsequently whether your next cuppa will be a particularly carbon intensive one.

If there’s spare capacity on the grid, the tealight will glows green, it’s basically saying:

‘Go ahead! Make some tea! Knock yourself out!’

If there isn’t, the colour shifts to red, saying:

“Now’s not the best time for that cuppa, give it a little while.”

The main idea here is that you can glance at the globe from across an office or co-working space, to get an idea about whether making that cup of tea is a good idea right now, without having to think too hard about it.

Think of it as national grid load balancing, using people, and hot beverages.

How we made this

This is thing is almost embarrassingly simple.

On the software side, we’re basically polling the api for caniturniton.com a website which scrapes the national grid for power usage data every minute or so, and depending on if the figure returned is higher or lower than the baseline of 50hz, we call a function to tell the BlinkM to change the colour of it’s LED accordingly.

Here’s the shopping list of hardware we used:

The fact that we could even make this, with me generally not being big on writing in any languages that feel like C, and with James being almost completely new to the platform is a testament to how lego-like the Arduino ecosystem is getting now.

When we take the shade off the lamp, it’s quite a bit easier to see how it all works:

Tealight working without the globe

The orange cable is a ethernet cable, and the grey one is the usb power, running off a spare iPod I had lying around.

The code has largely been a messy cut and paste job spliced from number of sources, but mostly from this thread in the arduino forums, and the string parsing code example is from a post by Jeff Tanner here on the daniweb forums.

This isn’t really big enough to be considered a project on github, so I’m just chucking a gist up for now:

Isn’t this massively oversimplifying and trivialising the whole concept of demand smoothing?

You could argue so, yes.

But placing it in a relatively high traffic co-working space, full of people working in totally unrelated fields is a great opportunity to speak to them about the ideas inspiring this little toy, and get lots of interesting feedback, and see how best to communicate on issues related to climate change and how massively energy intensive our life styles are.

But why tea?

A number of reasons:

  • they provide a recognisable power spike for comparing against national averages, and also for graphing against national load averages too. It makes it easier to see if behaviour is changing.

  • there’s a pattern to making hot beverages at work, but it’s pretty easy to timeshift it, without getting into emotive issues like calling people utter carbon bastards for flying to Spain on holiday.

  • it’s a usefully mundane , which makes explaining why changing behaviour here could work to smooth out demand on the national grid, meaning the oldest, dirtiest power stations don’t need to be powered up just so everyone can have a cup of tea at the same time.

  • because a good pun is its own reword.

This builds on ideas and hacks developed by Nick O'Leary at IBM, Tom Dyson at Torchbox Joe Short from Demand Logic, and presented at the last Homecamp. I really wish I was going, but I have a day of letter writing ahead of me instead for Saturday.

Which after this weekend, will be the subject of another post.

Renaming stuff with Ruby

I've been mucking around on the command line with Ruby again of late, and one thing that tripped me up initially, but is now firmly on my list of things I Like About Programming is how Ruby handles loops.

With javascript, actionscript, php, it's pretty common to iterate through an array with a for loop something like this:

for (i =o; i = array.length; i ++ ) {
 // call function foo() on array iteration 'i', with argument 'bar'
 array[i].foo(bar)
}

This is doable in Ruby too, but the following is much more common:

array do |i|
 // call function 'foo' on array iteration 'i'  
  i.foo(bar)
end

You could argue that you lose some context inside the loop if it's a long enough method, but for quick loops like in this file renaming widget me and Chris Mear wrote for the Open Rights Group, the expressiveness is pretty impressive.

Here's the full code we used for renaming the 6000-odd files that Photoshop spat out for the ORG founding 1000 badges. Chris knocked this out in about 5 minutes, and I've now commented it to the point that it's parsable even when I'm hungover. 

 

# this script iterates through about 6000 files that have been generated by Photoshop, 
# then renames them to fit naming conventions for a web app, as specified in a CSV file 'codes.csv'
# The Ruby CSV module allows to iterate through csv file easily
require 'csv'
# declare array literal to put desired filenames into
codes = []
# take column two of each row in codes.csv, and put it into 
# the first column of each row of the recently declared codes array 
CSV.open("codes.csv", 'r') do |row|
  codes[row[1].to_i] = row[0]
end
# switch into the directory 'export'
Dir.chdir 'export'
# bookmark current directory to return to later  
wd = Dir.getwd 
# glob is a function that returns an array of items matching the pattern given.
# in this case it this returns pretty much every directory or file name everything
# we could also substitute with Dir.entries('.')
('') do |dirname|
  # Dir.chdir is the Ruby equivalent to 'cd dirname'
  Dir.chdir(dirname)
  # perform a search for all .png files, (all files ending with '.png'  )
  Dir.glob('.png') do |filename|
    # read each filename, find the part of the filename that isn't the number (the '/\D/' part of the regular expression), 
    # then strip it out, leaving just the number, making sure to convert this to an integer, not a string
    number = filename.gsub(/\D/, '').to_i
    # local variable 'code' exists inside this loop only
    code = codes[number]
    new_filename = "#{code}.png"
    puts "Renaming #{filename} to #{new_filename}."
    File.rename(filename, new_filename)
  end
  # switch back to the starting directory before looping through the    
  # next folder 
  Dir.chdir(wd)
end