2009/11/12

TextMate, Emacs and META indent-region

[cross-posted from the Desert Moon blog.]

I haven't used GNU Emacs very much since switching to TextMate in 2005. One Emacs feature which I really miss in TextMate is indent-region. It lets you take an entire region of code, whatever its language, whatever its mix of tabs and spaces and indentation widths, and re-format it using your preferred indentation style.

But wait! Emacs has a batch mode, and you can drive it from TextMate. Many thanks to Gragusa's Things for showing the way.

The post on Gragusa's Things is specific to R code, but I'm more interested in re-formatting C and C++ code. Here's my first cut at a general TextMate Bundle to re-format code regardless of the source language:

#!/usr/local/bin/python2.6
"""
Use Emacs to re-indent regions of the current buffer.
Inspired by
http://gragusa.wordpress.com/2007/11/11/textmate-emacs-like-indentation-for-r-files/
"""
import tempfile
import os
import sys
import subprocess

# Use the same filename extension so Emacs will know which
# mode to use.
ext = os.path.splitext(os.environ["TM_FILEPATH"])[-1]
outf = tempfile.NamedTemporaryFile(suffix=ext, delete=False)
pathname = outf.name

outf.write(os.environ["TM_SELECTED_TEXT"])
outf.close()

args = [
"emacs", "-batch", pathname,
# Assume no emacs-startup.el
"--eval", "(setq indent-tabs-mode nil)",
"--eval", '(c-set-style "java")',
"--eval", "(setq c-basic-offset 4)",
"--eval", "(indent-region (point-min) (point-max) nil)",
"-f", "save-buffer"]
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode:
print(err)

inf = open(pathname, "r")
sys.stdout.write(inf.read())
inf.close()

os.remove(pathname)


NB:
  1. Due to the use of the delete=False keyword argument to tempfile.NamedTemporaryFile, this command bundle requires Python 2.6+.
  2. TextMate on OS X 10.5 won't, by default, have /usr/local/bin in its path; hence the pathetic shebang.


Anyway, install this as a new TextMate command bundle, assign a Key Equivalent such as ⌘-Shift-R, and enjoy.

2009/11/03

Creating an 'hg ignore' extension

[cross-posted from the Desert Moon blog.]

I often wish Mercurial had an 'hg ignore' command similar to 'bzr ignore'. Turns out it's pretty easy to add one:


#!/usr/bin/env python
"""Ignore pathnames and patterns"""

import os

def ignore(ui, repo, *pathnames):
"""Ignore the given pathnames and patterns."""
outf = open(os.path.join(repo.root, ".hgignore"), "a")
for p in pathnames:
outf.write(p + "\n")
outf.close()
return

cmdtable = {
'ignore': (ignore, [], "hg ignore pathname [pathname]"),
}


To use this, save it to a file such as ${HOME}/platform/independent/lib/hg/ignore.py. Then add the extension to your ${HOME}/.hgrc:
[extensions]
~/platform/independent/lib/hg/ignore.py

2009/09/24

Running TileCache within a Django Application

Punchline

Here is how to serve TileCache tile images from within a Django application.


from TileCache.Service import Service

_service = Service(...)

def get_tile(request):
global _service

format, image = _service.dispatchRequest(
request.GET, request.path, request.method,
request.get_host())
result = HttpResponse(str(image), mimetype=format)
return result


Scenario

You're building a low-traffic Django-based GIS application, and you need to serve your own map layers. You're using TileCache to improve your application's performance. But installation and configuration are hassles.

  • All of your servers must run with the right user and group IDs, so the Django app can expire the tile cache when necessary.
  • Your Django app needs to understand the structure of the tile cache, so it can remove the correct tile images when the underlying data changes.
  • Etc.

standalone_tilecache.png


This would all be much easier if you could serve TileCache requests from within your Django application. They're both Python-based; why not?

django_plus_tilecache.png


The TileCache code base includes sample code that shows how to run TileCache as a CGI or a FastCGI service. I couldn't find any sample code for running TileCache within a Django application, but it was easy to convert the cgiHandler code for use with Django's HttpRequest objects.

Installation Prerequisites

In order for TileCache to generate its own tiles, instead of delegating to a separate mapserver instance, you must already have compiled and installed mapserver's Python mapscript bindings. For instructions on compiling the bindings see the mapscript/python/README file in the mapserver source distribution.

Configuring TileCache


import os
thisdir = os.path.abspath(os.path.dirname(__file__))
def relpath(p):
return os.path.abspath(os.path.join(thisdir, p))

from TileCache.Service import Service
import TileCache.Layers.MapServer as MS

# Create the service 'singleton'.
_mapfile = relpath("../mapserv/data/mapfile.map")

_service = Service(
_cache, # See "Cache Invalidation", below
{
"basic": MS.MapServer(
"basic", _mapfile, layers="basic", debug=False),
}
)


Handling Tile Requests

This is the sweet part. It's derived from the cgiHandler() example in the TileCache source code, but Django's HttpRequest class makes the implementation very simple:


def get_tile(request):
global _service

format, image = _service.dispatchRequest(
request.GET, request.path, request.method,
request.get_host())
result = HttpResponse(str(image), mimetype=format)
return result


What About Feature Info Requests?

I don't know much about the required web API of a WMS server, but it appears as if the same URL must serve both tiles and feature info requests; the type of request is determined by the Request querystring parameter.

Django's dispatch system is based on URL pathnames; I'm not aware of any way to dispatch based on query string parameters. So you'll need to either configure your web server (e.g. Apache) to rewrite WMS requests to distinct URLs provided by your Django app, or you'll need to do some dispatch within your Django app.

Suppose you opt for the latter. Then your urls.py might look something like this:

...
url(r'^wms/$', 'world.views.wms', name='wms'),
...

and in world/views.py you might have this:

def wms(request):
if request.GET.get("request") == "GetFeatureInfo":
return get_feature_info(request)
return get_tile(request)

Cache Invalidation

For my web app, several of the tile layers are derived from a Django model which is updated via the admin interface. Whenever the model changes, the tile cache for the corresponding layer(s) needs to be invalidated, so the images can be regenerated.

The TileCache Cache interface doesn't provide for invalidation. Since I'm using a filesystem-based cache, I subclassed TileCache.Caches.Disk to create a Disk cache which does support invalidation.

import shutil
from TileCache.Caches.Disk import Disk

class InvalidatingDisk(Disk):
"""A Disk cache which can invalidate its contents,
layer by layer."""
def invalidate(self, layerName=None):
if self.basedir:
pathname = self.basedir
if layerName is not None:
pathname = os.path.join(self.basedir,
layerName)
shutil.rmtree(pathname, ignore_errors=True)

2009/09/22

Introducing Google Chrome Frame

Introducing Google Chrome Frame:

"With Google Chrome Frame, developers can now take advantage of the latest open web technologies, even in Internet Explorer. From a faster Javascript engine, to support for current web technologies like HTML5's offline capabilities and <canvas>, to modern CSS/Layout handling, Google Chrome Frame enables these features within IE with no additional coding or testing for different browser versions.
To start using Google Chrome Frame, all developers need to do is to add a single tag:


<meta equiv="X-UA-Compatible" content="chrome=1">
"


I guess that's good news. Makes you wonder why the target audience wouldn't just install Google Chrome. But I suppose this lets people continue to use IE while using modern web facilites on sites which require them.

2009/09/14

TR: China Wind Energy Potential, HVDC

(Just taking notes, trying to understand what HVDC is, what it has to do with variable power sources such as wind, and why it makes buried transmission lines convenient.)

Technology Review: China's Potent Wind Potential:

"The major grid upgrades already under way in China are making extensive use of continental-scale high-voltage direct-current (HVDC) lines, which remain the stuff of supergrid blueprints in Europe and the United States. 'They are leading the world in implementing long-distance transmission schemes,' says Bjarne Andersen, director of U.K.-based consultancy Andersen Power Electronic Solutions and an expert in the ultra-efficient HVDC technology."


Technology Review: Europe Backs Supergrids:
"This summer [2008], for example, a negotiator appointed by the EC convinced France to accept a new transmission connection with Spain, breaking a 15-year impasse over expanding power exchanges between the countries. Use of high-voltage DC (HVDC) technology will enable planners to bury the new line and thereby overcome local opposition to conventional overhead AC transmission lines."


