The Page Visibility API

Framegrab from a Google Chrome promotional video: click to view the Page Visibility API demoI’ve built a simple demo of the Page Visibility API, based on an idea of Mike Mahemoff‘s and using his favicon.js.

The API makes it possible to find out when a web page becomes visible or hidden, for example to pause download, processing or playback in order to save CPU and bandwidth.

More information about the API is available from code.google.com and MDN.

I’ve also built a Google Chrome extension that uses the API to pause video when it’s not visible.

Posted in HTML, Uncategorized | Tagged , , | 12 Comments

AppleScript to view HTML in a browser with TextWrangler

TextWranglerI really like TextWrangler, the free Mac text editor from Barebones Software, who make BBEdit.

I’ve just worked out how to set up TextWrangler so you can view HTML files in one or more browsers — simultaneously if necessary, and with keyboard shortcuts.

Mike Piontek at Junecloud gives instructions on how to do this in Safari:

tell application "TextWrangler" to set theFile to file of document 1
tell application "Finder" to open theFile using (path to application "Safari")

Unfortunately, this doesn’t seem to work for Google Chrome.

So I did a bit of hacking (with help from a comment by someone called Rob on TUAW) and came up with this:

tell application "TextWrangler" to set theFile to file of document 1

set appleScriptPath to theFile as text
set currentURL to POSIX path of appleScriptPath
set currentURL to ("file://" & currentURL)

tell application "Google Chrome"
activate
if (exists window 1) and (URL of active tab of window 1 is "chrome://newtab/") then
tell window 1 to set URL of active tab to currentURL
else
open location currentURL
end if
end tell

It may not be elegant, but it works.

Posted in Uncategorized | Tagged , | 8 Comments

Instant search for Shakespeare’s sonnets

Reputedly William Shakespeare, but who knows?

Some bloke with a moustache

I’ve written an application to search Shakespeare’s sonnets, which links to Quarto 1 facsimiles of each of the poems at the the University of Victora Internet Shakespeare Editions website.

You can access it as a plain old web page in Chrome, Safari or Opera, or install the free web app at the Chrome Web Store.

The app doesn’t do much — it’s just very fast, and works locally and offline.

I’m working on a Firefox version using the Indexed Database API. Not sure where Internet Explorer is headed in terms of local database storage.


How to use it

Enter text in the input box at the top of the page to display lines from sonnets containing the text.

Search is not case sensitive. Note that a minimum of two characters must be entered. Line numbers are shown to the right of each line.

Click any line to display the whole sonnet from which it is taken.

Click on a sonnet to display a Quarto 1 facsimiles of it at the the University of Victora Internet Shakespeare Editions website.


How does it work?

The sonnets are stored in JSON format in json/sonnets.js.

The first time the app is first opened, the JSON is parsed and the sonnets are stored locally in a Web SQL database. (I’m working on an IndexedDB version for Firefox and future versions of Chrome and other browsers.)

Whenever query text is entered or altered, the database is queried and any results are formatted and displayed.


Feedback

Please send bug reports, comments or feature requests to samdutton@gmail.com.

Posted in Uncategorized | Tagged , , , | Leave a comment

Framegrabber Chrome extension

I’ve built a free Chrome extension for bookmarking video timecodes and capturing framegrabs.

It’s called Framegrabber and you can get it here.


Framegrabs are still images of individual film frames.

The Framegrabber extension makes it possible to take framegrabs from HTML video elements. Framegrabs can be stored in a local database or opened in a tab so they can be saved as JPEG files.

Framegrabber is also useful for bookmarking video timecodes.

Framegrabber works for any page that uses the HTML video element.

One major caveat: to create framegrabs, video must be from the same host as the page it’s on, so Framegrabber can’t capture framegrabs on sites like YouTube and Vimeo. If Framegrabber cannot capture a framegrab, it will still store the timecode of the current frame.

Videos from which framegrabs can taken can be found on many sites, including Dive Into HTML5, Mozilla and my own website samdutton.com.


How to use Framegrabber

To save framegrabs, use the icons that the extension displays at the top left of video(s) using the HTML video element:

  • click on the green plus icon to open a framegrab in a new tab
  • click on the red circle icon to save a framegrab in local database storage.

Note that on some pages, you may need to start playing the video before an HTML video element is actually added to the page.

Click the extension icon (to the right of the address bar) to display stored framegrabs in a popup. Click a framegrab image in the popup to navigate to the video and timecode from which the framegrab was taken.

How does it work?

Framegrabber uses several relatively new web technologies, including Canvas, HTMLMediaElement and Web SQL Database.

Below are some technical details of how the extension works.

Framegrabber creates a canvas element (but doesn’t add it to the DOM) then uses the drawImage() canvas context method to draw a video frame on it. The canvas toDataURL() method is then used to create a data URL string representing the image. The image data URL can then either be opened in a new tab, or stored locally along with the URL of the page containing the video and the timecode of the framegrab: Framegrabber does everything offline.

Local storage is accomplished using the Chrome Web SQL Data
base implementation, which is fast and reliable enough to store strings such as image data URLs, which can be 200KB or more in size (i.e. 200,000+ characters in length).

