Chris Worfolk's Blog


Shadow DOM

March 17th, 2015 | Programming

If you’re using HTML5, you may well have come across templates, which are a way to create reusable code clocks. They can be used in conjunction with the Shadow DOM to create more semantic markup while still adding all the additional goodies in terms of additional CSS and HTML that you would like.

For example, lets say we want to put an email address in a fancy box into a website. The old horrible way of doing it is something like this:

<style>
    #email {
        background: url('images/at.png')
        center left no-repeat;
    }
    #email .label {
        font-size: small;
        text-transform: uppercase;
    }
</style>

<div id="email">
    <div class="outer">
        <div class="label">Email address</div>
        <div>
            john@example.com
        </div>
    </div>
</div>

Look at all that stuff we do not need. Semantically we do not need all those divs. Crawlers don’t need to seem them. Neither do accessibility tools. It would be way nicer if we could mark the page up like this:

<div id="email">john@example.com</div>

Turns out we can! All we need is a little help from templates and the shadow DOM. Lets work from that markup, and put the additional markup into a template tag.

<template id="emailTemplate">
    <style>
        #email {
            padding: 0.5em;
            background: url('images/at.png')
            center left no-repeat;
        }
        #email .label {
            font-size: small;
            text-transform: uppercase;
        }
    </style>
    
    <div id="email">
        <div class="outer">
            <div class="label">Email address</div>
            <div>
                <content></content>
            </div>
        </div>
    </div>
</template>

You will notice that this is basically the same code as we started out with, except now it is in a template tag, and instead of having the email address in there, there is a >content> tag. This acts as a placeholder that the contents of the div will be put into when we combine it all together.

Finally, we use some JavaScript to activate the shadow DOM.

<script>
    var shadow   = document.querySelector('#email').createShadowRoot();
    var template = document.querySelector('#emailTemplate');
    var clone    = document.importNode(template.content, true);
    shadow.appendChild(clone);
</script>

This allows us to add all the additional styling that we had initially, but thanks to the shadow DOM we are able to eliminate a lot of the additional markup in the page itself that made very little sense semantically.

Ember.js

March 16th, 2015 | Programming

emberjs Ember.js is a JavaScript framework for creating “ambitious web applications” apparently. What that translates to is a JavaScript framework that allows you to get started quickly and have URL-based apps.

It is under heavy active development at time of writing so means that there is plenty of new stuff but also means that the documentation can quickly get out-of-date, so it might take a bit of time fiddling around to get it bootstrapped up and up-and-running. There is a helpful Chrome plugin that fits into the Developer Tools too, though most of the time I spend time looking at the standard console.

Once you are ready to go, things are easy to build. It uses Handlebars, or at least a Handlebars style syntax, so if you have used Handlebars, or even Mustache before then you will probably have a basic idea of what you are doing. You can then layer up pages within each other to build complex applications that can all be bookmarked.

It is designed to work out-of-the-box with Ember Data, which provides instant support for a REST API. If you do not have a REST API, Ember.js claims it is easy to adapt to something else, though I’m sceptical that it is as easy as they claim. It seems to work best if you build the app, and then create a standard REST API to work with it.

I have implemented some simple embedded Ember.js apps for my photo gallery as well as working with it for some more complex projects elsewhere. It is a fun framework to work with, but the documentation is a little parse and it is not quite as flexible as I would like. See the Ember.js website for more information.

Talent is Overrated

March 15th, 2015 | Books

Talent is Overrated: What Really Separates World-Class Performers from Everybody Else is a book by Geoff Colvin.

I read it after I was recommended it by a friend. He is a member of my Toastmasters club and is a lovely and funny guy. But several of his talks have irked the sceptic in me. In one unlucky incident, for example, he gave a talk on neuro-linguistic programming, a field that has now been completed debunked. Unfortunately for him, I was his formal evaluator that way, and was quite outspoken in my evaluation speech!

