I design & develop websites.

I am a designer & developer. I am a communicator & strategist. I can add value to your business.

Installing iVerilog on Mac OS X 10.7 Lion

To save you all the hours I just lost trying to get iVerilog and vvp working on OSX 10.7 here's how to do it.

Firstly don't build the stable version from source as vvp fails to build. Secondly Homebrew and Macports try to build the stable version and both crash with indecipherable error messages so they're out too. I haven't tried Fink but I'm going to assume that they're building the current stable version as well.

The solution to my woes? Installing the latest development version from the iverilog git repo. The following are a list of commands that will do that for you.

git clone git://icarus.com/~steve-icarus/verilog
cd verilog
git checkout --track -b v0_9-branch origin/v0_9-branch
sh autoconf.sh
./configure
make check
sudo make install

Then run which iverilog and which vvp to check that they're installed. If nothing's gone wrong you should have a working installation.

jQuery vertical centre

I'm working on a super secret project for Hydrant at the moment which requires vertically centering an element on page load and keeping it centered on window re-size. Here's how it's done.

$(function() {
  $.fn.verticalCenter = function() {
    $(this).each(function() {
      $pageCenter = $(this).height() / 2;
      $windowCenter = $(window).height() / 2;
      $top = $windowCenter - $pageCenter;
      $(this).css({
        'position': 'absolute',
        'top' : $top + 'px'
      });
    });
  }
  myResize = function() {
   $('.page:visible').verticalCenter();
  }
  $(window).resize(myResize);
  myResize();
});

$.GreyScale jQuery Plugin

I was watching a video on Net.TutsPlus about using jQuery to grayscale images on the fly (revealing the coloured version on hover) and was very surprised to find no one (to my knowledge) had written a jQuery plugin encapsulating this idea. So I went ahead and wrote one.

The big problem with greyscaling images is that to access image data the image must be hosted locally for security reasons. Luckily Max Novakovic has written a jQuery plugin called $.getImageData which proxies requests for images using a server on Google's AppEngine which solves this problem for us. I have included it in the $.GreyScale plugin file for convenience.

Usage

Simply include jQuery and then greyScale.min.js into your page and then use the following code to trigger the greyscale effect. Currently the only editable parameter is the time (in ms) it takes to fade between the greyscale and coloured images.

      $(function() {
        // fade in the grayscaled images to avoid visual jump
        $('.greyScale').hide().fadeIn(1000);
      });
      // use window.load to ensure images have been loaded
      $(window).load(function () {
        $('.greyScale').greyScale({
          // call the plugin with non-defult fadeTime (default: 400ms)
          fadeTime: 500,
          reverse: false
        });
      });

Changelog

v 0.2

  • Added reverse functionality. Set reverse to true when calling the plugin to fade to black and white on hover rather than Vice versa.

A live example can be seen here and the project can be found on (and downloaded from) GitHub here.

Feel free to fork the code and play with it and if you find any bugs let me know in the comments below or via email at andrew@pryde-design.co.uk.

Update: I am getting emails telling me that the server used for proxying the requests is offline. I cannot make any guarantees about this server and as such you should implement your own on your servers using code from this GitHub repository.

Callable methods of a Python object

When developing in Python I often find myself using the dir() function to inspect modules. However, there is a great deal of clutter that dir() produces, which usually I am not interested in as all I need are the callable methods in the module. So I wrote a little one line function to return only the callable methods of an object.

def callableMethods(obj): return [item for item in dir(obj) if callable(getattr(obj, item))]

I hope you find it as useful a tool to have laying around in your toolbox as I do mine.

Wrap a class around half a string in PHP

This Stackoverflow question got me thinking about string manipulation in server-side vs client side languages. The questioner stated:

In theory I want to find all of the spaces in the sentence and divide it into two. If the headline contains an uneven number of words the script should detect that and also add the class to the nearest word.

To do this they suggest that Javascript—more specifically jQuery—could be used. At first I set about writing a few quick lines of jQuery to answer his question, however, I stopped abruptly and asked myself "is he asking the right question?". I am inclined to argue that his suggested technology is inappropriate for the task at hand and thus he's not asking the right question. Here's why:

  1. According to the mantra of progressive enhancement "enhanced behaviour is provided by unobtrusive, externally linked JavaScript". In this case we are making a change to markup which is non-behavioural but rather structural and so should be implemented in the markup rather than be added to it on the client side.
  2. The maintainability of the code is compromised by the use of client-side code to modify markup.
  3. Javascript is still not available on a significant percentage of user's browsers—a quick search gives W3Schools' latest statistics (admittedly from 2008) which quotes 5%.
  4. Doing too many operations such as this on thin clients such as mobile devices is detrimental to performance—though this is marginal especially on modern smart phones.