Wikipedia explains how HVDC can have low power losses:
"Power in a circuit is proportional to the current, but the power lost as heat in the wires is proportional to the square of the current. However, power is also proportional to voltage, so for a given power level, higher voltage can be traded off for lower current. Thus, the higher the voltage, the lower the power loss."
"The advantage of HVDC is the ability to transmit large amounts of power over long distances with lower capital costs and with lower losses than AC."


Lots of interesting stuff in the Wikipedia article. This excerpt seems to explain the connection between HVDC and variable power sources:
"Because HVDC allows power transmission between unsynchronised AC distribution systems, it can help increase system stability, by preventing cascading failures from propagating from one part of a wider power transmission grid to another. Changes in load that would cause portions of an AC network to become unsynchronized and separate would not similarly affect a DC link, and the power flow through the DC link would tend to stabilize the AC network. The magnitude and direction of power flow through a DC link can be directly commanded, and changed as needed to support the AC networks at either end of the DC link. This has caused many power system operators to contemplate wider use of HVDC technology for its stability benefits alone."


2009/08/17

ActionScript: TileList, deleting, scrolling backwards

I have a Flex app which shows users a TiledList of chemical structure depictions. Since it can be a large list, it's lazy-loaded from the server as the user scrolls through the list.

Users can delete items from the list, with undo. In order to do this with reasonable performance, once the app has received confirmation from the server that an item has been deleted, it clears out the single deleted item from its local lazy-list.

To undo the deletion locally, the Flex app fills the correct lazy-list entry with an ItemPendingError; that error gets thrown as soon as the TileList tries to retrieve the item.

All of this works okay when the row containing the undeleted item is already visible. On the other hand, if the user has scrolled away from the row where the undeleted item will reappear, then when (s)he scrolls back the TileList simply empties out that item and all of the successive items in the row. Ugly!

ugly_repaint.png


Workaround

When the item is undeleted, immediately try to retrieve it via getItemAt(itemIndex). Catch the resulting ItemPendingError and register an ItemResponder. When the ItemResponder's result or fault method is called, tell the TileList to invalidateList(). If the undeleted item actually contains a value, the TileList will repaint correctly -- no more unsightly gaps.


import mx.collections.errors.ItemPendingError;
import mx.collections.ItemResponder;
[...]
try {
structures.getItemAt(offset);
} catch (e:ItemPendingError) {
e.addResponder(
new ItemResponder(
function(result:Object, token:Object = null):void {
tilelist.invalidateList();
},
function(error:Object, token:Object = null):void {
tilelist.invalidateList();
}));
}

2009/08/10

I like Mike -- General Michael Collins, That Is

This year's John Glenn Lecture Series featured Sen. Glenn, Chris Kraft and the three Apollo 11 astronauts. Michael Collins was as smart, funny and humble as in "When We Left Earth." His talk starts roughly 55 minutes in.

Apologizing for the lecture-unfriendly layout of the IMAX theater, which he helped approve:

"I'm down here in the bottom of a black hole about to be sucked in by gravity..."


After putting up this picture, which he took as the LEM began its descent to the lunar surface:
michael_collins_background_img.png
"I like that photo, it's my favorite one. You see in the little thing there are 3 billion people, and then in the big thing there are two people..."


About the glistening blue earth in the background:
"Serene it is not. Fragile it is. The world population when we flew to the moon was 3 billion people. Today it's over six and headed for eight, so the experts say. In my view this growth is not wise, healthy or sustainable[...]
"Our economic models are all predicated on growth. They require it. Grow or die, or maybe both: the dead zone created by the runoff from the Mississippi into the Gulf of Mexico is now larger than the State of New Jersey, and still growing...
"We need a new economic paradigm that somehow can produce prosperity without this kind of growth."



The video: http://www.youtube.com/watch?v=w9fCPhspOCQ

2009/07/22

Sen. Lamar Alexander on Nuclear Energy

On July 13th Sen. Lamar Alexander held a press conference to propose a low-cost, clean energy plan centered on nuclear energy. I still haven't digested the whole proposal, but it's an interesting read.

C-SPAN has video. Senator Alexander's website has the proposal in PDF format.

One bullet item from the press conference really resonated:

"We want an America in which we are not creating “energy sprawl” by occupying vast tracts of farmlands, deserts, and mountaintops with energy installations that ruin scenic landscapes. The Great American Outdoors is a revered part of the American character. We have spent a century preserving it. We do not want to destroy the environment in the name of saving the environment."


Amen to that! "Energy installations" can be beautiful...

Navajo Power Plant Lake Powell

But I'd hate to see the Taos valley scarred over with wind turbines.

Anyway, just now the most cost effective way to address the electricity needs of the U.S. seems to be to reduce demand, by improving energy efficiency. Going forward, since our population is projected to grow by 44% by 2050, we'll probably still need to increase electricity production.

If we're willing to change U.S. policy on re-processing spent nuclear fuel, Sen. Alexander's proposal could work. France provides an existence proof.



Life Shore Gits Tedious

I was hoping to find numbers on total electricity consumption by country, to compare France's production capacity to our own projected needs. Instead I found this Wikipedia entry, which describes the currently-decreasing per capita electricity consumption of the U.S.; notes that the U.S. still consumes considerably more electricity per capita than countries such as Germany; discusses various ways of measuring national energy efficiency (e.g. energy intensity); describes the relationship between population growth and electricity consumption; and so forth.

Why does the reading list never get shorter? :)

2009/07/21

Unresponsive console.app on OS X 10.5

Recently, when I opened console.app and tried to view either Console Messages or All Messages, cpu usage spiked and console.app became unresponsive. Activity Monitor showed aslmanager using up all of the cpu.

The following discussion thread helped solve the problem. The final required step seems to have been to remove the entire /private/var/log/asl/ directory before restarting syslogd.

Apple - Support - Discussions - ASLMANAGER hogging CPU, resisting fix? ...

Update: It looks like aslmanager first appeared in OS X 10.5.6. It also looks like the asl facility is Apple's replacement for syslogd, created to make it easier to quickly search system logs. From the asl(3) man page: "This API permits clients to create queries and search the message data store for matching messages."

2009/07/18

I really like New Mexico...

... but every once in awhile I wish I was back in Dayton.

Apollo astronauts relive experiences at ceremony

2009/07/15

Bravo Bill Gates

In the same vein as yesterday's half-baked post, Bill Gates has helped make freely viewable (if not downloadable) a lecture series by Richard Feynman.

From CNET:

"Gates first saw the series of lectures 20 years ago on vacation and dreamed of being able to make them broadly available. [...] Tapping his colleagues in Redmond to create interactive software to accompany the videos, Gates is making the collection available free from the Microsoft Research Web site."


The name of the site?
Project Tuva. Nice touch.


The site doesn't seem to load in Safari 4 w. Silverlight 2, but Firefox 3.5 / Mac works fine.

2009/07/14

Lots of offsite backups

[behold, another half-baked post]

The Register says that NASA will on Thursday release 'greatly improved' footage from the Apollo 11 landing. They speculate that this footage is derived from original tapes of the landing, which in 2006 NASA admitted having lost.

I hope NASA makes the new video freely available for download. If they do, they'll get thousands (millions?) of offsite backups for free, hosted by history buffs around the world. And they won't need to worry so much about losing the originals again.

The Library of Congress has already done something similar with the nation's library, e.g. by posting images to Flickr.

Granted, backups are useless if you can't restore them. It should be easy to put out a call for well-known documents such as the lunar landing videos. But LoC has all kinds of documents ranging from famous to obscure, and retrieving them by broadcasting a call to volunteers would be dicey at best.

So it's interesting to see that LoC is launching a pilot program "to test the use of cloud technologies to enable perpetual access to digital content."

2009/07/02

Canada and Japan blocking climate-change deal, Sir David King warns - Times Online

Canada and Japan blocking climate-change deal, Sir David King warns - Times Online:

"Governments previously were able to hide behind the US's intransigence on climate change, he said, but the pro-climate policies being launched by the Obama administration means this is no longer possible. 'The time has come for people to reveal their cards,' he told delegates."


via @TomRaferty by way of @timoreilly.

2009/06/21

The Benefits of a Classical Education

Tim O'Reilly has posted yet another article full of thought-provoking nuggets, in which he answers interview questions for a special report:

The Benefits of a Classical Education

The article muses on ways in which capitalism can be altruistic rather than greedy; bumps up my respect for West Virginia's Robert Byrd, whom I often see as a detriment to Congress; and includes incisive quotes from Alexander the Great and Mark Twain ("While history doesn't repeat itself, it does rhyme"). All this in response to the first interview question.

A Supreme Leader Loses His Aura - NYTimes.com

If only because of the Times's reputation in recent years, I have to wonder how much of this report is real. Still, a compelling read.

Op-Ed Columnist - A Supreme Leader Loses His Aura as Iranians Flock to the Streets - NYTimes.com

@terrycojones has posted a link to the Wikipedia article on Iran's 1953 coup. Among other things I hadn't known that British Petroleum had its origins in the Anglo-Persian Oil Company. http://bit.ly/11q8Oq

2009/06/19

Opponents blast Northwest Quadrant housing project

Santa Fe's northwest quadrant housing project has all of the smells of the malling of Beavercreek, Ohio. City staff will just keep asking for approval until they get the answer they want.

Opponents blast Northwest Quadrant housing project:

"Other residents questioned [...] a plan to pump sewage uphill and other facets.
The housing project on city-owned land would be concentrated on about 122 acres of the 540-acre Northwest Quadrant. The proposal calls for construction of more than 750 housing units, including single-family homes and multi-family complexes that would rise up to three stories tall [emph. added] as well as up to 110,000 [square] feet of mixed-use development that could include commercial uses. "


<Incoherent Pre-coffee Ramblings>

Up to three stories tall... on top of a ridge line. There goes the neighborhood.

Would there be no value in turning this land into public space?

When I first moved to Santa Fe ten years ago, I could walk to the top of the ridge above my apartment and take in a view that encompassed Los Alamos, the Sangre de Cristos, and the Sandias more than fifty miles to the south. The view is still available, and it's on land which city staff wants to bury under multi-story housing.

These days I live "in the hole" of Casa Solana, just to the south of the proposed development. The targeted land is still the best place, for miles around, to watch the fog of a morning storm turn into ragged, fast-moving tufts of cloud.

Of course, when I first moved here the open area was also filled with old mattresses, broken beer bottles and old engine blocks. Human nature is everywhere the same.

Perhaps awesome views are of value mainly to those who have lived too long amid urban sprawl. Even city planners, who must know that scenery is one of the reasons people visit northern New Mexico, believe they will gain more from taxes on developed land than from natural beauty.

"You can't eat scenery." — Victor, "Local Hero"

</Incoherent Pre-coffee Ramblings>

2009/06/16

Palm's Big Opportunity


Via Macintouch:

"An iPhone app developer's world is lonely...
Three parties are involved: the developers (us), Apple, and the customers. For the most part, Apple stands between us and our customers[...] we can't issue refunds, we can only issue a few promo copies, we can't collect upgrade revenue, we can't respond to App Store reviews, we can't provide installation support, and we can't release updates to address customers' issues in a reasonable amount of time. We can't even tell them when the next update will be available, because we honestly don't know. [...] Our customers, like us, are mostly in the dark with this process, and we can't do much to help them.
For the most part, it's just us and Apple in the room.

And Apple's a brick wall.
"


In large part, Palm has based webOS on open standards. The Palm pre user experience is reported to be very good. Sprint (tethering) and AT&T (rug-yanking over data plans) both stink.

So will Palm be able to draw developers, and customers, to its platform by running a less authoritarian app store than Apple's? Will it even try to do so? Here's hoping...

2009/06/12

We are too many

Sciam examines relationships between environmental degradation and population. Still haven't digested it all. This looks like the punchline:

Population and Sustainability: Can We Avoid Limiting the Number of People?: Scientific American:

"...the evidence suggests that what women want—and have always wanted—is not so much to have more children as to have more for a smaller number of children they can reliably raise to healthy adulthood. Women left to their own devices, contraceptive or otherwise, would collectively ‘control’ population while acting on their own intentions."

2009/05/29

The TSA - back in bounds?

AOPA Online: TSA lessens security restrictions on transient pilots:

"According to the new directive, transient pilots who fly into commercial-service airports no longer need to get an airport badge or background check. However, they must remain close to their aircraft, leaving it only to walk to and from the fixed-base operator, service provider, or airport exit. The TSA also has said that it will make provisions for self-fueling operations and grant allowances for emergency situations."


Score one for AOPA.

2009/05/22

...Mentally awake...

Brain Power - At Card Table, Clues to a Lucid Old Age - Series - NYTimes.com:

"Interacting with people regularly, even strangers, uses easily as much brain power as doing puzzles, and it wouldn't surprise me if this is what it's all about."


Heck, I have a hard time just remembering names during introductions...

2009/05/21

H1N1 Death totals

The CSV data from the rhizalabs site does seem to show more than 150 deaths worldwide from H1N1. I'm not sure why the number is higher than the totals quoted elsewhere, but the CSV data does point to an excellent source of summary data: the Mexican government's Health - Mexico website. (I'm not sure about the proper site name. The URL is http://portal.salud.gob.mx/.)

In my previous post I wondered about the distribution of ages in fatal cases. The PDF reports from the Mexican health site present exactly that information (albeit for Mexico only), very clearly. See for example page 4 of http://portal.salud.gob.mx/descargas/pdf/influenza/situacion_actual_epidemia_190509.pdf

U.S. Says Older People Appear Safer From New Flu Strain - NYTimes.com

U.S. Says Older People Appear Safer From New Flu Strain - NYTimes.com:

"...federal health officials said on Wednesday that people born before 1957 appear to have some immunity to the swine flu virus now circulating.
Tests on blood serum from older people showed that they had antibodies that attacked the new virus, Dr. Daniel Jernigan, chief flu epidemiologist at the Centers for Disease Control and Prevention, said in a telephone news conference."


It would be interesting to see the distribution of ages in all confirmed incidents. Who aggregates that data?


Self-Serving Status Update

I've continued working on the Mesa H1N1 interactive timeline site. It now includes a graph of cumulative incidents (confirmed, suspected, fatal) over time. The number of new incidents worldwide has grown enough that I'm going to need to refactor the code, to better limit (through aggregation) the number of incident markers which must be placed on the map.

I'm still having trouble with a discrepancy in the time-series graph. The development server yields 86 deaths worldwide as of 20 May 2009, whereas the production server shows 154 deaths. Both are supposed to be using the same code, and the same database. I'm reloading the production database now.

It appears that http://flutracker.rhizalabs.com is still the best source of incident data, although there are a few discrepancies in its records. If anyone knows of an authoritative source of detailed incident data, please let me know via the comments.

2009/05/04

More about masks and flu transmission

I really need to learn to read...

How can masks be effective in preventing spread of viral infections, when viral particles are so small and when experiments with guinea pigs show that coughing and sneezing aren't required for transmission?

From the PNAS journal article:

"Our results indicate that droplet transmission of influenza virus occurs between guinea pigs..."


Granted, I haven't dug into the article for information on the droplets' sizes, but this suggests all kinds of variables to examine: mask porosity, how vapor/droplets condense onto masks, etc.

More anecdotal evidence on the effectiveness of masks in preventing secondary pneumonia, at least, comes from "The Great Influenza". From page 211:
"Capps did write the JAMA article. He reported finding the masks [used by patients with respiratory disease at Camp Grant near Rockford, IL] so successful that after less than three weeks of experimenting he had abandoned testing and simply started using them 'as a routine measure'."


They didn't always work. Page 215, describing the September 1918 wave of infection:
"Despite all precautions, despite wearing surgical masks and gowns... 43 percent of the staff... required hospitalization. Ten nurses at this single hospital died."

2009/04/30

“It's Good Weather for a Race”

Couldn't help thinking of Dian Chapman when I read this:

“It's Good Weather for a Race”:

"because when it comes to their service and sacrifice, warm words and gestures are more than warranted, but they're not nearly enough."

Technology Review: Swine Flu Genome Hints at Milder Virus

People exposed to the 1957 flu pandemic may have some immunity to the current H1N1.

Technology Review: Blogs: TR Editors' blog: Swine Flu Genome Hints at Milder Virus:

"Ralph Tripp, an influenza expert at the University of Georgia, said that his early analysis of the virus' protein-making instructions suggested that people exposed to the 1957 flu pandemic--which killed up to 2 million people worldwide--may have some immunity to the new strain. That could explain why older people have been spared in Mexico, where the swine flu has been most deadly."


Secrets of the Dead: Killer Flu suggested that the distribution of deaths by age in the 1918 pandemic hinted at a prior outbreak, about fifty years earlier.

2009/04/28

Swine Flu Genes From Pigs Only, Not Humans or Birds | Wired Science

Swine Flu Genes From Pigs Only, Not Humans or Birds | Wired Science:

"‘The new neuraminidase gene that came in from Eurasian swine is one we’ve never before seen circulating in humans,’ said Rambaut. ‘That’s one of the reasons it’s spreading rapidly. Very few people will have any immunity to this particular combination, which is what gives the concern that this will be a pandemic rather than just a normal seasonal flu outbreak. It remains to be seen how much and to what extent there is existing immunity.’"


Update 2009/04/30: The following article is more recent than the one above, but is it based on the "earlier reports" mentioned in the Wired article?

Technology Review: Hunting for Clues in the Swine Flu Genetic Code:
"The new swine flu virus appears to have done more swapping than usual, with genetic segments from four different sources: North American swine influenza viruses, North American avian influenza viruses, one gene segment from a human influenza virus, and two gene segments that are normally found in swine influenza viruses in Asia and in Europe.
"Parts of it are from the original 1918 virus, parts are similar to the current circulating H1N1 strain from seasonal flu," says Sasisekharan..."

Ford Fusion hybrid hypermiles, goes 1,445 miles on a single tank

Ford finally beat my 1990 Honda CRX :)

Ford Fusion hybrid hypermiles, goes 1,445 miles on a single tank:

" On the 1,445.7-mile trip, the Ford Fusion hybrid was pushed to an average of 81.5 mpg."


For the record, the CRX routinely topped 50 mpg on the interstates around Dayton. Descending out of the San Juans it could top 60 mpg. Two seats. No air conditioning.

So masks *do* work...

An earlier post expressed skepticism about how effectively masks prevent transmission of flu. Now a clinical trial has shown they can prevent transmission of disease from others to the wearer:

Worried about the flu? Get a mask: Scientific American Blog:

"All of the participants were initially healthy but at risk for catching viruses from their children, who had documented cases of respiratory illness. The researchers found that, after a week, the non-mask wearers were four times more likely to catch a variety of viruses, including the common cold and flu, than those who wore them properly (meaning they strapped them on whenever they happened to be in the same room as their sick children). The masks appeared to be equally effective."


If I'm reading correctly, plain old surgical masks were just as effective at preventing transmission as the more expensive P2 masks, which are "specially designed to filter out water droplets containing viruses".

2009/04/25

A few comments on pandemic influenza - fluidinfo

A few comments on pandemic influenza:

"The acting-director of the CDC has already said: "There are things that we see that suggest that containment is not very likely." That is a remarkably candid statement. I think it's very clear that the cat is out of the bag."


via Tim O'Reilly

Influenza Recap

Fear, anger and fatalism over swine flu in Mexico:

"But it may be too late to contain the outbreak, given how widespread the known cases are. If the confirmed deaths are the first signs of a pandemic, then cases are probably incubating around the world by now, said Dr. Michael Osterholm, a pandemic flu expert at the University of Minnesota.
No vaccine specifically protects against swine flu, and it is unclear how much protection current human flu vaccines might offer.

In Mexico City's Zona Rosa neighborhood, teenagers with spiky hair and tight jeans laughed at the danger.
'People are giving too much importance to something that isn't that big of a deal,' said Oscar Zarate, 19, shouting over the loud music and the jostling crowd outside a packed night club."


It will be interesting to see how this develops.

About a year and a half ago I was involved in developing a web application for visualizing results of pandemic simulations. It was intended as a disaster-preparedness application for governments and large (esp. multinational) corporations. The effects of all of the mitigations discussed in the article -- travel restriction, vaccinations, antiviral therapies, etc. -- could be compared in the web app.

Mitigation

I'm a little skeptical of the effectiveness of surgical masks, which seem to be a big feature of the initial response. Are masks really effective at keeping small viruses out of suspension in the atmosphere? The CDC says only that:
"Very little is known about the benefits of wearing facemasks and respirators to help control the spread of pandemic flu."


Recent experiments with guinea pigs showed that coughing and sneezing were not necessary for transmission of flu virus. Instead, atmospheric temperature and humidity determined how well the virus could be suspended in air, which is where it ended up as a result of normal exhalations by the test animals.

Those experiments, incidentally, were inspired by a report of events in southwestern New Mexico:
In an article published in 1919 that details the progression of the 1918 influenza epidemic at Camp Cody, New Mexico, the authors describe a parallel outbreak of pneumonial disease among their laboratory guinea pigs.


"The Great Influenza" gave a good account of the mitigations attempted in 1918 -- including use of surgical masks -- and of their effectiveness. The only thing which really worked then was quarantine. For example, Gunnison County Colorado escaped the 1918 flu with only two deaths, thanks to its stringent quarantine efforts. Silverton lost 10% of its population.


Early Detection

One question which our web application failed to answer was: how do you know when an outbreak is underway, i.e. how do you know when to start mitigation?

It's interesting that Google Flu Trends seems not to have picked up on this outbreak. Granted GFT monitors trends in the United States alone; but the CDC is already aware of cases in California and Texas.

Further Reading -- er, Viewing

PBS has produced some good documentaries on the 1918 flu.

"American Experience: Influenza 1918" (website) focuses on what it was like to live through the pandemic.

Although it's somewhat dated (IIRC it precedes successful recreation of the 1918 virus), "Secrets of the Dead: Killer Flu" (website) is a fascinating detective story about efforts to find the origins, and the keys to the effectiveness, of the 1918 flu.

2009/04/24

A Little Air Pollution Boosts Vegetation’s Carbon Uptake / Science News

A Little Air Pollution Boosts Vegetation’s Carbon Uptake / Science News:

"‘Surprisingly, the effects of atmospheric pollution seem to have enhanced global plant productivity by as much as 25 percent from 1960 to 1999,’ Mercado notes."


(See also the Nova episode on global dimming.)

This begs a rank-amateur question: are plants with needle-shaped leaves adapted for clear atmospheric conditions?

Developing Django apps with zc.buildout

Found this excellent introduction via Looking for quotes about Buildout.

Developing Django apps with zc.buildout:

"...

Finally, Buildout generated a bin/python interpreter."


So buildout makes it easy to create isolated Python environments, just like virtualenv, but perhaps with a different goal: isolated development environments vs. isolated deployment environments? Not sure; gotta read more...

2009/04/21

An Introduction to W3C Widgets

An Introduction to W3C Widgets:

"The king of browser compatibility tables, ppk, recently posted an introduction to W3C Widgets:

"


A new web standard to cover Konfabulator, Dashboard et al?

2009/04/17

Lang.NET 2009 at Ted Leung on the Air

Gratis ago ad Ted Leung for posting his summary of Lang.NET 2009. It seems like every time I see one of his summaries, my reading and projects lists grow.

Newspeak and Hopscotch
More reading here. Ted also links indirectly to the video of Gilad Bracha's talk.

Powershell

[Jeffrey Snover] seemed to think that UNIX shells could gain a fair amount of PowerShell’s capabilities by recognizing that pipes ship bytestreams, adopting a data format (like JSON or XML) for those byte streams, and proceeding from there. That might be true technically, but that would be a huge cultural change for that community.

Hm... imagine a /usr/bin_json/ sitting alongside /usr/bin. The first prototypes of the utilities therein could be based on David Beazley's tutorial "A Curious Course on Coroutines and Concurrency". (Start at slide 34 of the presentation slides.)

Monads
[Erik Meijer] then used mindless symbol pushing to demonstrate that [IEnumerable and IObservable] were duals of each other, and that they obeyed the rules for monads.

I'm so far behind on terminology... what the heck is a monad? Google suggests it's what Pythonistas would call a list comprehension or a generator expression.

Favorite Quote
I suspect that this is the only conference I will go to all year where Macs are the minority.

2009/04/10

Update: The TSA oversteps its bounds. Again.

(My earlier note is here.)

.:: Aero-News Network: The Aviation and Aerospace World's Daily/Real-Time News and Information Service ::.:

"Rex Tippetts of Grand Junction's Walker Field (GJT) estimates he'll need 2,000 additional security checks and badges. 'It's out of control. We have a large maintenance operation here with 400 people. We have a large interagency fire-fighting operation here, with maintenance facilities.'
To defray costs of the programs, pilots needing access to the ramp at Grand Junction will be charged $130 each for badges... which will not be honored at any other airport."


AOPA Online: Pilots unhappy with TSA security directive:
"Under the current version of the directive, pilots based [emph. added] at air carrier airports are required to undergo a security threat assessment and receive a security badge in order to continue to have unescorted access to their airports."


AOPA seems to be less concerned than Aero-News Network about Security Directive 8F. AOPA indicates that the directive requires security badges for GA pilots, but only at their home airports. ANN seems to interpret the directive to mean that pilots will need badges for all subject commercial airports which they visit. Or else, on arrival at such an airport, to remain in their cockpits until a badged escort arrives.

Either way, it's a PITA. One might think TSA was trying to destroy general aviation.

2009/04/09

Ford plans to increase efficiency by dramatically reducing weight

Ford plans to increase efficiency by dramatically reducing weight:

"Ford plans to cut 500 to 750 pounds of flab from each automobile that it redesigns. A reduction of weight on this magnitude should allow Ford to reduce the size of the engine powering the vehicle, further increasing fuel efficiency. "


Has Amory Lovins (or perhaps Bright Automotive) been consulting with Ford?

2009/04/02

Seagate, new Mac Mini, Firewire vs. USB

I recently bought a new Mac Mini, and wanted to connect my ~ 2 year-old Seagate 500GB drive[1] to it. I'd hooked up a couple of other drives via USB without incident. But the Seagate started giving me headaches right away.

Folders on the Seagate kept disappearing. When I'd try to disconnect the drive to cycle power on it, the Finder would report that it was still in use. If I went ahead and cycled power, I'd get a nasty warning dialog, but the drive would come back undamaged.

The system logs showed that the kernel started getting read errors on the drive just before each disappearing act.

Sometimes the problems would start almost as soon as the drive was recognized by the system. Sometimes they'd appear more than eight hours after the drive came online.

I've used this Seagate for a couple of years with no problems, on an iMac, via Firewire 400. I tried connecting it to the iMac again, this time via USB. No disappearing folders. Hmm.

I've read reports of Mac and Windows users having issues with Seagate drives whose firmware settings cause them to spin down after a few minutes of inactivity; they never spin back up. That doesn't seem to be the cause of this intermittent problem, but I can't rule it out.

In any case, a few days ago I ordered a Firewire 800-400 cable from Amazon, and used it to connect the Seagate to the Mac Mini's FW 800 port. So far — fingers crossed — all is well!



[1] It's an ST3500641CBRK.

2009/03/29

Perception is Truth

It's time to green this old (White) House - again:

"During George W. Bush's two terms, workers installed three solar systems, including a thermal setup on the pool cabana that heats water for the pool and showers, and photovoltaic panels atop a maintenance shed that supplement the mansion's electrical supply. "

2009/03/18

FactCheck.org: Education Spin

FactCheck.org: Education Spin:

  • The high school dropout rate hasn't 'tripled in the past 30 years,' as Obama claimed. According to the Department of Education, it has actually declined by a third[...]
  • Obama also set a goal 'of having the highest proportion of college graduates in the world' by 2020. But in terms of bachelor's degrees, we're nearly there. The U.S. is already second only to Norway in the percentage of adults age 25 to 64 with a four-year degree, and trails by just 1 percentage point.


Nobody listens to the real climate change experts - Telegraph

Nobody listens to the real climate change experts - Telegraph:

"Far from rising with CO2, as the models are programmed to predict they should, the satellite-measured temperature curve has flattened out and then dropped. If the present trend were to continue, the world in 2100 would not in fact be hotter but 1.1C cooler than the 1979-1998 average."
"The best correlation for temperature fluctuations is not CO2 but the magnetic activity of the sun. (For an admirable summary of proceedings by the Australian paleoclimatologist Professor Bob Carter, Google "Heartland" and "Quadrant")."


Here's an example:
"Dr Soon also described the empirical test as to whether extra carbon dioxide will produce extra warming that is conducted in Salt Lake City, and other similar cities, every winter. There, a winter CO2 dome attains CO2 levels up to 500 ppm, as compared to the present background atmospheric level of 380 ppm. Yet no discernible enhanced warming is present in the measured temperature curve for Salt Lake City. It follows that the worldwide rush to inhibit CO2, at huge cost, will have no effect on future climate whatsoever. “The role of CO2 in the climate system is just miniscule”, Dr Soon said."

2009/03/17

Scripting News: 3/17/2009

Scripting News: 3/17/2009:

"to the assembled educators -- you owe it to the next generations, who you serve, to prepare them for the world they will live in as adults, not the world we grew up in. Teach all of them the basics of journalism, no matter what they came to Cal to study. Everyone is now a journalist. You'll see an explosion in your craft, but it will cease to be a profession."


Emphasis added, etc.

2009/03/16

[CentOS-virt] CentOS 5.1 guide for VMware Fusion

I just installed CentOS 5.2 for x86_64 under VMware Fusion 2.0.2. Most things worked without tweaking, but the mouse cursor was always offset from the host system mouse, even when VMware was running full-screen.

This post took care of the problem. If I'm reading correctly, the problem was in X11 configuration, and the fix was to use the vmmouse driver with the "CorePointer" option.

Thanks, Bradley Sepos!

2009/03/13

d(rank)/dt > 0

PolitiFact | 8th graders are in 9th, but showing improvement, not falling:

"We considered giving the president partial credit since American students did come in 9th. But the point of his statement was that they had 'fallen' to that position and that mathematics performance in the U.S. is getting worse relative to other countries. And that's just plain False."

Change you can see through

Obama Administration Declares Proposed IP Treaty a 'National Security' Secret | Threat Level from Wired.com:

"...now, like Bush before him, Obama is playing the national security card to hide details of the controversial Anti-Counterfeiting Trade Agreement being negotiated across the globe."
"...the proposed trade accord would [likely] criminalize peer-to-peer file sharing, subject iPods to border searches and allow internet service providers to monitor their customers' communications."


Not good.

2009/03/08

The TSA oversteps its bounds. Again.

.:: Aero-News Network: The Aviation and Aerospace World's Daily/Real-Time News and Information Service ::.:

It presently appears that anyone on the ramp without a TSA ID is subject to fines or convictions in unknown amounts and arrest or detainment by unknown persons...


It is clear the Montrose Airport Appreciation day [...] could be a bit of an issue and the TSA suggested local law enforcement could somehow staff the escort necessities on the field. How exactly do you escort a large milling crowd?


[2009/03/11]

"As for our common defense, we reject as false the choice between our safety and our ideals." If the President really meant what he said, then he will act quickly to rein in the TSA.

2009/03/05

Web Hooks ≈ callback URLs

WTF is a Web Hook?:

"In short, a web hook, or "http callback" allows you to subscribe to another website's events with a URL. You tell a website, "Hey, when some event happens, send some information about it to this URL". Why? It doesn't matter, it's up to the developer to decide what to do with that information."


(low-lumen) Enlightenment

I begin to see how to apply component-oriented techniques to distributed/federated web application development. Thanks to John Herren (bwo Tim O'Reilly) for the clue.

Stainless for OS X Leopard

Stainless for OS X Leopard:

"A prime example is parallel sessions, which allow you to log into a site using different credentials in separate tabs at the same time. This new technology is woven throughout Stainless, from the private cookie storage system, to session-aware bookmarks that remember the session in which they were saved."


That would be useful for website development, whether testing authentication or propagation of messages/event notifications among users.

Guess I should download and give it a try. So many new tools, so little time...

2009/03/04

FF3.1b2, Safari 4b, and html 5 canvas, continued

The previous post described improved support for the HTML 5 canvas. It turns out the latest betas of both Firefox and Safari also support the canvas toDataURL method.

An obvious use for this method is to let users easily copy and paste rendered depictions into other applications.

    function saveToBitmap() {
var canv = $('#canv');
var img = $('img#bitmap');
img.attr('src', canv[0].toDataURL());
};


toDataURL_result.png

Firefox 3.1b2, Safari 4 Beta and HTML 5 canvas text

This will be useful for depicting chemical structures using HTML5 canvas: both Safari 4 beta and Firefox 3.1b2 support the HTML5 canvas text rendering APIs.

There are still rough edges, e.g. it's hard to measure text dimensions and therefore hard to position text properly. Still, it's great to see!

$(document).ready(function() {
function redraw() {
var canv = $('#canv');
var w = canv.width();
var h = canv.height();
// Let canvas know how big CSS wants it to be.
canv.attr("width", w);
canv.attr("height", h);
var ctx = canv[0].getContext("2d");

ctx.clearRect(0, 0, w, h);

var msg = "Hello, Safari text.";
var fontSpec = "24pt Verdana";

// Find out the dimensions of the rendered msg.
var e = $('<span style="visibility:hidden;font:' + fontSpec + '">' +
msg + '</span>');
$('body').append(e);
var tw = e.width();
var th = e.height();
e.remove();

ctx.save();
ctx.translate(w/2, h/2);
// Indented to highlight transformation state.
ctx.save();
ctx.rotate(-45 * Math.PI / 180.0);
ctx.translate(-tw/2, th/2);
ctx.font = fontSpec;
ctx.fillText(msg, 0, 0);
ctx.restore();
ctx.restore();
};
redraw();
});

2009/03/03

Ubuntu 8.10 and Intel i845 chipsets

Today I tried to install Ubuntu 8.10 on an old Dell Inspiron 1100 laptop. Most of the process went well, but when I tried to login the screen went black.

Okay, sometimes it went to the default amber Ubuntu background color. No matter: I never got any windows or menus. Since I was unfamiliar with Ubuntu's key bindings, the only way out was to cycle power.

It turns out that compiz, which provides the default Ubuntu 8.10 window manager, does not like the old i845 graphics chipset.

Google eventually turned up a way to disable compiz. Here's what worked for me.

Summary

Login using a Failsafe Terminal session, remove compiz and compiz-core, then logout and log back in using an Xclient script session.

Details

  1. Boot as usual.
  2. Before logging in, click the Options link at the bottom left of the display.
  3. Click Select Session...
  4. Click the Failsafe Terminal radio button.
  5. Click the Change Session button.
  6. A dialog will pop up, explaining that this is the Failsafe xterm session. Click OK.
  7. An xterm will open. At its prompt, type
    sudo apt-get remove compiz compiz-core
  8. Enter your password, etc. and confirm the package removal.
  9. When the removal completes, type
    metacity --replace &
    (I'm not sure this is necessary.)
  10. Exit the shell.
  11. When the login screen re-appears, click Options.
  12. Click Select Session...
  13. Click the Run Xclient script radio button.
  14. Click Change Session.
  15. Login again.


TODO

When I get more free time I need to repeat the entire installation process, this time collecting detailed information on the failure. Given enough info, I bet the Ubuntu and/or Compiz teams would be able to fix this problem.

2009/02/25

Japan's boffins: Global warming isn't man-made - The Register

Japan's boffins: Global warming isn't man-made — The Register:

The Register's title is an understatement. The report from The Japan Society of Energy and Resources goes beyond questioning human origins of global warming. It also claims that the pattern of warming since the mid-20th century has ceased.

Excerpts:

One of the five contributors compares computer climate modelling to ancient astrology. Others castigate the paucity of the US ground temperature data set used to support the hypothesis [emph. added], and declare that the unambiguous warming trend from the mid-part of the 20th Century has ceased.


The article includes a translation of parts of the report.
Global mean temperature rose continuously from 1800-1850. The rate of increase was .05 degrees Celsius per 100 years. This was mostly unrelated to CO2 gas (CO2 began to increase suddenly after 1946. Until the sudden increase, the CO2 emissions rate had been almost unchanged for 100 years). However, since 2001, this increase halted. Despite this, CO2 emissions are still increasing.


There is no prediction of this halt in global warming in IPCC simulations.


Hm, I thought there was. Certainly the halt has been discussed online — fun example here — and it has been attributed to a trough in sunspot activity...

But the report addresses this point, too, and goes on to say
...climate change and solar activity's relationship is inconclusive. It is necessary to increase research efforts into the relationship between Earth's climate fluctuations and solar activity.

2009/02/24

ADC - CSS Recipes for WebKit

Safari 4 Beta has some nice features. Some have apparently been around since Safari 3, but I didn't notice. For example:

ADC — CSS Recipes for WebKit:

"Getting columns right on webpages using pure CSS instead of HTML tables has always been tricky. Since the CSS3 properties for multi-column layout are implemented in Safari and WebKit, you can clearly define the number of columns [and] the gap between the columns...

This code defines that the HTML in the columns div tag should be presented in three columns. Each paragraph is its own column."


Wow, that's nice! It means you can define a fluid multi-column layout and have content flow between those columns.
safari_4_columns_1.png

Granted, the layout can do some strange things when images bleed across columns.
safari_4_columns_2.png

Maybe one of the -webkit-column-break-* properties can control this.

[Update: Of course Firefox 3 supports most of these column properties as well, via -moz-column-*. Firefox 3.1 beta 2 extends support to properties such as -moz-column-rule.]

2009/02/18

Canvas for a Text Editor?

Canvas for a Text Editor?:

The HTML 5 specification includes an API to render text on a canvas. Unfortunately, this portion of the canvas API has only been implemented by Firefox, though it's already in WebKit nightly builds (and thus will very likely be in a future version of Safari) and Chromium nightlies (from which Chrome versions are derived). We expect Opera will soon as well.


Support for canvas text in browsers other than Firefox will be a great thing for web applications. I've built 2D chemical structure viewers using Canvas, and the clunkiest aspect has been the overlaid text divs for atom labels. (Thank goodness for TextCanvas. Without it, I wouldn't have made the effort.)

You don't really notice text overlays are being used unless you accidentally click-drag your mouse over a depiction, or you set your browser preferences to disallow text smaller than a set size.

2009/02/17

Flex: Stopping event propagation from itemRenderers | kahunaburger

Flex: Stopping event propagation from itemRenderers | kahunaburger:

"My problem was that whenever I clicked on one of the menu items (the four icons at the bottom of the right tile), the mouse event would not only execute the action associated with the menu-item, no, the event would propagate up the chain and would result in the current tile being selected as well. Not good - this has to stop. "


Kahunaburger just saved me a lot of effort. The posted solution works for DataGrids as well.

macosxhints.com - 10.4: Use Automator to batch add Spotlight comments

Edited lightly:

macosxhints.com - 10.4: Use Automator to batch add Spotlight comments:

10.4: Use Automator to batch add Spotlight comments

By: cafemomo on Wed, May 18 2005 at 6:24AM PDT

In Automator, create the following workflow:

1. Finder > Get Selected Finder Items

2. Spotlight > Add Spotlight Comments to Finder Items

2.1. Keep 'Append to Existing Comments' checked

2.2. Open the Options disclosure area and check 'Show Action When Run' so you can set comments each time

3. In Automator, go to File > Save as Plug-in..., enter 'Add Spotlight Comments' as the 'Save Plug-in As:' name, and make sure 'Plug-in for:' is set to 'Finder'

4. Save and close Automator (if it asks you to save again, do so)

Now in Finder, select some items you want to add comments to and right-click (or control-click) and select 'Add Spotlight Comments' from the 'Automator' submenu.


Handy, e.g. for tagging related travel video clips which have been imported with Final Cut Pro.

Juxtaposition

Op-Ed Columnist - Yes, They Could. So They Did. - NYTimes.com:

It's a plug-in electric car that is also powered by rooftop solar panels -- and the two young women, recent Yale grads, had just driven it all over India in a 'climate caravan' to highlight the solutions to global warming being developed by Indian companies, communities, campuses and innovators, as well as to inspire others to take action.


Charging ahead with energy independence - SantaFeNewMexican.com:
Zappy is an all-electric vehicle under construction in Dan Baker's garage off Old Santa Fe Trail. Baker -- known around town as an avid cyclist -- also is a big solar-energy and electric-vehicle proponent. He'll run Zappy off the 5-kilowatt solar photovoltaic system he had installed on his roof last September.


Purpose Built Vehicles - Bright Automotive (of Indiana):
[Our vehicle] operates in all electric mode for the first 30 miles, then operates in hybrid mode with a full range of 400 miles. Bright Automotive's smart vehicle architecture is also designed to return stored energy back to the electrical grid - potentially reducing peak energy demand.

2009/02/16

Mozilla Webdev » Blog Archive » Native JSON in Firefox 3.1

Mozilla Webdev » Blog Archive » Native JSON in Firefox 3.1:

"Pretty easy huh? And here’s how to get a JSON string from an object:

var personString = JSON.stringify(person);"


As a long-time fan of Python's pickle and shelve, I hope JSON.stringify properly handles JavaScript object graphs. And I hope jQuery exposes a similar API.

I think jQuery provides only .param, which is designed as a helper for forms serialization and which does not handle nested objects. For example, in jQuery 1.3.1 this:

var graph = {
'item': {
'name': 'bob',
value:42
},
'index': 1};
$('#msg').html("Graph: " + $.param(graph));


produces this:
Graph: item=%5Bobject+Object%5D&index=1

2009/02/15

Change Happens

Change Happens:

"I won't say that this entry has that much spice, but I hope you can take a moment with me to see through time to allow wonder and delight to replace fear of change."


Tim O'Reilly's recent posts make for satisfying reading. He surrounds his ideas in a thick context of personal and family history.

Former astronaut scoffs at global warming - SantaFeNewMexican.com

Former astronaut scoffs at global warming - SantaFeNewMexican.com:

'As a geologist, I love Earth observations,' [Harrison Schmidt] wrote in his Nov. 14 resignation letter. 'But, it is ridiculous to tie this objective to a 'consensus' that humans are causing global warming when human experience, geologic data and history, and current cooling can argue otherwise.'

"We're very skeptical about the crisis that people are proclaiming in global warming," [said Dan Williams, publisher with the Heartland Institute, which is hosting the second International Conference on Climate Change in New York]. "Not that the planet hasn't warmed. We know it has or we'd all still be in the Ice Age. But it has not reached a crisis proportion and, even among us skeptics, there's disagreement about how much man has been responsible for that warming."
[Schmidt] said he is heartened that next month's conference is made up of scientists who haven't been manipulated by politics, possibly because they are not dependent on government funding.


The debate continues about the causes of global climate change. (See also Dr. John Theon's expression of skepticism.)

What interests me most about the debate is its effect on U.S. energy policy. If it spurs us to improved energy efficiency — e.g. in home heating and cooling and reduced contention for foreign oil — it seems beneficial to act as though climate change has some human causes, whatever the uncertainties in our understanding.

On the other hand, if the debate leads us to cover the wilderness with wind turbines, solar farms, and superconducting transmission lines [update: lucky timing - here's an example], then maybe we should start demonizing termite methane emissions :)

2009/02/13

VoodooPad and TextMate

VoodooPad's new HTML-savvy application-specific URLs are a great way to retrace your steps in TextMate.

I keep my worklog in VoodooPad. I do most of my code editing in TextMate. When I'm trying to understand a new chunk of code, I often need to jump around through the code base.

It's hard to keep track of where I've been, so I can back out of a code path once I understand what it does. Until now I've just jotted down pathnames and line numbers in my worklog, so I could manually retrace my steps.

Puzzle Pieces


  • VoodooPad URLs. They let you inject HTML content — including hyperlinks — into an open VoodooPad document.
  • TextMate URLs of the form txmt://open?url=file://pathname&line=lineNum;column=colNum. Open one of these URLs and TextMate will open a window showing the specified line (and column, if specified) of the specified file.
  • Textmate commands and key equivalents.
    TextMate lets you define custom commands and trigger them with keyboard shortcuts that you specify.


Put these all together and what do you get?

Scenario
  • Select some code of interest in TextMate
  • Type your keyboard shortcut
  • A hyperlink pointing to the selected code is inserted into your VoodooPad document

Later, when you want to get back to that chunk of code, just click on the hyperlink in VoodooPad. TextMate will open the document and jump to the line of code referenced by the hyperlink.

Granted, you're probably going to edit that code someday; and then your bookmarks will break. But this is a handy way to leave a trail of breadcrumbs while you're trying to decipher a new body of code.

Code

Here's a Python script which implements this "Bookmark in VoodooPad" capability in TextMate. You can use it by opening TextMate's Bundle Editor (Bundles -> Bundle Editor -> Show Bundle Editor), creating a New Command using the tool menu at the bottom left of the Bundle Editor window, and pasting it into the resulting Command(s) text area:

#!/usr/bin/env python2.6
import os, datetime, urllib, subprocess

escape = urllib.quote

# What Textmate location are we bookmarking?
path = os.environ["TM_FILEPATH"]
lineNum = os.environ["TM_LINE_NUMBER"]
_tmURLTemplate = """txmt://open?url=file://{path}&line={lineNum}"""
tmURL = _tmURLTemplate.format(path=path, lineNum=lineNum)

# Which VoodooPad worklog page should we add it to?
vpPageName = escape(datetime.date.today().strftime("%Y-%m-%d"))

# What text should Voodoopad show for the link?
currLine = os.environ.get("TM_SELECTED_TEXT", os.environ["TM_CURRENT_LINE"])

# How should the HTML be formatted?
_vpHTMLTemplate = '''<a style="font:12px helvetica" href="{tmURL}">{currLine}</a>'''
vpMarkup = _vpHTMLTemplate.format(tmURL=tmURL, currLine=currLine)

# What URL do we open to inject the HTML into VoodooPad?
_vpURLTemplate = """voodoopad:html={vpMarkup}&page={vpPageName}"""
vpURL = _vpURLTemplate.format(vpMarkup=escape(vpMarkup), vpPageName=escape(vpPageName))

subprocess.check_call(["open", vpURL])


Specify a key equivalent such as ⌘-T (Command-T) and you're off to the races.

VoodooPad bookmarklets now support HTML

VoodooPad bookmarklets are very useful. But they let you paste only plaintext from your web browser into your document — until now.

VoodooPad Application URLs

VoodooPad understands application-specific URLs of the form voodoopad:description=encoded_text&page=name_of_VoodooPad_document_page. When you open one of these URLs, VoodooPad inserts the encoded text into the indicated page of the current VP document.

You can open voodoopad: URLs from other applications, such as a web browser. That's what's so cool about VP bookmarklets -- they let you quickly select some text in your web browser and paste it into a VP document, along with other information such as the URL where the text originated.

The only problem is, the description parameter can contain only plain text. So if you've selected part of a web page that contains hyperlinks, those hyperlinks won't come along for the ride.

New Feature

Gus Mueller, VoodooPad's creator, recently released a new build. It adds a new html parameter to VoodooPad URLs. Now you can select part of a web page and transfer it as HTML into your VoodooPad document.

Gus summarized the new feature thus:

The format of the bookmarklet is like so:
voodoopad:page=junk&html=<b>hello</b>%20world!
Here's expanded code for a JavaScript bookmarklet which takes advantage of the new parameter. It works in both Safari and Firefox 3.0.x:

javascript: function pad(v) {
var res=String(v);while(res.length<2) {
res='0'+res;
}
return res;
};
var d=new Date();
var page=(String(d.getFullYear())+'-'+
pad(d.getMonth()+1)+'-'+ pad(d.getDate()));
function selHTML() {
var wr=document.createElement('div');
var c=window.getSelection().getRangeAt(0).cloneContents();
wr.appendChild(c);
return wr.innerHTML;
};
location.href='voodoopad:html='+encodeURIComponent('<div style="font:12px helvetica">'+location.href+'<br/>"""<br/>'+selHTML()+'<br/>"""</div><br/>')+'&page='+page;


Worth noting: in this snippet the html content is wrapped up in a div which has an explicit font specification. The bookmarklet is transferring a chunk of HTML, but that chunk doesn't include any of the CSS from the original web page. So if you don't specify a style for the wrapper div, VoodooPad will use its own default style for the current VP page. (I think that's something like Times Roman 10px.)

2009/02/12

Technology Review: Neanderthal Genome Unraveled

Technology Review: Neanderthal Genome Unraveled:

"Using previously sequenced genomes from other species was also crucial, says John Hawks, a biological anthropologist at the University of Wisconsin. 'Bootstrapping computer information about genomes really made all of this possible,' he says. 'To be able to take snippets of DNA of 50 base pairs or less and have the computer say that it's the same as a bacterial sequence has enabled the reconstruction of genuine Neanderthal sequence.'"


I wonder how this relates to recent findings about horizontal gene transfer? Are all of those 50-base-pair sequences unique to bacteria, or are they just "most likely to occur" in bacteria?

2009/02/11

Call This Progress?

Call This Progress?:

"Five years of ‘action’ and only one country out of five so-called advanced European nations — all of which fought with the USA to get it to sign the Kyoto Protocol — has managed to reduce its emissions by more than 5%."


The article claims that the U.S. increased its emissions by 2.4% in the measured period. That's better than Kyoto signatories France (2.9%) and Spain (12.4%).

2009/01/30

Blue light kills MRSA 'superbugs' - The Register

Blue light kills MRSA 'superbugs' - The Register:

"American medi-boffins say they have developed a way to kill so-called 'superbugs' - deadly infections which can't be cured using antibiotics - by simply shining a certain wavelength of blue light on them. They believe the technique could be used safely on patients infected with MRSA [Methicillin-Resistant Staphylococcus aureus].
'It is inspiring that an inexpensive naturally visible wavelength of light can eradicate two common strains of MRSA. Developing strategies that are capable of destroying MRSA, using mechanisms that would not lead to further antibiotic resistance, is timely and important for us and our patients,' says Chukuka S Enwemeka PhD of the New York Institute of Technology."

2009/01/28

Cheap, super-efficient LED lights on the horizon - New Scientist

Cheap, super-efficient LED lights on the horizon - tech - 29 January 2009 - New Scientist:

"Humphreys reckons that the UK government encouraged consumers to drop tungsten bulbs too soon. 'We should have stayed with tungsten for another five years and then switched to LEDs,' he says."

I'm a sceptic now, says ex-NASA climate boss - The Register

I'm a sceptic now, says ex-NASA climate boss - The Register:

[Theon said] "My own belief concerning anthropogenic climate change is that the models do not realistically simulate the climate system because there are many very important sub-grid scale processes that the models either replicate poorly or completely omit. Furthermore, some scientists have manipulated the observed data [emphasis added, etc.] to justify their model results. In doing so, they neither explain what they have modified in the observations, nor explain how they did it.
"They have resisted making their work transparent so that it can be replicated independently by other scientists. This is clearly contrary to how science should be done."

So he's a skeptic about man-made global climate change. I wonder what he thinks about climate change trends in general. E.g. do the data indicate long-term warming, regardless of cause?

Aside: I quit reading treehugger.com a few years ago, after the reporter in one of their so-called "news" videos mocked a claim that some climate change was due to the sun. "That's right: the sun. [snort]" As if fluctuations in our largest energy source could not affect our climate...

More from The Register:
"Hansen has called for energy industry executives to be jailed for dissenting from the man-made warming hypothesis."

I didn't know that. The Guardian confirms it:
"James Hansen, one of the world's leading climate scientists, will today call for the chief executives of large fossil fuel companies to be put on trial for high crimes against humanity and nature, accusing them of actively spreading doubt about global warming in the same way that tobacco companies blurred the links between smoking and cancer."

2009/01/26

Obama's Order Is Likely to Tighten Auto Standards - NYTimes.com

Obama's Order Is Likely to Tighten Auto Standards - NYTimes.com:

"It would also pay for 3,000 miles of new or modernized transmission lines as part of a new national electric grid as well as 40 million 'smart meters,' which provide instant readouts of electricity uses, on American homes. The money would also help refurbish two million homes and 75 percent of federal building space to better guard against the weather"


Electricity consumption isn't my home's problem. My home's problem is natural gas consumption.

2009/01/21

Why Darwin was wrong about the tree of life - life - 21 January 2009 - New Scientist

Why Darwin was wrong about the tree of life - life - 21 January 2009 - New Scientist:

"Other cases of HGT in multicellular organisms are coming in thick and fast. HGT has been documented in insects, fish and plants, and a few years ago a piece of snake DNA was found in cows. The most likely agents of this genetic shuffling are viruses, which constantly cut and paste DNA from one genome into another, often across great taxonomic distances. "

2009/01/20

Django snippets: DebugFooter middleware with textmate links

Django snippets: DebugFooter middleware with textmate links:

"This version adds TextMate links : if you are working on your local machine and using TextMate you can click on the template paths and they will be opened in TextMate. This speeds up development time considerably!
also, this works with django 1.0"


Very useful.

ack -- better than grep, a power search tool for programmers

I've been using "Ack in Project" in TextMate for awhile. It works so well, I'd like to start using it from the command line.

Luckily it's easy. Paraphrasing from the author's website:

ack -- better than grep, a power search tool for programmers:

curl http://ack.googlecode.com/svn/tags/latest/ack-standalone > ~/bin/ack && chmod 0755 ~/bin/ack

BBC NEWS | Asia-Pacific | Fresh warning on China bird flu

BBC NEWS | Asia-Pacific | Fresh warning on China bird flu:

"Hong Kong's secretary for food and health, Dr York Chow, said this was a cause for concern.
'There are two main areas we are concerned about: one is that if there is no avian flu outbreak in poultry and yet there are human cases, does this mean the virus has changed?
'Secondly, we are worried about whether there are more so-called 'slightly infected' chickens that actually might be carrying the virus and transmitting the disease, and yet do not show any symptoms or die from those illnesses,' Dr Chow said."

2009/01/14

jQuery 1.3 Live Events

Release:jQuery 1.3 - jQuery JavaScript Library:

"Live Events

jQuery now supports 'live events' - events that can be bound to all current - and future - elements. Using event delegation, and a seamless jQuery-style API, the result is both easy to use and very fast."


If I read this correctly, now you can reload parts of your page and have any replaced controls wired up automatically. No more need for post-processing callbacks on $.load() or $.getJSON()?

Outstanding!

(And the description, "Live Events", is concise — much better than the term "path-based bindings" that I've been using.)

2009/01/11

Work on Stuff that Matters

Work on Stuff that Matters: First Principles - O'Reilly Radar:

"Our economy has many elements of a ponzi scheme. We borrow from other countries to finance our consumption, we borrow from our children by saddling them with debt and using up non-renewable resources."

2009/01/07

iWork '09: Numbers

Numbers '09 has some significant improvements.

  • It supports axis transformations — linear, log-scale (okay, that's probably not new).
  • It supports overlays, including a host of curve-fits, with annotations (formula, R-squared error, etc.)
  • Unlike its predecessor, Numbers '09 provides an AppleScript dictionary.


Impressive!

Picture 1.png

2009/01/05

VoodooPad Bookmarklets

VoodooPad bookmarklets make it easy to log search results.

I keep a worklog in VoodooPad. Notes for each day are stored in a page with a name of the form 'yyyy-mm-dd'.

When I'm searching for info on the web, I like to include relevant results in my worklog. I tend to record results in this format, to make it easier to find the results again in future:

http://url.of.interest/:
"""
Excerpt
"""


It's tedious to format these excerpts. At least two visits to the browser application are needed:
  1. Copy the URL
  2. Copy the text of interest


Luckily VoodooPad supports application-specific URLs, and you can create JavaScript bookmarklets to open such a URL, with the URL and any selected text for the page you're currently viewing.

Here's an almost human-readable example of a bookmarklet which adds an excerpt from the current web page, formatted as above, to the current worklog page in VoodooPad.

javascript:
var d = new Date();
var padded = function(v) {
var res = v.toString();
while (res.length < 2) {
res = '0' + res;
}
return res;
};
var page = [
String(d.getFullYear()),
padded(d.getMonth() + 1),
padded(d.getDate())
].join("-");
location.href = ('voodoopad:description=' +
encodeURIComponent(location.href + '\n"""\n' +
window.getSelection().toString() +
'\n"""\n') +
'&page=' + page);


Here's the same bookmarklet formatted for inclusion in your browser's menubar:
javascript:var%20d=new%20Date();var%20padded=function(v)%20{%20var%20res%20=%20v.toString();while%20(res.length%20<%202)%20{res%20=%20'0'%20+%20res;}%20return%20res;};var%20page%20=%20[String(d.getFullYear()),%20padded(d.getMonth()%20+%201),%20padded(d.getDate())].join('-');location.href='voodoopad:description='+encodeURIComponent(location.href+'\n"""\n'+window.getSelection().toString()+'\n"""\n')+'&page='+page;