In another speech he spoke about Malcolm Gladwell’s 10,000 hour rule, which again is probably nonsense. I challenged him on it and he recommended I read “Talent is Overrated”. So, after that extended backstory, here I am having read it with my usual attempt to keep an open, yet appropriately-sceptical mind.

The central theme of the book is that you do not need “talent” to be good at something, you just need lots of time. It challenges the idea that there is a correlation between IQ and success. Research does not support these suggestions.

However, it does make an important point about the quality of practice. It says it is very important, and it is. One of the biggest criticism’s about Gladwell’s 10,000 hours is that he largely ignores quality of practice whereas Colvin stresses it is the most important thing.

The second half of the book turns into a management handbook for motivating your staff. This makes a good point that staff are your most valuable asset. However, some of it felt a little confused. For example it claims you need to have a long-term plan and talks about Panasonic’s 500 year plan. Then it talks about having to reinvent your business model every 3-4 years. How do we reconcile long term plans with the increasingly uncertain future?

The book finishes off by going back to the original topic of why are highly successful people so successful. It discusses age-related degrading of talents and suggests that while we do degrade as we get older, if we continue to push our skills they tend not to degrade much at all (but the rest of our bodies will). I’m not sure on the research on this, though I might just choose to believe it because it sounds pleasing. Ah the bliss of ignorance.

It also puts forward the idea that if you want to be truly amazing at something you need to start really young. This is probably a controversial point, that is probably true. Thus entirely justifying living out your dreams through your kids…

Talent is overrated

River Cottage: Pig in a Day

March 14th, 2015 | Distractions

Oh Mr. Fearnley-Whittingstall. My hero, my idol, for at least the past two months. How much damage you can do with two comments.

River Cottage: Pig in a Day is a course run at River Cottage HQ to teach people how to butcher a big. They then translated it into a two hour DVD. The DVD starts with a really nice section on keeping your own pigs and what fun they can be, before showing footage of sawing through a head and butchering the entire body of a dead one.

There were however two bits that annoyed me. Firstly, Hugh said the only real health problem he gets with his pigs were coughs and colds, that he treats with homoeopathic remedies. Boo! What a confidence knock in an otherwise sensible man.

Though this does have the advantage that you can clearly just ignore colds because they will go away by themselves. Or does it? This brings up an interesting question as to whether placebo works on animals. RationalWiki suggests that you can condition animals to get the benefit.

Secondly he referred to organic salt. What the fuck is organic salt? Presumably one with additives because you need to get the carbon in there somehow…

Anyway, that aside, the show really does embrace Hugh’s “nose to tail” philosophy as he calls it. They eat pretty much everything. I say pretty much because a bit of fat gets cut off, and the eyes come out. However, that is pretty much it. The organs are cooked, the trotters and tail are used for stock, and even the brain is fried up and scoffed.

It was a mildly interesting watch, but I’m not sure how much appeal it has. You are either a) do not have your own pigs, which seems very likely, so how relevant is the content? Or B) you do have your own pigs, in which case are you really going to try and butcher the entire thing based a DVD? If so, I tip my hat to you, you clearly have some balls. Specifically pig’s balls.

Terry Pratchett, 1948-2015

March 13th, 2015 | News

terry-pratchett

Someone once told me that polls of people’s favourite authors of all time consistently came up with only one living author. I don’t know if that is actually true or not, because I can’t find a source. Sadly however, even if it was, it no longer is now.

Jeremy Clarkson is an appalling character

March 12th, 2015 | Religion & Politics, Thoughts

It’s not that vile people like Jeremy Clarkson exist that makes me sad. It is that after he has been allegedly suspended for punching a producer, over half a million of you sign a petition to have him reinstated.

His antics over the years include:

  • Making fun of Gordon Brown for being disabled
  • Using the word “nigger” in a nursery rhyme
  • A series of Nazi jokes at the Tokyo Motor Show
  • A seemingly endless series of racist jokes with targets including India, Mexico, South Korea, Burma, Wales, Romania, Scotland and Japan
  • Using derogatory terms for people with mental health issues
  • Using derogatory terms for gay people

These are just a few of the most prominent. Wikipedia has many, many more. They even have a second page of it. This isn’t even the first time he has physically assaulted someone. Clarkson’s racist, homophobic, sexist, bigoted and violent personality has no place in civilised society, let alone the national media platform that he enjoys.

Stuart Lee does an excellent deconstruction:

NOTE: Since original publication, I have removed Clarkson’s joke about murdering public service workers in front of their families as such comments could be viewed as justifiable in context.

The Drunkard’s Walk

March 11th, 2015 | Books

The Drunkard’s Walk: How Randomness Rules Our Lives is a book about randomness and probability by Leonard Mlodinow.

It is well researched and written. He talks about a lot of the other research cited by similar books, and basically anything that references Daniel Kahneman is probably on the right track. Why Kahneman? Possibly because his research is the best. Or possibly because Kahneman’s work reached the critical mass to make it more popular than anyone else. I would seemed to have missed the point of the book if I didn’t accept that as a possibility.

Mlodinow talks a lot about luck, and how much that is a part of the most successful people. It is a massive part. I often describe it as “the one thing Malcolm Gladwell got right”. See my review of Outliers.

I was already familiar with most of the content of the book, but it was good to have a reminder. Take these points for example:

  • We judge more specific scenarios more likely than general ones. The classic example is a character description of a feminist. We judge “she is a feminist and a bank teller” to be more likely than “she is a bank teller” even though B is contained in A so must be at least as likely.
  • The two daughters problem. If a family has two children and one of them is a daughter, what is the probability that they will have two daughters. It might seem like a half, but the answer is actually a third. This is because there are four possibilities (boy boy, boy girl, girl boy, girl girl) and we only eliminate one (boy boy) by saying they have one daughter.
  • The two daughters with a name problem. What are the probabilities of a family of two children having two girls if they have a girl named Florida? The answer is a half, not a third. This is because families with two daughters have two chances to have one named Florida.

The answers to these questions are often not obvious at first. It took me a bit of time to get my head round them. But that is the point. Humans do not have an innate understanding of probability, we’re actually pretty bad at it a lot of the time.

Then some of it is downright confusing. Take for example the gambler’s fallacy and regression towards the mean.

In the gambler’s fallacy, people think that if black has come up ten times in a row on a roulette wheel, red must be due. Of course it isn’t. The odds are still 50/50. At the same time, if you have just had a really good of ten bets, the odds are that your next run of ten bets will be less good because of regression towards the mean. Holding these two concepts in your head simultaneous and knowing which to apply in each situation becomes incredibly confusing.

There are some other great examples in the book too.

DNA testing is often described as almost perfect. The changes of DNA being confused are incredibly small. Whereas the chances of a witness being wrong are quite high. For more details read The Invisible Gorilla by Christopher Chabris and Daniel Simons.

They correctly point out that faced with witness testimony vs DNA evidence, the DNA evidence is far more likely to be accurate. However, the odds are not millions to one that it will be wrong. Sure, the test itself is that good. But the chance of human error in the lab might be 1%. Thus it will still only be accurate 99% of the time.

Alcohol was another interesting topic. I’ve written several times before about how humans cannot tell the difference between cheap and expensive wine. Mlodinow quotes even more studies. In one, they labelled two bottles as $90 and $10 and subjects judged the expensive wine to be better. They were the same wine in two bottles. In a second cited experiment, food colouring was added to white wine and subjects were then served the same wine in “white” and “red” forms, claiming they could identify the differences.

Something also struck close to home was similar tests on vodka. Mlodinow points out that vodka is naturally without character, so most of it is marketing. Indeed, in a blind taste test, critics could not tell the difference between expensive brands such as Grey Goose and Ketel One and cheap brands – ultimately rating Smirnoff as the best.

I have done a taste test between Smirnoff, Absolut and Grey Goose and there was a clear difference. However, it was not blind and this study suggests that if I did it blind, I could not tell the difference (which I suspect is the case). It’s a good reminder of the power of expectation.

Mlodinow concludes the book by talking more about luck and how successful people are mainly just lucky. That is not to say that they do not tip the balance in their favour by being talented as well, but if you look at someone like Bill Gates, he himself admits he has been lucky to get where he is.

There is an important message to take away from this though. Because it is not innate, and there is a luck element, that gives us control. If we can control how many coin flips we take – in the form of how many times we try, be it in business, learning a new skill, whatever it is – the more chance we have for it to come up heads.

the drunkards walk

River Cottage

March 10th, 2015 | Distractions

Hugh Fearnley-Whittingstall’s third TV series, his most famous, is River Cottage. There are actually lots of them but so far I have watched the original ones, Escape to River Cottage, Return to River Cottage and River Cottage Forever.

This follows him packing up his life in London and moving to Dorset to live as a smallholder – that is someone who has a small farm, primarily used for self subsistence. Each series follows a year.

He seems to be well versed in rural life already. While he clearly isn’t a livestock expert, he does manage to keep them alive and seems familiar with a lot of activities I would not be, such as diving, butchery, smoking meat and wielding a gun. He also manages the first two years in a soft-top classic sports car, before finally giving in and buying a Land Rover (also a soft-top).

I did wonder how real it was. For example he talks about going to do a farmers market to raise some cash for a little project he has on. But was does the £100 actually cover? Presumably not his rent, his vet’s bills, or the large amount of food he buys in to supplement his own stocks. Fun to watch, but I got the distinct impression that undertaking such a project was not actually in the reach of us plebs, despite Hugh’s assertion that we could all do it.

It’s not really a cooking show. He cooks things obviously, but I did not come away with any recipe ideas. It’s just fun to watch (and it is very entertaining), and possible dream.

Cook on the Wild Side

March 9th, 2015 | Distractions

Hugh Fearnley-Whittingstall’s first TV show was called Cook on the Wild Side. In his first series he converted a truck into a “gastro van”, which the back folded out into a complete kitchen for him to cook from anywhere. He then drove round the country foraging for food and cooking it up.

There was a surprisingly amount of illegal activity in it, which was amusing. He tried poaching, trespassing and raiding supermarket bins. He went everywhere from inner city London to the highlands of Scotland. In seemed quite realistic in that a lot of his attempts, especially fishing, just did not work.

In the second series he used a boat that he sailed up the canals and even included a bike with a pedal-powered stove so that he could leave the water whenever he needed.

While the series was highly entertaining, I also took away two practical tips. The first is that you can eat common garden snails. Literally you can just pick them up and fry them. Though you may also want to cleanse them for a few days before doing this. Gorden Ramsey has a great video on this as well:

Secondly Hugh recommends a book called “why not eat insects?” and then goes on to gather up woodlice from a wood and then fry them too. Apparently they taste like shrimp. I like shrimp…

Jane Eyre

March 8th, 2015 | Books

Written by Charlotte Bronte, Jane Eyre makes up and important part of the Bronte sisters work. With Emily Bronte having written Wuthering Heights, these two novels represent the best work of the two sisters. It is only a shame there wasn’t a third Bronte sister to write another great novel. But there wasn’t.

I decided to go for the abridged version. I just couldn’t face the 500-or-so pages of the unabridged version. Of course you lose a lot of the detail that way, but I found it made for a more pleasurable experience for a book that I was not sure how much I would enjoy.

It started off very promising. An attractive young lady being restrained in “the red room”. Though it is luckily it did not end up going this way given how young the character was at the time.

Charlotte’s style conforms more to that of a Jane Austin novel than it does to that of her sisters and I think I am grateful for that. Wuthering Heights was an unpleasant story. It had depth, realism and emotion, and I’m not looking for that in a novel. I’m looking for a Jane Eyre style happy-ish ending.

Jane Eyre