When the extension icon is clicked, data URLs are retrieved from the local database and set as the src value for framegrabs displayed in the popup.

Feedback

Please send bug reports, comments or feature requests to samdutton@gmail.com.

Posted in Uncategorized | Leave a comment

School reports: There’s An App For That!

In England, primary school students get reports made up of statements like the following:

She uses descriptive and figurative language successfully.
She is able to use more than one strategy in order to read unfamiliar words, including phonic and contextual knowledge.
She uses a range of strategies to establish meaning.
Her writing conveys meaning in both narrative and non-narrative form.

To me this sounds demented — what the hell is ‘phonic and contextual knowledge’? How many normal people understand the meaning of ‘descriptive and figurative language’?

I was brought up in the golden age of terse, handwritten reports, with their heartfelt insights (“continues to disappoint”) and finely-wrought aperçus (“progress generally acceptable”). The new-fangled language is verbose, detailed and weirdly specific. The tone of voice is personal… but ominously authoritarian: the voice of God, if God was a Grade 7 civil servant.

As a parent governor at a primary school in south London, I asked some teachers to explain. It turns out that primary school reports must consist of statements that reflect individual guidelines of the National Curriculum and various other ‘strategies’.

Teachers, too busy to write individual statements for every child, resort to ‘statement banks’: prefab collections for each subject and level. Enterprising educationalists have gone a step further, sharing statement banks online – here’s a snippet from a collection for Reception pupils from the Times Educational Supplement website:


Personal, Emotional Development

Able
X is very caring and will often initiate play with other children and will look after a classmate who is feeling left out or poorly. X is aware of how to behave within the classroom and generally can be relied on to behave well. She takes responsibility for her own actions and she recognises the consequences of her actions on others. X can concentrate for extended periods of time on topics of her choosing, she needs to develop this further when working on set tasks as she is often eager to rush and wants to choose her own task.

Less Able
X shows an interest in classroom activities and participates well with self chosen activities. X can dress themselves independently but may sometimes need help when it come to their jumper or t-shirt. She can work well with her friends in class and is building on these relationships through play and talking. X can separate from her mum in the morning and feels confident when sitting with or near her friends at the beginning of the day.

The teacher who shared this work observes that the statements ‘can possibly be used as they are’, by which I assume they mean you could adapt statements for each child, just by changing X to the child’s name.

School report comment bank for sale on eBay

As seen on eBay: your child's assessment

I also found school report statements for sale on eBay (see right). Their slogan: ‘A comment for every child!’

Teacher-techies have gone a step further and built applications to automate report writing.

With these you don’t even have to copy and paste: simply feed student data into one end of the sausage machine, and out the other end come ready-to-print ‘personalised’ statements.

One of the most popular is The Report King. This application produces carefully randomised assessments (‘No two reports are the same’) conforming diligently to the rules of the National Curriculum, Primary National Strategies, APP materials and the QCA schemes of work.

Here are some statements I produced in about 20 seconds — all I had to do was select a subject and level:

Semi-automatic report writing

Semi-automatic report writing

Communication, language and literacy

Language for communication and thinking Sam shares his news, elaborating on key events when prompted, and takes turns during paired discussion. He shows a better ability to remember detail from stories and rhymes shared in class, and uses voices for different characters during drama activities.

Reading Sam can explain which parts of a story he liked and enjoys more difficult books. He understands that non-fiction books can be used to answer questions and he reads an increasing number of words by sight.

Writing Sam makes some plausible attempts at writing unfamiliar words and he can write recognisable letters with a pencil. He appreciates that writing is a way of sharing a thought with someone else and he is becoming more confident when copying from the whiteboard.

Likewise, Report Assistant produces ‘professional sounding, individualized report cards in the shortest possible time’, which ‘can be tailored to suit individual students’.

Michael Gove is Watching You

Michael Gove is Watching You

All this automated assessment would be splendid — if we were happy to live in a world where authority meant more than authenticity. There is, after all, something a tiny bit tempting about the nationalisation of language as imagined by Kafka and Orwell and Atwood.

In reality, I think this is… bollocks.

Communication between teachers and parents is important. It should be truthful and accurate. Teachers should not copy and paste — then tell their students not to do the same. The argument that school reports don’t matter — because they’re written in a way that means parents either don’t read or don’t understand them — is ingeniously self-fulfilling, but it doesn’t really help. Assessment and reporting should be done properly, even if that’s a pain.

Assessment statements like those quoted above are supposed to be for parents, and yet they sound like they’re written for the bureaucrats who invented them. Most parents don’t understand educational jargon — and the specificity of the statements falsely implies an accuracy that isn’t possible. How can any teacher forced to write dozens of reports possibly go into such detail with any accuracy? Parents who actually bother to read school reports might naively think that teachers are making genuine, personal, individual statements about their child — which, of course, is a deception.

Maybe, in this reputedly litigious age, teachers are actually scared of saying anything individual and understandable?

Rt Hon Michael Gove MP, Secretary of State for Education

Our Glorious Leader

The response to these problems seems either defeatist, ‘we’re just too busy… it’s always been like that’, or defensive, ‘we have far bigger things to worry about’. Cynics suggest that school reports are inherently useless, so we shouldn’t waste time trying to improve them: a bit rubbish, but really not all that important.

