2008/03/06

DailyTech - Researcher: Basic Greenhouse Equations "Totally Wrong"

From DailyTech:

"NASA refused to release the results.  Miskolczi believes their motivation is simple.  'Money', he tells DailyTech.  Research that contradicts the view of an impending crisis jeopardizes funding, not only for his own atmosphere-monitoring project, but all climate-change research.  Currently, funding for climate research tops $5 billion per year.
"

"The equations also answer thorny problems raised by current theory, which doesn't explain why "runaway" greenhouse warming hasn't happened in the Earth's past. The new theory predicts that greenhouse gas increases should result in small, but very rapid temperature spikes, followed by much longer, slower periods of cooling -- exactly what the paleoclimatic record demonstrates."

"Miskowlczi has used his theory to model not only Earth, but the Martian atmosphere as well, showing what he claims is an extremely good fit with observational results."


Hey, at least we still have peak oil.

2008/03/03

Intermittent Pickle Problems in Jython

The previous post mentioned "integrating" Jython and CPython by transmitting a stream of pickles between the two. I encountered one intermittent problem with this approach, and I'm unsure of its cause. (Hm, and I should probably post this to a Jython mailing list...)

Problem


In Jython I'd pickled the str() of a java.io.StringWriter, into which I'd just written the SD representation of a CDK molecule. Jython could create the pickle alright. But when I tried to unpickle it in CPython, sometimes, for some molecules, I got a traceback:
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 970, in load_string
raise ValueError, "insecure string pickle"
ValueError: insecure string pickle


The error occurred consistently in my application code, always on the same input structure. But I couldn't derive a simple test script to demonstrate the problem.

Investigation


Examination of the problematic pickle data showed that a Python unicode string literal marker had somehow been inserted, and the type code for the item was somehow S (for string) rather than V (for unicode):
...
sS'sdf'
p3
Su'ZINC00000181\n CDK...
^ What the... ?


Workaround


Google turned up a usable workaround: encode the offending string as utf-8 before trying to pickle it.


import codecs
enc = codecs.getencoder('utf8')
...
sdf = enc(sdf)
...


Ted Leung: The Sun is going to shine on Python

Congratulations to Ted Leung (and to Frank Wierzbicki):
The Sun is going to shine on Python.

Their work at Sun will extend well beyond Jython, but Ted's post reminded me of my recent experiences. Jython 2.2 sure made it pleasant and easy[1] to get what I needed out of CDK, and to integrate the results into a CPython app via pickle and subprocess.

I did miss some language features such as yield which have appeared in CPython since 2.2. Maybe at some point Ted and/or Frank will have time to re-sync Jython with CPython?

[1] I had one intermittent problem with this approach. See the next post.

2008/02/26

New Scientist: Fatal brain cancer tamed by gene therapy

Fatal brain cancer tamed by gene therapy - 25 February 2008 :

Previous attempts to treat glioblastomas with gene therapy failed because some tumour cells survived and regrew. The new treatment overcomes this problem by permanently priming the immune system to pick off any straggler tumour cells.

A harmless virus that only infects fast-dividing cancer cells is injected directly into the brain... One gene, HSV1-TK, kills the cancer cells by activating ganciclovir...


And here's the cool bit:
...a second gene, Flt3L... summons immune "dendritic" cells from the bloodstream into the brain.


(How does it do that?)

[The dendritic] cells engulf the debris and transport it back to lymph nodes, where they re-prime the immune system to attack any remaining tumour cells during and after treatment.


Lymph nodes seem like a gunnery school for white blood cells: you go there to learn how to distinguish friend from foe. (BTW fevers seem to help lymph nodes do their jobs.)

2008/02/25

Doc Searls: The FCC and the Giant Zero

The FCC and the Giant Zero:

"Message to Verizon and the rest: the Internet is not about ‘consumer choice’. We produce as well as consume. We need to be able to run our own servers. [emph. added] We need to be able to exercize supply as well as demand. We need symmetricality, not just neutrality."


Amen to that.

I live in Santa Fe. As far as I can tell, my choices are Earthlink (via Qwest DSL @ 1.5Mbps) and Comcast. If I want a static IP address, a useful step to server-hood, then my rates would go up by 30%. Bah.

Netgear WAN MTU Size

(Not sure why I haven't written this up yet. It sure was a problem for a long time...)

I used to work "offsite" -- outside the home -- several days a week. When offsite my laptop could perform subversion operations against a repository on my home network, with good performance. But when the notebook was "inside" the home network, those same operations would take forever.

Eventually I stumbled on the fix, clearly explained in the help sidebar of the WAN Setup page of my Netgear WGR614 router: change the MTU to 1492. (Shades of Christopher Columbus!)

Nobody reads documentation :\

The normal MTU (Maximum Transmit Unit) value for most Ethernet networks is 1500 Bytes, 1492 Bytes for PPPoE connections, or 1436 for PPTP connections.


2008/02/14

Site-specific browsers and web-app testing


 ?


Site-specific browsers should simplify testing of some types of web applications, e.g. those which support multiple registered users. On platforms such as Mac OS X, which typically run only one instance of each application, SSBs should allow you to launch multiple, distinct applications which point to the same website.

Is anyone doing this? Is it better (and does it always suffice) to simply run multiple copies of a twill script, and to dispense with browser-based tests?

I haven't tried Fluid yet, since my main work machine is still running Tiger.

Alas, I guess basic Prism apps won't do the job:

prism_one_copy.png


Technorati Tags:
, , ,


2008/02/13

DNA Articles du Jour

Next-generation pathogen sequencing

http://www.technologyreview.com/Biotech/20191/

454 Life Sciences have figured out how to isolate pathogen RNA from human tissue samples, and have used the process to identify previously-unknown pathogens as the likely cause of death for three transplant recipients.

In the 1980s, my brother's neighbor almost died from an illness whose cause was never determined. More recently, local doctors have been unable to figure out why a friend's daughter had a fever for three weeks. This process may make it possible to diagnose the causes of many more illnesses.

"...the sequence of the new virus was different enough that existing methods could not have detected [it]..."


"As many as 40 percent of cases of central nervous system disease cannot be traced back to a specific culprit. For respiratory illness, the figure is 30 to 60 percent."


"Usually, PCR requires some advance knowledge of the sequence in question because it relies on molecular primers that match the string of code to be amplified. But 454 sequencing avoids that problem by using a large number of random primers."



Combining DNA from >2 "parents"

http://www.dailytech.com/article.aspx?newsid=9835

I didn't know people could have problems with their mitochondrial DNA.

"...[the] research involved implanting the DNA from a [woman] with a mitochondrial disorder into the egg of a [woman] with healthy mitochondria. Thus the woman with the genetic disorder passed on the rest of her genetic legacy, while the other woman contributed only [healthy mitochondrial] DNA."


Ethical firestorm to follow...

2008/02/10

Installing PVM under MacPorts on Leopard

I've been having trouble getting PVM 3.4.5 to install under MacPorts on Leopard. The conf/DARWIN.def configuration file defines the FAKEXDRFLOAT preprocessor symbol; it may be needed for OS X 10.4, but it causes a compiler error w. GCC 4.0.1 under 10.5:

../../src/pmsg.c:785: error: static declaration of 'xdr_float' follows non-static declaration.


The workaround is simple: install the Darwin8 variant.

$ sudo port install pvm +darwin_8

2008/02/09

DailyTech - Solar Activity Diminishes; Researchers Predict Another Ice Age

DailyTech - Solar Activity Diminishes; Researchers Predict Another Ice Age:

Researcher Dr. Timothy Patterson, director of the Geoscience Center at Carleton University, shares the concern. Patterson is finding "excellent correlations" between solar fluctuations, a relationship that historically, he says doesn't exist between CO2 and past climate changes. [emphasis added] According to Patterson. we shouldn't be surprised by a solar link. "The sun [is] the ultimate source of energy on this planet," he says.


Oh no! Is it too late to start increasing our greenhouse gas emissions, to keep the planet from freezing over? ;)