So where should such alterations to markup be made? In the markup. However, we rarely work with static markup these days and so this kind of alteration to markup should be made in the backend and then cached. Here is an example of how to split a string in half (using number of words rather than characters) and wrap a class around the first half of the string in PHP.

<?php
$headline = "This is a headline  of epic proportions";
$split = explode(' ', $headline);
$a = array_slice($split, 0, (count($split)/2));
$b = array_slice($split, (count($split)/2));
$headline = '<span class="whatever">'. join(' ', $a) . '</span>' . join(' ', $b);
print $headline;
?>

The task is completed even more elegantly with python:

headline = "This is a super headline"
words = headline.split(" ")
headline = '<span class="whatever">' + " ".join(words[:len(words)/2]) + '</span> ' + " ".join(words[len(words)/2:])
print headline

This of course can be achieved in any server-side language and if you would like an example using a specific language just leave a comment below. I have not implemented any form of caching here as I wouldn't suggest caching elements individually but rather caching the entire page.

No. of Days Between Two Dates in Python

In the countdown to Christmas everyone is eager to know how many days of work there are to endure before the holidays. I decided to removed the necessity for counting with a "number of days between date calculator"—snappy name I know—written in Python. If anyone can tell me a better way of getting the seconds since the epoch for the current date—not time, date—please post a comment but here is my solution.
import sys
import time
import re

importantDates = { 'xmas' : '25/12/2010'}

def formatDate(inputStr):
  """formatDate(list) -> list of ints
 
  returns a list containing integer values for the date [yyyy, mm, dd]"""

  inputStr = inputStr.split('/')
  inputStr.reverse()
  inputInt = [int(i) for i in inputStr]
  return inputInt

def toEpoch(inputInt):
  """toEpoch(list) -> floating point number
 
  Convert a date list [yyyy, mm, dd] to seconds since the Epoch"""

  inputInt.extend([0]*6)
  return time.mktime(inputInt)

def betweenDates(startDate, endDate):
  """betweenDates(list, list) -> string
 
  Calculate the number of days and weeks between two dates in weeks and secconds"""

  endDate = formatDate(endDate)
  secconds = toEpoch(endDate) - toEpoch(startDate)
  days = secconds / 86400
  past = ''
  if days < 0:
    days = -days
    past = '(in the past)'
  if days > 7:
    weeks = days / 7
    days = days % 7
    return '%d week(s) and %d day(s) %s' % (weeks, days, past)
  else:
    return '%d day(s) %s' % (days, past)

def main():
  if len(sys.argv) == 2:
    path, endDate = sys.argv
    if endDate in importantDates.keys():
      endDate = importantDates[endDate]
    elif not re.match(r'^\d{2}/\d{2}/\d{4}$', endDate):
      raise ValueError("Date not in format dd/mm/yyyy")
    startDate = [int(i) for i in time.localtime()[:3]]
  elif len(sys.argv) == 3:
    path, startDate, endDate = sys.argv
    startDate = formatDate(startDate)
  else:
    print ('Usage: date.py 10/10/10 11/10/10 - to calculate between any two dates', 
           '\nUsage: date.py 10/10/10 - to calculate between today and a specified date')
    sys.exit()
  print betweenDates(startDate, endDate)

Python Prime Number Calculator

Below is a prime number calculator I wrote after attending to a lecture on big numbers and quantum computers at York University (primes were mentioned re their being instrumental in PKI which will be useless when quantum computers move from their current infancy). It is by no means the fastest, in fact on the scale of the algorithms available for calculating prime numbers its very slow (takes 3.844 (have optimised to now only divide by numbers < half of current number) 2.020s to calculate the primes between 2 and 10,000 on my 2Ghz Core 2 duo Macbook). However before Googling I set myself the challenge of designing something that solved the problem. Anyway without much further ado here it is.

import sys

def isPrime( no ):
  sqrt = round(no**0.5);
  # if counted through and all numbers from 3 too x are not factors is prime
  if no % 2 == 0 or no % 3 == 0:
    return False
  for x in range(6, int(sqrt), 6):
    if no % (x - 1) == 0:
      return False
    if no % (x + 1) == 0:
      return False
  return True

def primesInRange(limLow, limHigh):
   # negitive numbers, 0 and 1 are not primes so answer invalid
  if limLow < 2:
    raise ValueError('Lower limit must be 2 or more')
  # if lower limit is even its not prime so increase by 1
  if limLow % 2 == 0:
    limLow += 1
  primes = []
  while (limLow <= limHigh):
    if isPrime(limLow): primes.append(limLow)
    limLow += 2
  return primes


def main():
  limLow = int(sys.argv[1])
  limHigh = int(sys.argv[2])
  print primesInRange(limLow, limHigh)
   