But, but, but… Communication is at the heart of learning (isn’t it?) and schools are setting a bad example. There are, of course, many good teachers who are bad at documentation, or who just do their job and accept the existing guidelines for school reports, or manage to get around them — but that doesn’t mean we shouldn’t rock the boat. If the government is committed to accurate assessment and reporting in schools, they need to legislate for something different from the mess we have now.

The Department for Education (its third rebranding in the last decade) has come up with something called Assessing Pupils’ Progress, but resources for this and other assessment guidelines are difficult to fathom and hard to find. The National Strategies website is a nightmare to navigate (as several teachers have commented). For parents like me who want to find out how school reports work, there’s absolutely sweet FA.

Like most workers politicians refer to as being on the front line (as opposed to back-room bureaucrats) teachers are dogged by documentation. As well as actually having to teach, teachers are now expected to document their class work in detail while they’re working: ‘observing and recording evidence’, to ‘integrate the assessment of pupil’s progress into their teaching’.

This is all the more reason to make school reports more pragmatic: what is their purpose? who are they for? Recent plans to abolish quangos such as QCDA may offer a chance to do something better. In the end, maybe all the Department for Education needs to do is ask parents what they want.

After all, school reports are for parents — aren’t they?

Posted in Education, OFSTED, Primary schools, QCDA, School | Tagged , , , , , | 6 Comments

Shakespeare’s sonnets in JSON format

Title page of the first edition of Shakespeare's sonnets

Title page of the first edition of Shakespeare's sonnets

For what it’s worth, I’ve created a JSON version of Shakespeare’s sonnets.

I’ve validated this with JSON Lint and checked the text against an XML version of the sonnets on the Shakespeare Geek site.

The JSON text is based on the Project Gutenberg text except that I’ve used Arabic numerals for numbering, because that’s what was in the 1609 first quarto edition.

If you like the sonnets, there is a nice facsimile viewer at Internet Shakespeare Editions.

Posted in Literature, Poetry, Shakespeare, Uncategorized | Tagged | Leave a comment

For The Messengers

For The Messengers

Published by Donut Press

Jude Cowan (who works for ITN Source) has written an excellent book of poems ‘in response to the un-packaged daily news footage she was archiving for the Thomson Reuters news agency’.

Posted in Poetry, Uncategorized | Tagged , , | Leave a comment

HTML: The standard that failed?

Below is a response to Neil McAllister’s article about the future of the HTML standard, which starts like this:

HTML is a standard dictated by browser vendors — not an independent body.

That seems to be the message from the Web Hypertext Application Technology Working Group (WHATWG), which last week announced that it would be dropping version numbering from the HTML specification once work on HTML5 is complete. Henceforth, HTML will become a “living standard,” with the most current version of the specification being the one maintained on the group’s website. In other words, the standard is whatever WHATWG says it is this week.

————————————————————————————————————————————–

Jeez… Lighten up!

You paint a gloomy picture of a cliquey oligopoly — whereas in reality, browser standardisation has never been healthier.

The Web is a better place to work right now than ever before, and those of us who were condemned to attempt cross-platform coding in the good old days remember just how bad it used to be. Even Microsoft, traditionally seen as the enemy of open standards, appears to be getting on board: with Internet Explorer 9 they have taken feedback from developers and greatly improved support for HTML5, CSS, ECMAScript and other standards.

In fact, current versions of Internet Explorer and other browsers already implement a high base level of common functionality, parsing, rendering and API support. Again, it’s worth remembering how much things have improved: for example, noone thinks twice about using div elements instead of tables, whereas only a few years ago that was virtually impossible — and noone in their right mind now would use shims and spacers, whereas that used to be only way to achieve reliable cross-platform positioning. The success of Ajax, and JavaScript-heavy sites like Google Maps, also show how far Web standardisation has progressed.

Standardisation is not just about specification documents, either. Libraries like jQuery have become de facto standards, and better coding tools, content management systems, templating toolkits and web frameworks — along with the common adoption of patterns, idioms and other best practices — have encouraged and enabled developers to produce more reliable and efficient web applications that work well for a range of browsers, devices and contexts.

HTML is a standard dictated by browser vendors — not an independent body.

Have you seen the WHATWG mailing list? The participants are an eclectic, international mix, and most of them don’t work for browser vendors. Anyone with a half-decent idea gets a hearing and, whatever the faults of the WHATWG, it’s hard to imagine an alternative that would be more democratic and open. Besides, HTML specifications *should* get input from industry, just like HTTP, DVB, or any other successful standard. As for the role of Ian Hickson, it’s worth remembering that much of the best Web technology has involved a benevolent dictator — that just seems to be the way that things get done.

implementing half-baked ideas and incomplete specifications, often in inconsistent ways. Most famously, the HTML5 committee gave up trying to specify codecs for the much-anticipated video tag when no consensus could be reached, leaving each browser vendor to support whichever video formats it saw fit.