Whatever is the truth about how we affect our environment, it's good to be reminded of our insignificance — and our uncertainty.

2008/01/30

Stephen Fry - Bloggery

No, no: Break a Leg.

Stephen Fry has broken his arm so badly it took ten screws to pin it in place. The x-rays look so bad they actually convey a sense of the pain he must be feeling.

Interesting to note that he suffered the break while filming a segment of "Last Chance to See" in Brazil. I didn't know there was such a series, but (from a selfish perspective) what serendipity: Douglas Adams was one of my favorite authors, and I'm a fan of Mr. Fry's work as well.

I have a little list of people I'd like to meet. No idea what I'd say to any of them, except perhaps, "Thank you." Stephen Fry is on that list. Douglas Adams was there, too, but I missed him by a year; like others he has slipped onto the list of missed opportunities.

Maybe I should just post a "get well soon" to Mr. Fry's blog :)

2008/01/26

Online NewsHour: Update | Obama Routs Clinton in South Carolina | January 26, 2008 | PBS

Online NewsHour: Update | Obama Routs Clinton in South Carolina | January 26, 2008 | PBS:

'We are up against the idea that it's acceptable to say anything and do anything to win an election,' Obama said.


That's almost word-for-word what the late Paul Tsongas said about Bill Clinton during the 1992 Democratic primaries. From the New York Times archives:
Paul E. Tsongas unleashed his harshest attack yet tonight against Bill Clinton, assailing his Democratic rival as a "pander bear" who "will say anything, do anything to get votes."


We'd have a different world if Tsongas had won. At the least he would have helped us face the fact that Social Security and Medicare are unsustainable. The Concord Coalition strives, still, to spread his message.

Back to the present, and Obama:
'We know that this is exactly what's wrong with our politics; this is why people don't believe what their leaders say anymore; this is why they tune out. And this election is our chance to give the American people a reason to believe again.'


2008/01/25

Likin' bzr

I've been using bzr for the past couple of months, and am liking it.

I'm not using it on any projects involving multiple people. All of my employer's code still lives in subversion repositories.

Rather, I'm using bzr for local, lightweight revision control. It sure is nice to be able to go into a directory tree where I'm whanging together a prototype, or where I'm working up some documentation; and to say

$ bzr init
$ bzr add .
$ bzr commit -m "New repository"'


And bingo, I can make changes and back out of them at will, with little fear of trashing anything. And of course, for technical writing it's nice to be able to refer to old revisions.

Lately I've started fiddling around w. bzr branch, building prototype web servers in one directory tree and occasionally pulling them out to a "deployment" branch. This feels a little more like working with subversion, but bzr lets me make local "checkpoint" commits, where some things are broken, without fear of breaking the build.

At this point my only problem with bzr is that I don't quite grok what's going on under the hood. Distinctions between branches and checkouts seem clear enough. But I don't understand why, when I commit from a "checkout" workspace, a subsequent bzr status in the source workspace will tell me that my workspace is out of date; whereas a similar sequence of actions from a "branch" workspace -- a commit followed by a push, followed by a status in the target workspace -- offers no warning that the code has been updated.

Given some time and experience these confusing behaviors should make more sense. Meanwhile, it sure is nice having cheap, local revision control. Kinda like XCode 3's Project Snapshots, but without the XCode :)




Technorati Tags:
, ,


2008/01/16

Mill at the Camp Bird Mine, Ouray County, Colorado (LOC)

Wow. Ken and Dave and Suzanne and I drove past this mine in August, 2006, in Suzanne's indomitable Bronco. The place looks a bit more run-down now.

This LOC collection is going to be full of gold nuggets...

2008/01/14

DailyTech - Cellulosic Ethanol Promises $1 per Gallon Fuel From Waste

DailyTech - Cellulosic Ethanol Promises $1 per Gallon Fuel From Waste

GM's (or rather, Coskata's) approach starts ... by putting the various organic waste materials, such as tires, crops, crop waste and yard waste into a grinder. The remaining powder is then exposed to plasma, which causes the organic powder to ferment, releasing carbon-chain gas. It rises into the air where natural anaerobic bacteria eats the gas molecules and excretes ethanol and water vapor. This mixture then rises, and travels through a series of tubes with a separating membrane. The yield is pure water and pure ethanol.

...an analysis of the process conducted at Argone National Laboratory reveals that for every unit of energy Coskata uses, it creates approximately 7.7 times as much energy, a ratio well above current tradition ethanol production.

Lutz ... also explained that the move will take GM and other auto makers "out of the firing line" of accusations that they contribute to everything from "out-of-control global warming, to funding terrorism."


Producing fuel from renewable resources may reduce net carbon emissions, and it's interesting to see technological breakthroughs emerge. But I wonder how well a change in fuel sources would compare with a change in lifestyle -- for example, one which encouraged the use of mass transit -- in reducing emissions. Have any relevant studies been published?

2008/01/10

Sir Edmund Hillary has died - Yahoo! News

From Yahoo! News:

WELLINGTON, New Zealand - Sir Edmund Hillary, the unassuming beekeeper who conquered Mount Everest to win renown as one of the 20th century's greatest adventurers, has died, New Zealand Prime Minister Helen Clark announced Friday. He was 88.


'Sir Ed ... lived a life of determination, humility, and generosity,' Clark said in a statemen"


...he was more proud of his decades-long campaign to set up schools and health clinics in Nepal, the homeland of Tenzing Norgay...

2008/01/07

Using supervisor on OS X

Last week's sojourn with Leopard gave me a chance to learn about some new ways of performing common system administration tasks. I've already written about using iCal in place of cron. I also had a chance to get acquainted with launchctl.

I have some custom web app servers which need to launch at system startup, and which need to be restarted if they fail. (I guess I could launch them from within Apache...)

The last time I needed to launch anything at system startup on OS X, /Library/StartupItems was in vogue. It's still usable, but now launchctl and /Library/LaunchDaemons et al are recommended in its place. As the launchd man page states:

In Darwin it is preferable to have your daemon launch via launchd instead of modifying rc or creating a SystemStarter Startup Item.


At some point my web apps may be deployed on Linux. So instead of going all the way with launchctl I decided to introduce supervisor into the mix: use launchctl to keep supervisor running, and use supervisor to keep the custom services running.

Of course this is a stupid thing to do. Both launchctl and supervisor are intended for the same types of problems. But supervisor will be available on Linux whereas, presumably, launchd will not. This is as good a place as any to learn how to use supervisor.

Besides, I have a long history of solving problems in ways which are almost, but not quite, entirely incorrect.

After much bumbling about, this became the plist script which would get supervisor up and running at system boot:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN
http://www.apple.com/DTDs/PropertyList-1.0.dtd >

<plist version='1.0'>
<dict>
<key>Label</key><string>com.agendaless.supervisor</string>
<key>ProgramArguments</key>
<array>
<string>
/Library/Frameworks/Python.framework/Versions/Current/bin/supervisord
</string>
</array>
<key>Debug</key><true/>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
</dict>
</plist>


This script is installed as /Library/LaunchDaemons/com.agendaless.supervisord.plist. As the launchctl.plist man page says, that's the place for "System wide daemons provided by the administrator."

Both the name of the plist file and the value of the Label are based on the domain of the copyright owner for supervisor: http://www.agendaless.com/

The ProgramArguments consist solely of the path to the supervisord executable.

RunAtLoad ensures that supervisor is started as soon as it is loaded.

Setting Debug to true increases the odds that, if some problem arises in running supervisor, the problem will be noted in the system log.

Finally, KeepAlive ensures that, if supervisor dies, it will be restarted. (KeepAlive is not documented in the OS X 10.4 man pages; it may make sense only for OS X 10.5. I need to re-read the blog where I saw it mentioned to better understand its intended use.)

I'm still such a novice with supervisor (not to mention launchctl) that I'm not sure supervisor meets the expectations of launchctl. But in any case, the above seems to work.




Technorati Tags:
,


2008/01/06

Intel iMac hard drive failure

Just after returning from Christmas vacation my iMac (Intel Core Duo 1.83GHz, 17") started showing spinning beachballs. And the system log started accumulating error messages similar to those described on this blog. The hard drive was dying.

Luckily I'd run a SuperDuper backup the night before starting vacation.

It was also lucky that I had an early-model Intel iMac. Supposedly newer models are much harder for amateurs to service.

Thank goodness for John Wood's iMac_Disassembly web page. If it weren't for him I'd either be running from an external hard drive right now or shipping the iMac off for a very expensive (not under AppleCare) repair.

Using the photos and instructions on the disassembly page I was able to swap out the failed 160GB Seagate Barracuda 7200.7 for a 320GB Western Digital WD3200AAJS, purchased from NewEgg. Required tools:

  • A #0 Phillips screwdriver for the memory slot cover
  • A T-8 Torx driver for the top case
  • A small Allen wrench (not sure about the size) for the screws securing the LCD panel to the back case
  • A sharp knife and a spot of rubber cement for moving the temperature sensor to the new drive
The whole job took about an hour and a half, not because it was difficult, but because I am a coward :)

There were two minor differences between my iMac and the one Mr. Woods took apart. Mine had two "hooks" at the top of the front plate, and I bent one of them slightly before discovering it was there. And in addition to the black tape overlying the sides and bottom of the LCD panel, I had perforated foil tape running along the top edge.

Everything's up and running again, and now I have lots of free disk space :) Time to do another backup. Of course in the meantime I've been doing development under Leopard on the MacBook; so it's tempting to follow that backup with an archive-and-install of 10.5 onto the iMac...

2008/01/03

Leopard, 'ls -l' and extended attributes

Under OS X v10.5 the permissions column from ls -l contains extra characters which I haven't seen before.

$ ls -l
total 16
-rwxr--r--@ 1 me me 165 Jan 2 06:38 run_webalizer
-rw-r--r--@ 1 me me 0 Jan 3 10:04 run_webalizer.scpt
The man pages didn't say anything about these @ characters. Google was no help since it ignores punctuation characters like "@".

Eventually I realized that, since I had done an "upgrade" installation of Leopard, my man pages might be out of date. Indeed they are: Apple's online man pages explain @ and much else that's new in the ls command:
If the file or directory has extended attributes, the permissions field printed by the -l option is followed by a '@' character. Otherwise, if the file or directory has extended security information, the permissions field printed by the -l option is followed by a '+' character.


And
The following options are available:
-@ Display extended attribute keys and sizes in long (-l) output.


Ah, Bach. Look at some of the interesting tidbits revealed by -@:
$ ls -l@
total 16
-rwxr--r--@ 1 me me 165 Jan 2 06:38 run_webalizer
com.macromates.caret 33
-rw-r--r--@ 1 me me 0 Jan 3 10:04 run_webalizer.scpt
com.apple.FinderInfo 32
com.apple.ResourceFork 754
So that's how TextMate knows where to put the cursor when I re-open a file.

Now I just need to figure out how to get my man pages up to date.

Replacing cron with iCal

cron is deprecated in OS X. iCal makes a straightforward, if tedious, replacement, despite its limited support for scripted alarms.

In iCal you can easily create a repeating event with an associated alarm that runs a script.

ical_repeating_event.png


Put all of your periodic system management events into a hidden "Automation" calendar (so they don't clutter up the calendar view) and you're all set.

automation_calendar.png


Of course, there's a problem. I prefer to write system management scripts using Python. iCal can run only AppleScripts.

It's easy to write an AppleScript "wrapper" which just launches a shell script, but the process involves lots of button-clicking:
  • Launch Script Editor
  • Enter do shell script "/path/to/shell/script"
  • Save the script
  • Quit Script Editor
Luckily, the osacompile command lets you do the same thing from the command line. Together with Python's pathname-manipulation facilities, osacompile makes it simple to create AppleScript wrappers for shell scripts.

Given the path to a shell script, the following Python program creates a corresponding AppleScript wrapper in the same directory:
#!/usr/bin/env python
import sys, os, subprocess, logging
def main():
for filename in sys.argv[1:]:
pathname = os.path.abspath(filename)
scriptname = os.path.splitext(pathname)[0] + ".scpt"
if os.path.exists(scriptname):
os.remove(scriptname)
status = subprocess.call([
"osacompile",
"-e", 'do shell script "%s"' % pathname,
"-o", scriptname])
if status:
logging.error("Got status %d creating %s" %
(status, scriptname))

if __name__ == "__main__":
main()

2007/12/28

Custom keybindings in OS X

Since I keep forgetting how to customize keyboard navigation, here's a pointer to the documentation:
http://developer.apple.com/documentation/Cocoa/Conceptual/EventOverview/TextDefaultsBindings/chapter_9_section_2.html

And here are the bindings I'm currently using in my ~/Library/KeyBindings/DefaultKeyBinding.dict file. Basically they cause the "Home" and "End" keys on the Apple keyboard to move the cursor to the beginning and end of the current text line. Hitting these keys while holding "Shift" will also select all text covered by the move. And the page up/down keys do what you'd expect.

{
"$\Uf729" = "moveToBeginningOfLineAndModifySelection:";
"$\Uf72b" = "moveToEndOfLineAndModifySelection:";
"\Uf729" = "moveToBeginningOfLine:";
"\Uf72b" = "moveToEndOfLine:";
"\Uf72c" = "pageUp:";
"\Uf72d" = "pageDown:";
}

2007/12/19

Twenty-year-old Civics got 57 miles per gallon - Dec. 19, 2007

Twenty-year-old Civics got 57 miles per gallon - Dec. 19, 2007:

"Even in its base HF trim, the CRX was considered a fun car to drive because it was small and responsive. Its zero-to-sixty time, though - about 12 seconds by some estimates - would put it well behind even a large, sedate family sedan like the Ford Taurus today."


I owned a red 1990 CRX HF for about 11 years. I drove it off the lot just a few days before Saddam Hussein invaded Kuwait. Boy, did I feel smug.

It was a great little car. On long trips it often averaged 60-62 mpg.

I finally gave it up after moving to Santa Fe. It had trouble climbing La Bajada. And it started pulling to the left after a local mechanic installed new front-end ball joints. Okay, and it had no air conditioning, which made for stinking hot desert travel.

But it was a great little car...

2007/12/12

CDK, Jython and chemical structure format conversion

These days I'm learning how to work with some new (to me) Java cheminformatics toolkits. Google, Jython 2.2.1, and VoodooPad are helping me get up to speed:


  • Google to find the documentation for the Java APIs

  • Jython to learn API nuances without an edit/compile/test cycle

  • VoodooPad as a scratchpad for sample scripts -- it's easy to save them in pages that sit alongside my worklog



During initial exploration I just bang up the script in VoodooPad, then repeatedly select all (Cmd-A), copy (Cmd-C), switch to a Terminal session running Jython (Cmd-Tab), and paste (Cmd-V).

The "learnings" are going into proper Jython scripts maintained with TextMate.

It's nice to be able to deploy using Jython instead of pure Java. Since almost all of the heavy lifting is being done inside the cheminformatics jars, I don't need to worry about the overhead of running a Python interpreter inside a JVM...

Here's a simple example using CDK, to transform an SD string into a SMILES string.
#! /usr/bin/env jython
# You must have set your CLASSPATH to pick up the CDK jar.
# encoding: utf-8

import java.io
from org.openscience import cdk

def getCDKMol(sdf):
reader = cdk.io.MDLReader(java.io.StringReader(sdf))
result = cdk.Molecule()
result = reader.read(result)
return result

def getSmiles(cdkMol):
result = java.io.StringWriter()
writer = cdk.io.SMILESWriter(result)
writer.write(cdkMol)
return str(result)

def sdfToSmiles(sdf):
return getSmiles(getCDKMol(sdf))

# Example:
print sdfToSmiles("""1-7


42 44 0 0 0 0 999 V2000
-0.8349 0.9908 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0
-0.0502 1.2457 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-0.0502 2.0707 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-0.8349 2.3257 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-1.3198 1.6582 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
0.6172 0.7608 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-1.0898 0.2062 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
0.5310 -0.0597 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
1.1984 -0.5446 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
1.9521 -0.2090 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
2.0383 0.6114 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
1.3709 1.0964 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-1.8968 0.0346 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-2.1517 -0.7500 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-1.5997 -1.3631 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-0.7927 -1.1915 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-0.5378 -0.4069 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-2.1448 1.6582 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
2.6195 -0.6940 0.0000 S 0 0 0 0 0 0 0 0 0 0 0 0
3.1044 -0.0265 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0
2.1346 -1.3614 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0
3.2869 -1.1789 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-1.8546 -2.1477 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
0.6172 2.5557 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-1.0898 3.1103 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-0.2227 -0.3952 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
1.1122 -1.3651 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
2.7920 0.9470 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
1.4571 1.9168 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-2.4488 0.6477 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-2.9587 -0.9215 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-0.2407 -1.8046 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-0.1632 -1.1420 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-2.1448 0.8332 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-2.1448 2.4832 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-2.9698 1.6582 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
3.7719 -0.5114 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
2.8020 -1.8463 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
3.9544 -1.6638 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-1.0700 -2.4026 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-2.6392 -1.8928 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
-2.1096 -2.9323 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
1 2 1 0 0 0 0
1 5 1 0 0 0 0
1 7 1 0 0 0 0
2 3 2 0 0 0 0
2 6 1 0 0 0 0
3 4 1 0 0 0 0
3 24 1 0 0 0 0
4 5 2 0 0 0 0
4 25 1 0 0 0 0
5 18 1 0 0 0 0
6 8 2 0 0 0 0
6 12 1 0 0 0 0
7 13 2 0 0 0 0
7 17 1 0 0 0 0
8 9 1 0 0 0 0
8 26 1 0 0 0 0
9 10 2 0 0 0 0
9 27 1 0 0 0 0
10 11 1 0 0 0 0
10 19 1 0 0 0 0
11 12 2 0 0 0 0
11 28 1 0 0 0 0
12 29 1 0 0 0 0
13 14 1 0 0 0 0
13 30 1 0 0 0 0
14 15 2 0 0 0 0
14 31 1 0 0 0 0
15 16 1 0 0 0 0
15 23 1 0 0 0 0
16 17 2 0 0 0 0
16 32 1 0 0 0 0
17 33 1 0 0 0 0
18 34 1 0 0 0 0
18 35 1 0 0 0 0
18 36 1 0 0 0 0
19 20 2 0 0 0 0
19 21 2 0 0 0 0
19 22 1 0 0 0 0
22 37 1 0 0 0 0
22 38 1 0 0 0 0
22 39 1 0 0 0 0
23 40 1 0 0 0 0
23 41 1 0 0 0 0
23 42 1 0 0 0 0
M END
$$$$
"""
)

2007/12/05

SQLElixir/SQLAlchemy/SQLite3 and ISO-8859 content

See here for the full discussion. The upshot is that, if you are storing string data into an SQLite3 database via Python, and if you suspect that the data may contain non-ASCII characters, you need to ensure that it's properly converted to (Python) Unicode before inserting.

#!/usr/bin/env python
# encoding: utf-8
"""Explores a problem importing a chemical structure file into an
SQLElixir/SQLAlchemy/SQLite3 database.

The file was in SD format. One of the tags contained ISO-8859 characters.
Python read the file contents without trouble; SQLite3 stored the contents.
But on retrieval SQLite3 raised an OperationalError:
Could not decode to UTF-8 column '[...]' with text '[...]'

This script explores the problem, and demonstrates two successful
Unicode encodings: utf-8/replaced and utf-8/ignored.

NB: Only the latter actually worked with SQLElixir:
s = unicode(s, encoding='utf-8', errors='ignore')
"""

import unittest, sqlite3

class TestCase(unittest.TestCase):
def setUp(self):
self.conn = sqlite3.connect(":memory:")
self.conn.cursor().execute('CREATE TABLE demo (value TEXT)')

def insertAndDump(self, encoding, errors, expectFailure=False):
caseName = repr([encoding, errors])
data = 'K\xf6 1366'
try:
if encoding is not None:
data = unicode(data, encoding=encoding, errors=errors)
cursor = self.conn.cursor()
cursor.execute("INSERT INTO demo (value) VALUES (?)", [data])
cursor.execute('SELECT * FROM demo')
self.failUnless(len(cursor.fetchall()) == 1)
self.failIf(expectFailure, "Unexpected success for %s" % caseName)
except Exception, info:
self.failUnless(expectFailure, "Failed %s: %s" % (caseName, info))

def testCannotRetrieveUnencoded(self):
self.insertAndDump(None, None, True)

def testCannotEncodeStrict(self):
self.insertAndDump("utf-8", "strict", True)

def testCanRetrieve8859Strict(self):
self.insertAndDump("8859", "strict")

def testCanRetrieveUTF8Ignored(self):
self.insertAndDump("utf-8", "ignore")

def testCanRetrieveUTF8Replaced(self):
self.insertAndDump("utf-8", "replace")

unittest.main()

2007/11/29

Wired News - Late Shift Work Linked to Cancer

Wired News - AP News

Linked because I like the improbable, but simple, hypothesis:

"Back then, [Richard Stevens] was trying to figure out why breast cancer incidence suddenly shot up starting in the 1930s in industrialized societies, where nighttime work was considered a hallmark of progress. Most scientists were bewildered by his proposal."


Richard Stevens is a cancer epidemiologist, which is interesting in its own right. He is a professor at the University of Connecticut Health Center.

Apparently, this is old news. From his bio:
"He proposed in 1987 a radical new theory that use of electric lighting, resulting in lighted nights, might produce "circadian disruption" causing changes in the hormones relevant to breast cancer risk. Accumulating evidence has generally supported the idea, and it has received wide scientific and public attention. For example, his work has been featured on the covers of the popular weekly Science News (October 17, 1998) and the scientific journal Cancer Research (July 15, 1996)."

Government H5N1 Sites

CDC and government sites concerning H5N1:



The map at bottom left of the Pandemic Flu site provides links to

  • state pandemic planning info

  • state pandemic web site info

  • local state contacts


Technology Review: Liver Models Go to Market

Technology Review: Liver Models Go to Market:

'Only one of every ten compounds tested by pharmaceutical companies becomes a product, says Shuler, and half of the failures are due to toxicity.'


(There's the bottleneck which cheminformatics has not been able to widen.)

'"The liver is a complex organ that has many different cell types," says Tannenbaum. These cells exchange chemical signals and even exert mechanical forces on each other that help maintain their function...'

'"In order to get any functionality [in a model], you have to have multiple cell types organized into a structure like a liver," he says. When cells are taken out of the liver and cultured using traditional means, their gene-expression profiles change very quickly, and they begin to deteriorate in a few days.'
'For four to six weeks, [Hepregen's] cells maintain gene-expression profiles comparable to those of liver cells in the human body; they continue to produce the enzymes that break down and modify drugs; and they even form functioning bile ducts, important transport systems in the liver.'


MIT's News Office has a similar article.

Drug brings hope for a universal flu vaccine - health - 27 October 2007 - New Scientist

Drug brings hope for a universal flu vaccine - health - 27 October 2007 - New Scientist

Ordinary flu vaccine contains dead influenza A viruses from the H1 and H3 families. When the researchers put this, plus the RNA-like drug Ampligen, into the noses of mice, the mice made antibodies not only to the vaccine viruses but also to H5N1 bird flu - without ever having been exposed to it. Better, when groups of nasally vaccinated mice were exposed to different strains of live H5N1, [at least half] of each group survived... The team think antibodies in mucus reacting with proteins in the virus could be key.

2007/11/13

UK bird flu outbreak confirmed as H5N1

From New Scientist: UK bird flu outbreak confirmed as H5N1

To go along with this news, some useful terms from Dictionary.app:

A disease that quickly and severely affects a large number of people and then subsides is an epidemic.

A disease that is continually present in an area and affects a relatively small number of people is endemic.

A pandemic is a widespread epidemic that may affect entire continents or even the world.

2007/11/08

Volcanic clay found to kill 99 per cent of MRSA superbugs

Volcanic clay found to kill 99 per cent of MRSA superbugs:

[Researchers] said that the clay was found to wipe out bug colonies in a day during laboratory experiments. They also revealed that control samples of MRSA, which were not treated with agricur, grew 45-fold over the same period.

The World health Organisation welcomed [the work of French doctor Line Brunet de Course] when she approached it in 2002 with 50 case studies. However, it denied her funding because of a lack of scientific evidence.
"It is possible that it is not one single element that is toxic to the bacteria."
The researchers also backed the possibility that the clay worked through a physical rather than a biochemical process, meaning that bacteria could never develop resistance. "It's fascinating. Here we are bridging geology, microbiology, cell biology. A year ago, I'd look at the clay and say, 'Well, that's dirt,'" Dr Haydel, a microbiologist, said.

2007/10/29

CherryPy 3: interpreting error messages

I'm stubbing out a method in a nested CherryPy application object. I keep getting error messages of the form


File "/path/to/CherryPy-3.0.2-py2.5.egg/cherrypy/_cprequest.py", line 551, in respond
cherrypy.response.body = self.handler()
File "/path/to/CherryPy-3.0.2-py2.5.egg/cherrypy/_cpdispatch.py", line 24, in __call__
return self.callable(*self.args, **self.kwargs)

TypeError: 'Data' object is not callable


And the cause? Almost every time, in the browser I've mistyped the URL for my server's Ajax method. I might be invoking foo instead of bar, and the result is always this sort of error message.

Why don't I instead get the old "We didn't find anything"? Dunno. It's probably something in my configuration.

2007/10/26

Exhibitionist spiny anteater reveals bizarre penis - New Scientist Environment

Science can be funny.

New Scientist Environment:

The spiny anteater ... is notoriously difficult to observe in the wild and shows little enthusiasm for breeding in captivity...

Four-headed phallus

Then Steve Johnston of the University of Queensland in Gatton, Australia, and his colleagues inherited a male spiny anteater that ... had been ‘retired’ from a zoo as it produced an erection when being handled at public viewing sessions.


This reminds me of a Panda exhibit at the Cincinnati Zoo in the late 80s. We were ushered into the viewing gallery in groups, at regular intervals. There we stood gazing in reverent silence upon an artificial bamboo forest -- a quiet, still forest, in the midst of which lay an inert black and white lump.

Minutes passed. The lump stirred. The crowd gasped.

The lump rolled over. The crowd went "Aahhhwww," and broke into applause.

They seemed not to care that they were now facing a leering, semi-conscious panda, sprawled on its back, legs spread wide like a drunken flasher.

Er, anyway... when doing science, one must be careful with electricity:

The spiny anteater's four-headed phallus had been puzzling scientists. "When we tried to collect semen by [electrically-stimulated ejaculation] before, not only did we not get a single drop, but the whole penis swelled up to a four-headed monster that wouldn't fit the female reproductive tract..."


2007/10/19

New Scientist: Cold weather really does spread flu

Cold weather really does spread flu - New Scientist Environment

Flu virus can spread without the aid of coughing/sneezing -- you just gotta breathe. It stays in suspension longer in cold, dry air than in warm, moist air. And it doesn't help that mucus flows more poorly in cold weather.

"...Virtually no lab animals get it the way humans do... The most useful animal has been the ferret... “They’re big, they’re expensive, and they bite,” Peter Palese of Mount Sinai Medical School in New York City told New Scientist.

In 1919, US Army doctors at Camp Cody in New Mexico reported (Journal of the American Medical Association, vol 72 p1056) that the 1918 flu pandemic had killed their guinea pigs – kept at the time for medical tests. “We didn’t know guinea pigs got flu,” says Palese. They are no longer popular lab animals, and no-one had tried them."


Bad news for air travelers:
"“It spread just in the air they exhaled,” says Palese. “Guinea pigs with flu don’t cough or sneeze.”"


2007/09/27

Thank Goodness for the Judiciary (again)

Oregon judge knocks down part of Patriot Act:

"SEATTLE (Reuters) - An Oregon judge on Wednesday ruled that two provisions of the Patriot Act violated the U.S. Constitution's protection against unlawful searches and seizures.

U.S. District Judge Ann Aiken ruled in favor of Brandon Mayfield, a lawyer wrongly arrested by the FBI in 2004 for possible ties to the Madrid train bombings, who challenged the secret searches of his home and office.

The judge said the amendments made by the Patriot Act to the Foreign Intelligence Surveillance Act allows the government to conduct searches and monitor American citizens without probable cause, which is typically required by the Fourth Amendment to the U.S. Constitution.

'The defendant here is asking this court to, in essence, amend the Bill of Rights by giving it an interpretation that would deprive it of any real meaning. This court declines to do so,' Aiken wrote in her ruling."

2007/09/25

Stucco color matching for fun, if not profit

This summer I've bought two buckets of stucco patch for the house. I can't seem to hold a color chart up against the wall and have any chance of picking the right color.

Today I finally realized the digicam could do most of the work.

  1. Tape the color chart to the wall.
  2. Take a picture.
  3. Import it into iPhoto.
  4. Create a new OmniGraffle document.
  5. Create a big rectangle.
  6. Set its fill color by sampling the wall color from the imported photo.
  7. Create a bunch of little rectangles.
  8. Lay them out over the "wall" rectangle.
  9. Set their fill colors by sampling the swatches in the photo.

Stucco Color Matching 145 Solana.jpg

You don't even have to do any white balance correction. Everything in the photo should have its color skewed in roughly the same way.

Seempuhl. Wish I'd thought of this about ten dollars ago...

2007/09/24

Marching Morons

Getting ready to launch a glider at Kamuela/Weimea, Island of Hawaii. 1182 on Flickr.

The war on terror looks so often like a war on civil liberties. Our airports showcase the problem: law enforcement does its job literally and vigorously, enforcing "the law" without regard for whether enforcement is warranted or the law is even constitutional. Vision Aerie's experience at Kamuela airport is just one more example.

And when it turns out that the enforcers have over-reacted? Admit no wrong. Note the good fortune, of those detained in error, that law enforcement has shown such great self-restraint.

2007/09/20

Canon Scanners, Spotlight and OCR

When I scan receipts and invoices with my Canon LIDE 600F, OS X's Spotlight somehow, magically, is able to find them based on their text content. But I'm just scanning the documents, not running OCR software on them.

For example, this morning I scanned the receipt for my new MacBook, so I could send it in for a shipping rebate. Just for grins I then did a Spotlight search for "MacBook". There it was, near the top of the list.

mdls showed that "MacBook" didn't appear anywhere in the file's metadata. And the filename, "File0001.PDF", certainly didn't match. Yet somehow mdfind identified it as a match.

Searching for the string "MacBook" in the PDF turned up nothing. (Granted, I used 'strings -a' to extract the strings, and that command is ASCII only.)

Google, and David Creemer, provided the answer. Creemer also showed that the text in "CanoScanned" documents is selectable in Preview.app.

What's going on? It seems that the CanoScan Toolbox application is automatically performing OCR when it finishes scanning documents. For more info see zachary.com : Easy and cheap PDF Document Management (with OCR) on Mac OS X.

Synergy kudos to Canon and Apple!

2007/09/16

Water consumption in Santa Fe

Future Water, part 1: A big straw:

"Despite growth, the citywide annual demand for water is lower now than it was in most of the 1980s and '90s. Residents used 9,600 acre-feet last year. That compares to nearly 12,000 acre-feet in 2001."


The area's estimated population: 80,000, growing at 20% per year.

Maybe it's okay that I don't water the lawn :)

2007/09/15

Jon Udell: Discussing the re-invention of air travel with Ed Iacobucci

A conversation with Ed Iacobucci about the reinvention of air travel --
This article by Jon Udell ties together several items of significance to me: Eclipse Aviation; the Santa Fe Institute and the BIOS Group (now part of NuTech Solutions); complexity theory, Free Flight, general aviation and Byte Magazine (may it rest in peace).

2007/09/10

Viking ship resurfaces under Merseyside boozer | The Register

From
The Register -- too funny:

"A team from Nottingham University [...] believes it has rediscovered [...] an intact Viking boat under a Merseyside pub - originally unearthed in the 1930s [...], but quickly reburied because [the builders] feared 'an archaeological dig would disrupt their work'."

2007/08/29

www.neweurasia.net - Blogging Central Asia » Kiran over Mongolia: Interview with Joseph Spaid

www.neweurasia.net - Blogging Central Asia » Kiran over Mongolia: Interview with Joseph Spaid:

Q: What motivated you to shoot the documentary?

I was moved by the rugged and natural beauty of the eagle hunters and their lifestyle. Berkutchis [...] are just so damn strong and tough. They typically don’t even wear gloves, although it regularly gets below -25ْ F where they hunt. They are true ‘badasses’ by my definition.

2007/08/28

A'bit an hour of Stephen Fry

Stephen Fry just turned 50. BBC did a documentary on him:
http://www.snitchseeker.com/harry-potter-news/j-k-rowling-potter-stars-talk-stephen-fry-49899/

It seems as if everybody is involved with the man, including many of the folks behind Harry Potter.

Would I could write. A pun of Fry and (six degrees of) Bacon is trying hard to form in my head.


2007/08/23

Ted Leung summarizes Erlang

Some simple thoughts...:

Semantically, there is a lot to like about Erlang - the actor based concurrency model, hot code swapping, higher order functions, and (once one gets used to it) pattern matching. The OTP libraries have been refined by many years of production usage in demanding, commercial applications.

2007/08/20

Posting Syntax-Highlighted Code to the Web, Redux

Following up on July's post, I've modified my TextMate 'rawhtml' command so it no longer generates inline <style> sections. (They may work, but AFAIK <style> should appear only in a document's <head>.)

Instead, the command now wraps its output in a div of class SourceCode, and it expects the containing web page to include an appropriate <style> section.

Here's a test to see if this works :) I've added the following CSS to the Bottled Text template HTML:

div.SourceCode {
font-family: "Bitstream Vera Sans Mono", "Monaco", monospace;
font-size: 12px;
width: 500px;
overflow: auto;
margin: auto;
white-space: nowrap;
padding: 4px;
background-color: #ffffff;
border: 1px solid #777788;
}

div.SourceCode .comment {
font-style: italic;
color: #888;
}

div.SourceCode .keyword {
font-weight: bold;
}

div.SourceCode .string {
color: #00F;
}

div.SourceCode .entity {
text-decoration: underline;
}

div.SourceCode .storage {
color: #888;
}

div.SourceCode .support {
color: #0b0;
}

div.SourceCode .constant, div.SourceCode .variable {
color: #F0F;
}




The "rawhtml" command script now looks like this:
#!/bin/sh
cat <<HTML
<div class="SourceCode">
<div style="white-space: pre; -khtml-line-break: after-white-space;">
HTML


perl -pe 's/<\/[^>]+>/<\/span>/g' \
| perl -pe 's/<([^\/.>]+)[^>]*>/<span class="$1">/g' \
| perl -pe 's/\t/&nbsp;&nbsp;&nbsp;/g'

echo "</div></div>"


To get a realistic preview in MarsEdit, click the "Edit Template" button in the preview window and add a <style> section to the preview template for your blog. Paste in the CSS above and you're good to go.

2007/08/14

Sci Foo 2007 Gossip Liveblog (Aaron Swartz's Raw Thought)

Engrossing summary: Sci Foo 2007 Gossip Liveblog (Aaron Swartz's Raw Thought).

Dyson: Climate models are rubbish | The Register

Dyson: Climate models are rubbish | The Register:

"Dyson can expect another round of crucifixion with the predictable chorus that he's not a climate 'scientist'.
His contention, that the models aren't really science when they're programmed to produce the expected results, will no doubt be overlooked. ®"


I love the way Dyson writes. His article is full of thought-provoking observations and assertions, not all of them as directly concerned with global warming as you might expect. For example:
All our fashionable worries and all our prevailing dogmas will probably be obsolete in fifty years.

2007/08/06

Death, taxes and beyond

I thought bureaucracy could follow you only as far as the grave. But then there's eastern religion:
China tells living Buddhas to obtain permission before they reincarnate - Times Online

Via Ottmar Liebert

2007/07/19

Posting Syntax-Highlighted Code to the Web

Awhile back I noted some ways to copy syntax-highlighted text from TextMate to other applications like VoodooPad and MarsEdit. In some cases it was a simple procedure of two or three steps. But getting syntax-highlighted text into MarsEdit was comparatively tedious.

In all cases the procedure started with the Experimental -> View Document as HTML bundle. This morning I finally got around to browsing that bundle's definition and lo! it's just a simple Perl script invocation.

Better yet, it can act on either a complete document or just the text you've selected within that document. So if you want to post a code snippet? No problem.

It's also easy to make a copy of the bundle which, instead of creating a new HTML document, creates a plaintext document containing the HTML mark-up. You can copy the contents of this document and paste it directly into MarsEdit. (With a few caveats, i.e. you need to modify the stylesheet to avoid affecting the appearance of your entire post.)

The steps are simple:


  1. Select Bundles->Bundle Editor->Show Bundle Editor...

    Picture 4.png

  2. Browse into Experimental and select the View Document as HTML command

    Picture 5.png

  3. Click the "double-plus" button at the bottom of the window to make a copy of the command

    Picture 6.png

  4. Drag the command to some other bundle. I like to keep custom snippets, commands and templates in an @My Stuff bundle, which won't get overwritten when I upgrade TextMate

  5. Select the copied command. Rename it as you see fit, e.g. Format as Raw HTML

  6. Change the Output popup menu's value from Show as HTML to Create New Document

    Picture 8.png



That's it! Now you can select some code which you want to post, select your new command from the Bundles menu, and get a window with (almost) ready-to-post HTML markup.

Next Steps


Keyboard Navigation


If you come from (X)Emacs and wish you could invoke the bundle without having to navigate through a menu hierarchy, you can. Just use Control-Command-T to bring up the Select Bundle Item command window. Then type in the name of your new command, and hit return.

Picture 11.png

If you want to feel even more at home you can give your bundle a name which "feels like" an Emacs command. I've been trying single-word "command name" prefixes, like "rawhtml - Format as Raw HTML". The idea is to give your command both a quick-to-type "command" name, so you can get to it quickly in the command window, and a human-readable name so you can remember what it does :)

Limiting the Scope of the Styling


I haven't had time to do further customizations to the command. The next thing to tackle will be the stylesheet which it generates -- it's written to address an entire document, so it applies styles to e.g. the body element. I'd like to customize the generated HTML so it puts everything into a <div> with a unique timestamp for its id, and to modify the CSS so it applies only to that div. That'll make it easier to create markup that can be dumped directly into a blog regardless of what else might be on the blog page.


Update:
Turns out it was easy to modify the generated styesheet, and to wrap the output in a timestamped div. I'm not sure how righteous it is to include a <style> block inside the body of a blog post, rather than the head, but it renders okay in WebKit and Firefox 2.



Here's the source code for the command, as rendered by itself :)



#!/bin/sh
now=`date +'%Y%m%d%H%M%S'`

cat <<HTML
<style type="text/css">
#source_${now} {
font-family: "Bitstream Vera Sans Mono", "Monaco", monospace;
font-size: 12px;
width: 400px;
overflow: auto;
margins: auto;
padding: 4px;
background-color: #ffffff;
border: 1px solid #777788;
}

#source_${now} .comment {
font-style: italic;
color: #888;
}

#source_${now} .keyword {
font-weight: bold;
}

#source_${now} .string {
color: #00F;
}

#source_${now} .entity {
text-decoration: underline;
}

#source_${now} .storage {
color: #888;
}

#source_${now} .support {
color: #0b0;
}

#source_${now} .constant, #source_${now} .variable {
color: #F0F;
}

</style>
<div id="source_${now}">
<div style="white-space: pre; -khtml-line-break: after-white-space;">
HTML


perl -pe 's/<\/[^>]+>/<\/span>/g' \
| perl -pe 's/<([^\/.>]+)[^>]*>/<span class="$1">/g' \
| perl -pe 's/\t/&nbsp;&nbsp;&nbsp;/g'

echo "</div></div>"

2007/07/18

Firefox 2.x / Linux image scaling

Why does image scaling seem to be so bad in Firefox 2 on Linux?

For one of our web apps we want to show static pixmap images of chemical depictions. Depending on the context we want to show those depictions at different sizes, and we don't want to create and cache too many renderings. We'd rather create one fairly large rendering and have the browser scale it down as needed.

For users who are running Firefox/Win or Firefox/Mac this works fairly well, if the images aren't scaled down too much. (Otherwise lines get too thin, as you'd expect.) But for Firefox/Linux users, the results look horrible.

ff_mac.pngff_linux.png
Firefox/MacFirefox/Linux

What's up with that? Is there any way to control how Firefox downscales images, to get better quality?

Perhaps not. Or not yet, at least. Acts of Volition has an entry comparing image resizing in Firefox 2.x and Firefox 3. Paraphrasing:
The Cairo graphics library will power Firefox 3.
In Firefox 2, if you tell the browser to resize an image it will do so, but not with any of the smoothness that you would see if you had resized the image in an application like Photoshop or the Gimp.

Now, in Firefox 3.0 Alpha 1, resizing an image like this actually produces a smoothly sized image.

2007/07/14

changelog: Parallels 3.0: breaking the network

changelog: Parallels 3.0: breaking the network:

Parallels Desktop for Mac installs a startup item, llipd, which delays network traffic of some forms as much as 5 seconds.


According to /Library/StartupItems/ParallelsTransporter/StartupParameters.plist llipd is a "Parallels Link-local IPv4 deamon" (sic).

I don't need Parallels Transporter, so it's outta there.

2007/07/12

JavaScriptTemplates

JavaScriptTemplates offers template-driven formatting of web-page content, using JavaScript.

It will be fun to try this out. I often need to build web pages in which some of the content is created dynamically, via Ajax requests. The JavaScript which transforms the incoming JSON data to HTML tables can be painful to maintain. But I can't use server-side templating because I don't want to reload the entire page.

JavaScriptTemplates seem to offer a way around this. Not sure how one goes about previewing the templates, which are embedded in hidden textareas. Much to learn...

It will be really interesting to see how this, together with Naneau or Jester, changes development of dynamic web apps.

After the First Blush

Hm, this is a little troublesome:

    var myStr = "Hello ${customer.first} ${customer.last}, Welcome back!";
// Using the process() method is easy...
result = myStr.process(data);

Do they really pollute JavaScript Strings with a process method?

Yes, they do...
String.prototype.process ( contextObject, optionalFlags )

As a convenience, the String prototype is enhanced with a process() method. It parses the String as a template and invokes process(). The arguments are the same as for templateObject.process().