if __name__ == '__main__':
  main()

Update: I have modularised the code so that it can be imported and used within other programs and the Python interpreter.

Display featured services columns in WordPress

On a recent client project I needed client editable columns at the bottom of the WordPress front page. There seemed no logical way to do it within the TinyMCE editor without using a plugin and tables for layout (bah EVIL) so I decided to use custom fields and the following code. I am sure there are more robust and prettier ways of doing this but here is my solution.

  <?php if (is_front_page()) : ?>
    <ul class="featuredServices">
    <?php for ($i = 1; $i <= 3; $i++) : ?>
      <li class="<?php echo ($i == 3) ? "col-last" : "col"; ?>">
        <h3>
          <a href="<?php echo get_post_meta(get_the_ID(), "Col$i Link", $single) ?>">
            <?php echo get_post_meta(get_the_ID(), "Col$i Title", $single) ?>
          </a>
        </h3>
        <p>
          <?php echo get_post_meta(get_the_ID(), "Col$i Text", $single) ?>
        </p>
      </li>
    <?php endfor; ?>
    </ul>
  <?php endif; ?>

All the site editor has to do is edit the custom fields named Col1-3 Title, Text and Link and the code displays the data as an unordered list which can be styled as columns. An improvement would be do add the ability to do a varying number of columns as the number of columns is hard-coded into the theme but it wasn't necessarily for this project and would just have added another custom field to confuse the editor.

Please let me know what you think via the comments and if you have any suggestions for improving the code / doing it in a different way that would be great too.

- @Prydie

PHP Redirect / Refresh Function

Often I find myself redirecting users between pages using varying methods depending where in the program flow the redirect is required (i.e. have the headers been sent). I decided to write a function which took the effort out of redirecting or refreshing (with a delay) a page.

<?php
function redirect($location, $delay = 0) {
	if (!headers_sent()) {
		if ($delay > 0) {
			header("Refresh: $delay; url=$location");
		} else { header("Location: $location"); }
	} else {
		?>
		<script type="text/javascript" charset="utf-8">
			$(function () { 
				setTimeout(function() { 
					window.location.replace('<?php echo $location; ?>');
				}, <?php echo $delay*1000; ?>); 
			});
		</script>
		<noscript>
			<meta http-equiv="refresh" content="<?php echo $delay; ?>;url=<?php echo $location; ?>">
		</noscript>
		<?php
	}
}
?>

The script first tries to redirect the page using the header() function. If the headers have not been sent and then falls back to jQuery, resorting finally to a meta refresh if javascript is disabled.

Differentiate jQuery $.ajax requests

To ensure that your PHP application works both with and without Javascript enabled in the users browser it is often necessary to return different content depending on whether Javascript is enabled or not. For example often it is useful to return data via JSON when Javascript is enabled however it is unhelpful to display JSON to a user.

jQuery + Apache

jQuery (and most other major Javascript libraries) when executing AJAX requests use a specific header to show that they are doing so. This header can be requested and accessed as a variable as long PHP is installed as an Apache module. This method requires no change to your Javascript (jQuery) code however if PHP isn't installed as an Apache module there is a slightly less elegant workaround below that does require you to edit your Javascript.

<?php
$headers = apache_request_headers();
if( !empty($headers['X-Requested-With']) && ($headers['X-Requested-With'] == 'XMLHttpRequest')) { 
	header("Content-type: application/json"); }
}
?>

The above code firstly requests the headers and stores them in the variable $headers and then if the header is present sets the content type to application/json so that the browser treats the data as JSON. We use two clauses in the IF statement to avoid PHP displaying a warning about $headers['X-Requested-With'] being undeclared when Javascript is disabled.

Then when returning data (such as error information) you can use the same if statement to return a JSON encoded array if Javascript is enabled or just simple HTML if not.

jQuery with another webserver

PHP does not (to my knowledge) provide a platform independent method of getting the request headers. Therefore we can simply add another data field to our jQuery $.ajax request to be used as a differentiator.

$(".button").click(function() {
	var firstName = $("input#firstName").val();
	var lastName = $("input#lastName").val();
	var email = $("input#email").val();
	var dataString = 'firstName=' + firstName + '&lastName=' + lastName + '&email=' + email + '&js=1';
	$.ajax({
		type: "POST",
		url: "add.php",
		data: dataString,
		success: function(result) {
			// do something
		}
	});
    return false;
});

By adding &js=1 to the request in the Javascript we can use the $_POST['js'] variable in PHP to differentiate between jQuery $.ajax requests and browser requests.

if (!empty($_POST['js'])) { 
	header("Content-type: application/json"); 
}

I hope you found this useful, if you have any comments or suggestions (especially on a more universal method of reading request headers) please let me know in the comments.

- Andrew Pryde