You’re blaming the messenger for the bad news. The WHATWG is in no way responsible for the lack of consensus. Standardisation of video codecs and containers is complex and difficult, for technical, legal and other reasons, and (unfortunately) well and truly out of the control of any single standards organisation. ‘Half-baked’ is wrong, too: in reality, the HTML audio and video elements have been a huge success, incredibly liberating to those of us once condemned to dealing with plugins. These elements have already been used in a range of highly functional and innovative applications, and led to further innovations such as the Mozilla Audio API. (And, just to be pedantic, it’s the video element, not the video tag.)

Without so much as a version number to go by, it will be virtually impossible for the customer to understand — or even express — just what form of HTML that actually is. … Without a version numbering scheme for HTML, there will be no easy way to measure what has changed between the browser I’m using today and the browser I could upgrade to …

Are you saying that people care about the standards, and the versions of the standards, that their browser conforms to? This has never been the case, and seems unlikely to change. In fact, most browser users shouldn't need to know anything about web standards. Besides, browsers, just like other technologies, have never supported the whole of any standard. What interests browser users — alongside speed, reliability and all the rest — is functionality: not some bureaucratic seal of approval.

But hardest hit by this change will surely be independent Web developers, who now face the prospect of coding to a standard

Huh? Developers don’t ‘code to a standard’ — unless they don’t know what they’re doing. Decent developers code to capabilities. The language in this sentence sounds tendentious, too: ‘hardest hit by this change will surely be independent Web developers’. Bring on the violins!

But how do you set a scope of work and specify coding standards for a project when you can’t even express which version of the HTML specifications you’re coding to?

Again, this is not the way things work. Web development projects are (or should be) scoped to fit the audience: who they are, what they have, what they want and might want, their environment — and so on. Organisations can and should use coding guidelines, such as agreement on browser coverage, JavaScript libraries, patterns, idioms, coding layout and commenting styles, but I’ve never worked on a Web project that was scoped to a standard of any kind. That just wouldn’t make sense.

Overall, I don’t get the point of this article. ‘HTML5’ has been appropriated by marketeers to represent much more than the WHATWG draft specification. In a way, this is great — poor old HTML 4.01 never had such brand value! — but it just goes to show how meaningless version numbering has become.

In general, software and standard version numbering already has a checkered history, and getting rid of it for the HTML standard makes a lot of sense. Browser vendors will continue to implement parts of the standard instead of waiting for some bureaucratic finale — and to me that’s a good thing.

Posted in Google, HTML, html5, Ian Hickson, standards, WHATWG | Leave a comment

Debugging apps and extensions for the Google Chrome Web Store

Firstly: don’t forget that newer versions of Chrome support much of the ECMAScript 5 spec, including Array methods such as forEach and map — which can simplify code and make it easier to debug. Conversely, be aware that a few users (especially in corporate environments) may not have an up-to-date version of Chrome.

One other simple trick: bookmark the Extensions page chrome://extensions.

…and remember to click on the Developer mode +/- button at the top right of the Extensions page to access technical details for extensions.

Chrome debugging basics

If you’re building Chrome extensions, you’ll need to use the Chrome developer tools and get access to the JavaScript console for error and log messages.

From the Tools menu in the settings menu (the spanner icon to the right of the address bar):

  • select Developer tools (Control-Shift-I)
  • to view the Javascript console, select JavaScript console (Control-Shift-J) or, if you have the Developer tools already open, click on the Console button at the top of the Developer tools pane, or click on the Show console button at the bottom left.

How to get at the JavaScript console

JavaScript for Chrome extensions can live in three different places: in a pop-up, in content scripts and in the background page.

To view the Chrome Developer Tools for a pop-up, right-click the extension icon to the right of the browser address bar, and select Inspect Element. (In earlier versions of Chrome, this was done by selecting Inspect pop-up.) Click the Show console button near the bottom left of the Tools window to view the console. Sometimes when debugging pop-ups, it’s easier to send log messages to a content script: see the section below about displaying popup debug.

To get at content scripts, open the JavaScript console on any page that has injected scripts.

A link to a Developer Tools window for the background page for each extension is available from the Extensions page, chrome://extensions. (If you can’t see the links to the background page for each extension, e.g. background.html, make sure you’ve clicked the Developer mode button at the top right of the page.)

Gotchas

Messaging, events, closures and callbacks are a central part of the Chrome extension architecture. Be aware of scope and context rules — there’s a good tutorial about closures on the JavaScript Kit site. Where possible, be explicit about your intended scope and give a qualified name for variables.

When using objects in a function, you may need to pass a ‘this’ value, use class members, or specify context by qualifying variable names.

Watch out for context in callbacks. For example:

MyClass.prototype = {
    doSomething: function() {
        chrome.tabs.getSelected(null, function(tab) {
            // 'this' refers to the chrome.tabs.getSelected method, 
            // so this.handleTabData(tab) is not defined!    
      });
    },
    handleTabData: function(tab) {
        // ...
    } 
}

Given the mix of synchronous and asynchronous code execution in Chrome extensions, it’s easy to run into problems with scope and timing. For example:

function foo() {
    var selectedTabId;
    chrome.tabs.getSelected(null, function(tab) {
       selectedTabId = tab.id;
    });
    // selectedTabId is still null 
}

Sending and receiving messages

This can get confusing…

From background page to content script

In the background page:

function responseCallback(value) { // used below
    console.log(value); 
}

chrome.tabs.onSelectionChanged.addListener(
    function handleSelectionChange(tabId, selectInfo) {
        var requestObject = {"backgroundKey": "backgroundValue"};
        chrome.tabs.sendRequest(tabId, requestObject, 
            responseCallback);
    }
);

In the content script:

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        console.log(request);
        sendResponse({"contentKey": "contentValue"}); 
        // NB: always respond, if only with an empty object
        // otherwise request remains open    
    }
);

From pop-up to content script

In the popup, get the selected tab, then send a message:

chrome.tabs.getSelected(null, function(tab) {
        tabId = tab.id;
        tabUrl = tab.url;
        chrome.tabs.sendRequest(tabId, {"fooKey": "fooValue"}, 
            initPage);
    }
);

In the content script (as above):

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        console.log(request);
        sendResponse({"fooKey": "fooValue"});
    }
);

From pop-up to background page

Pop-ups have access to the DOMWindow object for the background page (if there is one) so you can call background page functions directly, like this:

var backgroundPage = chrome.extension.getBackgroundPage(); 
var foo = {"fooKey": "fooValue"}; 
backgroundPage.doSomething(foo);

It may be worth declaring a global backgroundPage variable in the popup — and also setting global variables for the current tabId and tabUrl.

I’ve also found it useful to add a doQuery function to the background page for use with local database storage:

backgroundPage.doQuery("DELETE FROM fooTable WHERE pageUrl='" + 
    tabUrl + "' AND foo='" + foo + "'", callbackFunction); 

…and watch out for all those ‘other’ tabs!

Be careful to consider tabs with chrome URLs such as chrome://newtab (when a new tab is created) and tabs for data URLs, view-source or other resources such as images.

These ‘pages’ with no source code will not be injected with content scripts — and this might cause your extension to malfunction if, for example, a popup expects to interact with a script in the selected tab page, or if a page or browser action relies on content scripts to perform tasks when the current tab changes, such as updating a tooltip or badge.

Displaying pop-up debug

Sometimes it’s useful to log messages from popup scripts without using the Inspect pop-up function. This is also a way to get debug output from a popup if you’re forced to use an older version of Chrome that doesn’t have the Inspect pop-up function.

You can do this by adding a logging function to your pop-up script like this:

function clog(val) {
    var message = JSON.stringify(val).replace(/n/g, " ");
    chrome.tabs.sendRequest(tabId, 
        {"type": "consoleLog", "value": message}); 
}

…and listening for log messages in a content script like this:

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        if (request.type === "consoleLog") {
            console.log(request.value);
        }
        // ...
    }
);

This enables debug messages from the popup to be viewed in the JavaScript console for the current page.

Posted in Google Chrome, HTML | Tagged , | 7 Comments

The BBC, Glow and jQuery

From the BBC Glow Google Group:

> On 14/10/2010 15:16, “Sooty the dog” wrote:
>> Hello, what’s happening with Glow 2 dev? Is it canned? I had a quick
>> look on your issues tracker via the BBC website and didn’t see any
>> activity….. Looking at the API, are you just going to deploy
>> something as a JQuery plugin?

> Glow 2 is no longer in active development. We are currently researching and
> developing a BBC JavaScript library that uses jQuery for its core DOM
> manipulation functionality.
> —
> Michael Mathews
> Senior Web Developer
> BBC Frameworks

Posted in Uncategorized | Tagged , , | Leave a comment

Additional methods for JavaScript Array

Below is a basic set of additions to the JavaScript Array prototype to make it easier to work with numeric arrays.

Disclaimer: these additions work for me, but I can’t vouch for their correctness or efficiency, with all values in all situations on all platforms.

I’m also aware that adding methods to an existing class is, in many situations, a bad idea! These additions were useful to me in a highly constrained context but, obviously, this kind of approach does not scale well, particularly with multiple coders and multiple JavaScript libraries.


Array.prototype.absMax = function(){
return Math.max.apply({}, Math.abs(this));
};

Array.prototype.absMin = function(){
return Math.min.apply({}, Math.abs(this));
};

Array.prototype.avg = function(){
return this.sum() / this.length;
};

Array.prototype.max = function(){
return Math.max.apply({}, this);
};

Array.prototype.median = function(){
var sortedArray = this.slice().sort(function(a, b){return a - b;}); // make a deep copy and sort it
return sortedArray[Math.floor(this.length / 2)]; // for one item, i = 0; two items, i = 1; 3 items, i = 1...
};

Array.prototype.min = function(){
return Math.min.apply({}, this);
};

Array.prototype.numSort = function(){
return this.sort(function(a, b){return a - b;});
};

Array.prototype.sum = function(){
for (var i = 0, sum = 0 ; i != this.length; ++i) {
var n = this[i];
if(!isNaN(n)) {
sum += n;
}
}
return sum;
};

Posted in Uncategorized | Tagged , , | Leave a comment

Kenneth Tynan prophesies CGI

If only Kenneth Tynan had lived to see Toy Story.

Here’s a diary entry of his from nearly 40 years ago…

I am certain that the full potential of cinema will not be achieved until it concentrates on the development of full-length cartoons. … I do not, by this, mean stylised drawings of talking animals; nor would anyone imagine anything so absurd were it not for the fact that Walt Disney’s accidental domination of the cartoon scene has made it impossible for us to think of it except in terms of clothed, speaking animals and birds going through the motions designed to entertain the nursery. It’s significant that the first X-rated or ‘adult’ cartoons, Fritz the Cat, has pigs, crows and cats in its cast but no people. It is as if the first oil painter had painted only trees, and the art of painting had subsequently been defined as the art of painting trees.

What the cinema ought to be doing (and to have done) is to present coloured images of reality (or fantasy) designed by artists. At present — by using the camera to photograph reality — it is confining itself to a function that is part newsreel and part photographed theatre. In pure cinema there would be no real actors and no real backgrounds; there would be drawn (or painted) people in drawn (or painted) settings. Only thus will cinema achieve its historic mission of rising above and eventually replacing the novel.

From The Diaries of Kenneth Tynan, 20 July 1972

Posted in Uncategorized | Tagged , , , | Leave a comment

jQuery debugging tips

I’ve been using jQuery a lot lately and occasionally ended up with strange errors — particularly given the tendency in JavaScript to use custom events, closures and callbacks.

Below are some gotchas to avoid.

$. versus $

If you use the dollar sign syntax for methods such as $.each(), it’s easy to make a mistake like the following:

$.('#container').append('foo'); // dodgy!

This leads to really puzzling error messages such as ‘Uncaught SyntaxError: Unexpected token (‘ (in Chrome) or ‘XML filter is applied to non-XML value (function (a, b) {return new (c.fn.init)(a, b);})’ (in Firefox).

Maybe this is another reason to use jQuery.each() not $.each();

ID selectors

This is so obvious, but it’s bitten me more than once.

When selecting an element by ID — especially if you’re used to using getElementById() — it’s easy to forget to add the hash character.

Make sure to use $(“#elementId”) not $(“elementId”).

Properties and attributes

Make sure whether you should be using .css, .attr or a (DOM) object property. For example: background-image is a CSS property, not an attribute.

DOM element or jQuery object?

It’s easy to miss the obvious…

For example, all a method on a video element like this:

    $(“#myVideo”)[0].play();

This, of course, will not work:

    $(“#myVideo”).play();

Synchronous and asynchronous

Be careful when mixing synchronous and asynchronous code.

This is not particularly a jQuery problem — here’s an example from Google Chrome Extensions (which make extensive use of callbacks):

function foo() {
var selectedTabId;
chrome.tabs.getSelected(null, function(tab) {
selectedTabId = tab.id;
});
// selectedTabId is still null
}

Don’t forget the “px”!

var  jGrabImg = $(““).attr(“src”, grabImgUrl).css({“right”: (videoRight – 10) + “px”, “top”: (videoTop + 10) + “px”});

ready() and setTimeout()

Again, this is not specifically a jQuery problem, but be aware of scope in $(document).ready(function() {…}); 

For example, variables declared inside the ready function are not visible to setTimeout code called via a string argument, which is evaluated in the context of Window:

$(document).ready(function() {
var foo = “blah”;
setTimeout(“alert(foo)”, 1000); // foo is undefined when alert is called
});

You can use a function argument like this, because :

$(document).ready(function() {
var foo = “blah”;
setTimeout(function(){alert(foo)}, 1000); // foo is defined
});

In Firefox and Chrome (at least) you can give the setTimeout method one or more arguments, like this:

$(document).ready(function() {
function f(arg) {
alert(arg);
}
var v= “blah”;
setTimeout(f, 100, v);
});

Alternatively you can use closures:

$(document).ready(function() {
(function () {
var arg = “blah”;
setTimeout(function(){alert(arg);}, 100);
})();
});

Callbacks and scope

Also watch out for scope in jQuery callbacks. For example:

MyClass.prototype = {
doSomething: function() {
$.getJSON(myUrl, function(data) {
// this.handleData(data) won’t work!
});
},
handleData: function(data) {
// do something with data
}
}

You’ll need to make ‘this’ available in the callback or, for static methods at least, name the function MyClass.handleData.

The same applies for each():

myJQueryObj.each(function(){ …})

Objects and arrays and trigger()

If you use an array as the argument to the jQuery trigger method, any associated bind callback will be called with multiple arguments, one for each item in the array. This can be confusing when triggering an event from a $.getJSON callback. If the JSON data object returned is an array and you use this object as an argument to a trigger call, it looks as if you are ‘sending’ a single object (an array), whereas on the receiving end, via bind, this is seen as multiple parameters.

Posted in Uncategorized | Tagged , , | 2 Comments

Brain control interfaces: the Emotiv EPOC headset

1872 Sholes and Glidden typewriter, image from Wikipedia

So 1870s

I used to think that sooner or later we’d get rid of clunky computer input devices and use ‘thought control’ instead. It seems crazy that we’re still wiggling mice and pecking away at keyboards.

Now I’m not so sure.

Today I had a go at an EEG-powered brain-computer interface: the Emotiv EPOC headset. I trained it to move a cube on a screen up and down and backwards and forwards. It’s easy to extrapolate going from this to (say) using it as a TV remote control.

Emotiv EPOC headset, image from Wikipedia

The mind control mohawk

The Emotiv headset is a wonderful piece of kit with huge potential.

It’s a relatively cheap device with which, for example, a person with no motor control could (at the very least) change channels on a TV without having to wait for someone to do it for them.

However, after an hour or two with the Emotiv, I began to realise the advantages of physical interfaces.

Some very non-expert thoughts below…

  • A lot of our interactions with things works well because they happen sub (un? pre?) consciously and non-verbally — think of typing (if you’re a good typist), or those times when you make a regular car journey ‘without even thinking about it’, or when you can only remember how you do something (like using a computer program) when you’re actually actually doing it. As it stands, BCIs (Brain Control Interfaces) require you to consciously *think* about what you want to happen. There is, at least as I understand it, no way yet to use this kind of interface to control a computer in the ‘unthinking’ way you type or move a mouse.
  • BCIs are inclined to lots of false positives — signals that you didn’t intend — especially if you’re not concentrating 100% on using the BCI controller!
  • BCIs require a change in behaviour and, in my experience, interfere with the flow of thoughts.
  • At the moment, BCIs are relatively slow — whereas, especially for experienced users, interactions with physical interfaces can be remarkably fast.
  • BCIs are difficult to use in environments that are perceptually noisy, or if you’re distracted — let alone when (say) interacting with media which, by their nature, are desgned to evoke sensory responses, thoughts and feelings.
  • In our interactions with things, we can do lots of different things (almost) at the same time — for example, in a car: check street sign, indicate, brake, check for pedestrians, change gear, check for traffic, turn. As yet, BCIs require one thing at a time.
Posted in Uncategorized | Tagged , , , , | 1 Comment

HTML 5 video — now with tracks

Ian Hickson has added to the HTML draft standard a specification for timed tracks.

This provides a simple, standardised way to add timed auxiliary content to video.

This spec has huge potential: timed cues for arbitrary content synchronised with media playback – as well as simpler subtitle/caption/description use cases. Once again the web becomes less static and – maybe – more like a broadcast medium.

A video with tracks might look like this:

<video src="foo.ogv">
<track kind="captions" src="fooCaptions.srt" srclang="en"></track>
<track kind="descriptions" src="fooDesciptions.srt" srclang="en"></track>
<track kind="chapters" src="fooChapters.srt" srclang="en"></track>
<track kind="subtitles" src="fooSubtitles_de.srt" srclang="de"></track>
<track kind="subtitles" src="fooSubtitles_en.srt" srclang="en"></track>
<track kind="subtitles" src="fooSubtitles_ja.srt" srclang="ja"></track>
<track kind="subtitles" src="fooSubtitles_oz.srt" srclang="oz"></track>
<track kind="metadata" src="keyStage3.srt" srclang="en" label="Key Stage 3"></track>
<track kind="metadata" src="keyStage4.srt" srclang="en" label="Key Stage 4"></track>
<track kind="metadata" src="keyStage5.srt" srclang="en" label="Key Stage 5"></track>
</video>

Tracks use the WebSRT data format which — for cue in a kind = “metadata” track — might look like this:

  10:00.000 --> 20:00.000
  {title:"Fish", moreinfo:"http://en.wikipedia.org/wiki/Fish", image:"images/fish.jpg"}

The spec also defines CSS extensions, like this:

  ::cue { color: green; font: 1em sans-serif; }
  ::cue-part(1) { font: bold 1em serif; }

Documentation

The track element:
http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-track-element

WebSRT:
http://www.whatwg.org/specs/web-apps/current-work/websrt.html

Timed track formats:
http://wiki.whatwg.org/wiki/Timed_track_formats

Timed track use cases:
http://wiki.whatwg.org/wiki/Timed_tracks

Posted in HTML, Uncategorized, WHATWG | Tagged , , , , , , , , | Leave a comment

iPad first impressions

I had a go on a friend’s iPad last weekend.

First thing I thought: what if I dropped it?

It’s hard to believe an iPad would survive falling off a kitchen worktop, or getting trodden on.

Having said that, the iPad feels really solid – or, you could say, quite heavy.

It’s smaller than I expected – I imagined something like a tablet PC, whereas it *seems* not much bigger than a couple of iPhones side by side.

This might mean you start seeing iPads on the Tube (or the Metro or the subway or…)

The complete lack of ports is very striking when you’re actually holding the thing. People have been grumbling about this, but I think the emphasis on wireless connectivity to peripherals and the internet really makes sense. (I’m old enough to remember when people complained about the original iMac’s lack of built-in floppy drive!)

Battery life is apparently excellent – my friend told me it’s way better than his iPhone.

Video quality is fantastic. This could be the major selling point: for use on trains and planes and by kids on long car journeys.

Sound, for such a tiny speaker, is actually pretty good.

Having a large, shiny dark screen means it’s prone to paw prints, especially with kids around. But so what?

Usability outdoors is reasonable but not great.

The interface and apps feel like they’re not quite right for the screen size, though it feels very fast and responsive.

All in all – still not sure what the iPad is for. Is this the ‘kitchen’ device?

Posted in Uncategorized | Tagged , , , , | Leave a comment

Why we need better IT teaching for girls

http://www.apple.com/pr/bios/

http://www.microsoft.com/presspass/exec/leadership/default.aspx

http://www.samsung.com/uk/aboutsamsung/management/boardofdirectors.html

http://www.sony.net/SonyInfo/CorporateInfo/executive/index.html

http://www.nokia.com/about-nokia/corporate-governance/group-executive-board

http://www.canon.com/corp/executive.html

http://www.google.com/corporate/execs.html

And take a look at this list of founding CEOs from Ben Horowiz’s blog:

Acer—Stan Shih
Adobe—John Warnock
Amazon – Jeff Bezos
AMD—Jerry Sanders III
Apple – Steve Jobs
DEC—Ken Olsen
Dell—Michael Dell
EA—Trip Hawkins
EDS —Ross Perot
Hewlett-Packard—Dave Packard
IBM—Thomas Watson, Sr. (*)
Intel—Andy Grove (*)
Intuit—Scott Cook
Microsoft —Bill Gates
Motorola—Paul Galvin
nVidia—Jen-Hsun Huang
Oracle—Larry Ellison
Peoplesoft—Dave Duffield
Salesforce.com—Marc Benioff
Seagate—Al Shugart
Siebel—Tom Siebel
Sony—Akio Morita
Sun—Scott McNeely
VMware—Diane Greene

Posted in Uncategorized | 2 Comments

Eliza lives!

...in the form of IKEA's Anna!

Nice top

http://193.108.42.79/ikea-uk/cgi-bin/ikea-uk.cgi

Sample conversation below.

You just said : That's a lovely microphone you're wearing.
I have an outfit that my creators made for me, but because 
I'm an IKEA Online Assistant, I don't wear real clothes.

You just said : Saucy!
I'm not sure what you're trying to exclaim. Please be a little more detailed if you can.

You just said : You wear virtual clothes?
I think you're confused or trying to ask me a question, but I need more than that 
to give you a proper answer. Please try again.

You just said : Do you sell Volvos?
Transport is not something about which I'm programmed to discuss. Sorry.

You just said : Are you Swedish?
Let's talk about IKEA now.
Posted in Uncategorized | Leave a comment

Wolfram Alpha: don’t ask the wrong questions

I’ve had a go at the Wolfram Alpha ‘knowledge engine’ preview.

Sadly, in my experience, it’s a bit disappointing: US-centric and effective only in specific, limited domains.

It gave no results for many of my queries, for example:

  • ‘What is the population of Adelaide’ (capital of South Australia)
  • ‘Tim Winton prizes’ (Australian writer)
  • ‘where is Kapunda’ (town in South Australia — misinterpreted as an animal, kakunda)
  • ‘where is Wandsworth, London’ (Wandsworth is a London borough — gives a ‘did you mean wadsworth’ response)
  • ‘why is DAB radio delayed’ (and variations — ‘Wolfram|Alpha isn’t sure what to do with your input’)

Alpha is a great project with a lot of potential — to provide well presented, accurate answers to questions asked in natural language.

But they better be quick or the world — or Google — will move on.

Posted in Uncategorized | 4 Comments

Treat Yourself Right

The UK’s National Health Service is running a good and sensible campaign on how best to seek medical treatment.

Thankfully they haven’t wasted any NHS cash on campaign artwork, resorting instead to pictures from a cheap and very cheerful People of Many Lands clip-art collection:

Treat yourself right

Beware the demented dentist

Unfortunately, their miniature ‘healthcare professionals’ don’t really look like real people. Don’t trust them — they’re zombies! Everyone has nice, healthy pink cheeks — even the black man!  The sweet girl with the almond-shaped face and plaits looks like she sprang from some dodgy old Ladybird story with a title like Little Running Bird’s Big Adventure. The guy with the bag (‘You forgot your lunch!’) is meant to be ‘ethnic’ in some way. Is he Turkish or Portuguese, or a bit of both? And what do his triangular hair and big eyebrows signify?

But… It’s the technology that really worries me. The mad, waving dentist who’s been at the nitrous oxide — wild orange hair, Jaws teeth — has on his head one of those old torch things that doctors used to wear in cigarette ads.  What a fun guy, with his green latex hands! Another man is holding up what I think is meant to be a good-news X-ray, but looks like some scary relic of medical history.

If advertisements for the NHS computer department featured floppy disks and men wielding soldering irons, I’d be tempted to go elsewhere. I suspect that younger patients won’t even recognise these objects from a (thankfully) bygone age.

…and not to be picky, given the NHS’s daily miracles, but the dress sense of their mini-zombies leaves a lot to be desired. I can’t believe my National Insurance is funding their terrible wardrobe. Blue-and-green-should-never-be-seen was never more true, Mr Dentist  — and  big trousers, big red trousers, Mr X-ray White Stripes, I don’t think so…

Posted in NHS, Uncategorized, Wandsworth | Tagged | Leave a comment