Category Archives: programming

Rendering table rows in React

When rendering content with JSX, you have to remember that render method can only return one root node. This makes populating table rows a little tricky. For example, the following code would be invalid:

renderRows() {
    return (
        <tr>
            <td>
                Item 3
            </td>
        </tr>
    );
}

render() {

return (
                <tr>
                    <td>
                      Item 1
                    </td>
                    <td>
                      Item 2
                    </td>
                </tr>
                {this.renderRows()}
);

This is invalid because render contains two root nodes (two tr’s). You’ll see the following error occur:

Uncaught Error: Parse Error: Line 27: Unexpected identifier

To get around this limitation, you need to wrap the content in a new root node. Typically you would use a div for this purpose, but this wouldn’t be valid HTML within a table so the only solution is to use a tbody tag like so:

renderRows() {
    return (
        <tr>
            <td>
                Item 3
            </td>
        </tr>
    );
}

render() {

return (
          <tbody>                
                <tr>
                    <td>
                      Item 1
                    </td>
                    <td>
                      Item 2
                    </td>
                </tr>
                {this.renderRows()}
          </tbody>
);

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Listing your Git commits from the last 24 hours

Useful aide-memoire when you are creating end of day status emails:

git log --author="`git config user.name`" --pretty=format:"%cd %h %s" --date=short --since="yesterday"

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Allow per-developer Vagrantfile customisations

If you are sharing a Vagrant file across a team, for example, for configuring a local development environment you’ll know that sometimes individual developers want their own VM tweaks. For example, they may have a machine with more memory that they’d like to dedicate to the VM. In order to support this, you can add a config file for custom changes:

Example Vagrantfile showing custom memory and CPU cap:

# -*- mode: ruby -*-
# vi: set ft=ruby :
require 'yaml'

if File.exists?('vagrant.yml')
  settings = YAML.load_file 'vagrant.yml'
end

memory_use    = defined?(settings['memory']) ? settings['memory'] : 1024
cpu_execution = defined?(settings['cpucap']) ? settings['cpucap'] : 50

Vagrant.configure(2) do |config|
  config.vm.box = "puphpet/centos65-x64"
  config.vm.network "private_network", ip: "192.168.56.101"

  config.vm.provider "virtualbox" do |vb|
    vb.memory = memory_use
    vb.customize ["modifyvm", :id, "--cpuexecutioncap", cpu_execution]
  end

  config.vm.provision "ansible" do |ansible|
    ansible.playbook = "provision/playbook.yml"
    ansible.become = true
    ansible.raw_arguments = Shellwords.shellsplit(ENV['ANSIBLE_ARGS']) if ENV['ANSIBLE_ARGS']
    ansible.compatibility_mode = "1.8"
  end
end

In this example, we’ve specified two configurable settings — memory_use and cpu_execution. Values will be read from the settings file, if it exists, otherwise default values are set (lines 9-10). Memory is specified in megabytes, and CPU execution is the maximum allowed percentage of the hosts CPU usage.

Example vagrant.yml file:

memory: 4096
cpucap: 75

Don’t forget to add the vagrant.yml file to your .*ignore file to make sure it isn’t committed to your source repo.

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Enable WordPress automatic updates in your Vagrant VM

If you are using Vagrant to manage VM’s for WordPress development, you’ll know that by default auto-updates of core and plugins do not work. This is because the VM’s shared folders are not writable by the web server. This is a simple thing to fix, though. Open up your Vagrant file and add the following to your config.vm.synced_folder line:

:mount_options => ["dmode=777", "fmode=666"]

So, if your config.vm.synced_folder line looked like this before:

config.vm.synced_folder "./", "/var/www", id: "vagrant-root"

Change it to this:

config.vm.synced_folder "./", "/var/www", id: "vagrant-root", :mount_options => ["dmode=777", "fmode=666"]

Then reload your VM for the change to take effect:

vagrant reload

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Don’t Rest on Your Laurels

resting

I read a great article that describes the great life developers have right now, but raises a warning:

Don’t get too comfortable. Don’t get locked into a language. Don’t burn bridges for short term gain. Keep your tools sharp. Learn soft skills. Build an audience. Save some money. Network. Read.

There’s some excellent advice here, so let’s consider each point:

Don’t get too comfortable

Software development is a huge subject, and it’s a very fast-moving discipline. Web development is a great example of how you cannot afford to stagnate – for example, nobody is using table tags to build out sites any more, and for good reason.

Don’t get locked into a language

Whilst it’s great to master a language and/or a framework, try not to have tunnel vision: there are always alternative solutions so keep open minded about other languages.

Don’t burn bridges

This is especially pertinent when you are freelancing, but it also applies to permanent employees. Don’t tread on other’s toes, and try not to piss people off.

Keep your tools sharp

I wrote about this last time (see Know Thy Editor). The processes and tools that complement your software development are essential for your productivity.

Learn soft skills

Developing communication skills are critical to keep on top of your game. If you are working as part of a team, then you can practice this every day. Learn to actively listen, be courteous to others and don’t be afraid to take the initiative and lead whenever you can.

Build an audience

If you have knowledge, then spread the word and you’ll find yourself building an audience. The easiest way to do this? Teach through your blog.

Save some money

You never know what might happen in the future – tech companies are notoriously volatile. Have savings put away in case of emergencies. If you are out of work, then you will have a cushion to give you time to find something new.

Network

Meetup is a great resource for finding networking events. These may also be “soft” networking events such as co-working or tech talks. Remember that everyone you meet may be a potential client.

Read

Keep learning, but be particular about what you read. Pick one or two blogs to follow, find authors that you like and trust. Continue to learn: Coursera is a great online learning hub.

To sum up, don’t get complacent. Things are great for developers right now, but there are always ways to improve your craft.

photo credit: resting by Michael Cory, on Flickr

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Know Thy Editor

Code

I’ve used many editors for programming over the years.

  • 1996 – 1999, Emacs
  • 2000 – 2007, BBEdit
  • 2009 – 2011, Emacs
  • 2012 – Present, Sublime Text 2

This week I was providing some mentoring with somebody that was using Notepad++ as their code editor of choice. What struck me was how few features of the program he was using. Cursor keys to move around. Not using the find function. Clicking rather than using keystrokes.

It was painful to watch!

The thing is, it doesn’t really matter which editor, or indeed IDE, you use. What’s important is how you use it.

As Andrew Hunt noted in The Pragmatic Programmer, use a single editor well.

Watching somebody who really knows their editor is a joy. I remember a few yers back marvelling at a colleague who used vim and he just flew around it. He had mastered it.

The most important thing is that you know your editor inside out. Be efficient. Be effective. It can make a huge difference to your software development productivity.

photo credit: Code by Riebart, on Flickr

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Some Documentation is Better than No Documentation

LimeSurvey v2 schema

Ever started work on an existing software project that has NO technical documentation whatsoever?

I have recently, and I immediately felt lost.

No coding standards, no testing guidelines and most importantly, no notes at all about how the existing codebase was designed.

Why is this a problem? Well, for me it meant a lot of time reverse engineering the codebase and subsequently generating new documentation. I had to learn the project from scratch. It added a huge amount of time before I could do any real work on the project.

Every little piece of documentation that you add to your project can help save time later on – either for yourself or for another person working on the project.

What’s the minimum you should have in your project documentation?

  • Database schema in visual form
  • Coding standards
  • Source control branching strategy
  • Deployment instructions for all environments (e.g. staging and/or production)
  • Development environment setup

Wikis are perfect for collecting this kind of documentation. They are free-form, so you have freedom to structure as you wish.

Have no documentation at all? Fear not, it’s easy to get up and running. A few ideas to start with:

  1. Use a database management tool, such as MySQL Workbench, to reverse engineer your database schema and produce a graphical model
  2. Use your unit testing framework to produce agile documentation from your tests – for example, PHPUnit has a –testdox option for generating documentation.
  3. Start using standard inline documentation. For example, use phpDocumentor for PHP code.

Take a look at the documentation you have for the project you are currently working on. If a new developer came onto the project today, would the documentation be enough to get them up to speed? If not, what would you need to add?

image credit: LimeSurvey v2 schema by juhansonin, on Flickr

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

HTML5, character encodings and DOMDocument loadHTML and loadHTMLFile

Extreme HTML Verschachteling

Whilst working on a script for my GetProThemes app recently, I came across a problem with PHP’s loadHTML and loadHTMLFile methods.

The problem

I noticed that when using loadHTMLFile to parse an HTML document, the character encoding — UTF-8 in this case — was not being taken into consideration. Because of this, there was some mojibake after I extracted some content from the document. Here is an example of the problem:

$i18n_str = 'Iñtërnâtiônàlizætiøn';

$html = <<<EOS
<!doctype html>
<head>
  <meta charset="UTF-8">
  <title>html 5 document</title>
 </head>
 <body>
<h1 id="title">$i18n_str</h1>
</body>
</html>
EOS;

$dom = new DOMDocument();
$dom->loadHTML( $html );
echo $dom->getElementById( 'title' )->textContent;

// output: Iñtërnâtiônà lizætiøn

After some digging into the PHP source code, I discovered this function, along with loadHTML, uses Libxml for determining the character set of the HTML document automatically. It uses a function named htmlCheckEncoding for this purpose. What this function does is to look for a meta tag declaring the character set. Unfortunately, it only looks for the HTML4 style declaration:


<META http-equiv="Content-Type" content="text/html; charset=UTF-8">

This means that if your source document is HTML5, it will not pick up the newer meta tag declaration which has this form:


<meta charset="utf-8">

It seems that this glitch has been fixed in version 2.8.0 of Libxml, but if you are stuck with an older version then I have created a workaround.

The solution

I have created a drop-in replacements for the loadHTML/loadHTMLFile methods which will automatically convert an HTML5 character set declaration, if it exists, into an HTML4 character set declaration and thus allowing Libxml to parse the document correctly.

Fixing the above example is trivial:

require_once 'DOMDocumentCharset.php';

$i18n_str = 'Iñtërnâtiônàlizætiøn';

$html = <<<EOS
<!doctype html>
<head>
  <meta charset="UTF-8">
  <title>html 5 test</title>
 </head>
 <body>
<h1 id="title">$i18n_str</h1>
</body>
</html>
EOS;
		
$dom = new DOMDocumentCharset();
$dom->loadHTMLCharset( $html );
echo $dom->getElementById( 'title' )->textContent;

// output: Iñtërnâtiônàlizætiøn

So, the fix involves:

1. Including the DOMDocumentCharset class
2. Instantiating DOMDocumentCharset rather than DOMDocument
3. Calling the new loadHTMLCharset method

The class will only activate the workaround if the installed Libxml version is less than 2.8.0, so upgrading Libxml will not break this code.

The source code can be found on GitHub: dom-document-charset

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

View carriage returns, line feeds and tabs within text files

This is a useful Python one-liner for viewing characters that are usually hidden in text files;

  • Carriage returns (shown as \r)
  • Line feeds (shown as \n)
  • Tabs (shown as \t)
python -c "f = open('filename.txt', 'r'); f.seek(0); file = f.readlines(); print file"

Example output:

['Carriage return and line feed: \r\n', 'Line feed: \n', 'Tab: \t\n']

I recently used this script when trying to work out why a shell script was not executing correctly on a Debian machine — the reason was some carriage returns inserted by a Windows-based editor.

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Install mcrypt PHP extension on OS X Snow Leopard

Lock away the evil...

Please note: The following instructions apply to Mac OS X 10.6 (Snow Leopard). I have an updated guide for how to install mcrypt on 10.7 (Lion).

mcrypt is a useful extension to PHP if you would like to support a wide range of encryption algorithms within your code.

This guide explains how you can enable install mcrypt, along with the PHP extension, on Mac OS X 10.6.

Xcode

The Xcode package installs the necessary versions of tools like autoconf which is needed during the PHP extension compilation process. Make sure you have at least Xcode v3.2 installed; the install package is available on the Snow Leopard install DVD under the “Optional Installs” folder.

libmcrypt

libmcrypt is the library that provides the encryption functions. We need to install this before building the PHP extension.

  • Open up Terminal.app
  • export CFLAGS="-arch x86_64"
  • Download libmcrypt from sourceforge
  • Unpack the archive somewhere
  • cd libmcrypt
  • ./configure --disable-shared
  • make
  • sudo make install

PHP Extension

Once we have libmcrypt installed, we can build the PHP extension.

You should see output similar to the following:

Configuring for:
PHP Api Version:         20090626
Zend Module Api No:      20090626
Zend Extension Api No:   220090626
  • ./configure
  • make
  • sudo make install

On successful install, you will see the following message:

Installing shared extensions:     /usr/lib/php/extensions/no-debug-non-zts-20090626/

To enable the module, include the following line in your /etc/php.ini file:

extension = mcrypt.so

Finally, restart your Apache server:

sudo apachectl restart

And that’s it: you should now be able to utilise the functions, as detailed in the PHP mcrypt documentation.

mcrypt php extension

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn