Fixing predicted runtime on APC UPS after replacing battery

The battery in my APC Back-UPS BR 800 was worn out after years of service, so I bought a replacement from APC.com. However, apcupsd still reported zero runtime and erratic charge and load percentages. I did some manual recalibration attempts (charge fully, discharge completely using constant load). This got my estimated runtime from zero up to a few seconds, but the UPS was still not useful. A couple seconds of power outage would lead to bogus critically low battery readings and trigger automated shutdown. (Despite the fact that it took me about half an hour to complete the run-down under a similar load.)

This evening I was preparing for another recalibration attempt by looking for a way to disable the beeping when power is disconnected. It turns out apctest can disable the alarm. In the process, I noticed apctest can also read and write the battery date. On a whim, I updated the date. And, magic: Merely changing the battery date fixed the reported runtime, charge, and load percentages!

Changing the battery date back to the original value did not bring the bogus readings back. Presumably the behavior is based on dead-reckoning of time elapsed since last battery change rather than any knowledge of what the current date actually is.

error: File name too long during Scala compile

[ERROR] error: File name too long

A common way to install Ubuntu is with an underlying ext4 file system and eCryptfs encrypted home directories. ext4, like many other file systems, has a maximum filename limit of 255 bytes. eCryptfs creates filenames much longer than the original. Compiled Scala classes tend to have long file names since anonymous classes end up in their own files. Therefore, when compiling Scala projects within eCryptfs on ext4, it is easy to get file name too long errors. :-(

Scala’s missing splat operator

Ruby, Python, and many other dynamic languages have a so-called splat operator that lets you easily invoke a function by providing a list of argument values:

def f(x,y)
  x*y
end

> fArgs = [6,7.0]
=> [6, 7.0]

> f(*fArgs)
=> 42.0

Scala does not have a splat operator per se, but you can achieve the same effect without too much work. Sadly the syntax is different for fixed-arity and variadic functions.

Scala splat for variadic functions

For variadic functions there effectively is a splat operator. If you invoke a variadic function and append :_* to the argument the compiler will perform the splat:

> def g(xs:Int*) = (0 /: xs) (_ + _)
g: (xs: Int*)Int

> val gArgs = List(1,2,3,4)
gArgs: List[Int] = List(1, 2, 3, 4)

> g(gArgs:_*)
res23: Int = 10

Scala splat for fixed-arity functions

> def f(x:Int, y:Double) = x * y
f: (x: Int, y: Double)Double

> val fArgs = (6, 7.0)
fArgs: (Int, Double) = (6,7.0)

> f _ tupled fArgs
res8: Double = 42.0

Magic! The first part, f _, is the syntax for a partially applied function in which none of the arguments have been specified. This works as a mechanism to get a hold of the function object. tupled returns a new function which of arity-1 that takes a single arity-n tuple. It is defined in the Scala Function object,

However, given a List of arguments to pass to f, I’m not sure how to easily convert the List to a Tuple.

p.s. There’s a stackoverflow post about this called “scala tuple unpacking.”

Argumentless git pull and git push

Pulling and pushing with git can be a bit verbose.  This post explains how to get from git pull --rebase origin master and git push origin master to just typing git pull and git push.

Rebase

First, set rebase for every new upstream branch (Why rebase? It makes your history easier to understand.)

git config --global branch.autosetuprebase always

This is explained in more detail (and with other helpful hints) in Mislav Marohnić’s post A few git tips you didn’t know about.

Tracking

Second, make git push only send the current branch to its matching upstream (aka tracking) branch. (Otherwise the default behavior is to push all branches that have the same name on both ends.)

git config --global push.default upstream

This is covered in some detail in Mark Longhair’s post An asymmetry between git pull and push.

On any existing branches, you can set up tracking by doing an explicit push:

git push -u origin branchname

Default refspec

At this point you should be set according to all the tutorials I came across. In my experience, however, this only works for branches other than master. A plain git push on master yields the error:

fatal: The current branch master has multiple upstream branches, refusing to push.

The solution is to set the default refspec for git push. I’m unclear on why this needed for master but not for other branches.

git config remote.origin.push HEAD

A Fruitless Search for a Password Bookmarklet

Using a bookmarklet to store passwords is appealingly simple. Alas, after doing some digging, I couldn’t find any viable options.

The first concern I came across is that it important to use a hash algorithm that’s slow (e.g. bcrypt or scrypt). Otherwise it’s too easy to brute-force the master password based on a site password. Suppose site you visit stores your password in plaintext and gets hacked. That breach then compromises your master password, even though only your site-specific password was revealed.

I couldn’t find a JavaScript implementation of scrypt, but I found a JavaScript bcrypt implementation. Better yet, I found a derivative that tidies up the first one, removing dependencies on e.g. ClipperZ, and wraps it in a simple bookmarklet. SuperGenPass provides a much more user-friendly bookmarklet, so I started gearing up to replace it’s MD5 hashing with bcrypt.

But, alas, SuperGenPass (and any other simple bookmarklet) is not secure in the face of a malicious website that contains JavaScript designed to sniff entry of the master password in to the bookmarklet. PwdHash is a browser extension based approach from the Stanford Security Lab designed to combat the weaknesses of the bookmarklet based approach. Their paper, Stronger Password Authentication Using Browser Extensions, is interesting reading and explains a variety of ways to compromise a bookmarklet based approach. PwdHash has already spawned a number of ports to other browsers and mobile devices, but alas they’re all based on prototype code that uses HMAC-MD5 as the hashing algorithm (even though the paper points out PwdHash is a good candidate for a better hashing algorithm).

I was not able to find any PwdHash derivative that used bcrypt. I did find a simple command-line tool based on scrypt, but that’s not great if you don’t have easy access to your own computer.

Solutions like PassPack offer the potential to solve these problems (extension rather than bookmarklet, use of strong encryption rather than weak hashing), but have an Achilles heel of their own: the service provider has the power to decrypt all your passwords. For now I’ll stick with my moinmoin-client-crypt approach.

Misadventures in Breaking Actors with Scala Self-Types

Quick refresher: self-types are commonly used when writing traits that want to proscribe that they get mixed in to a particular class. For example, the cake-pattern leverages them. In the example below, FooTrait specifies a self-type of FooTraitConfiguration to insure that it is mixed in to a class that provides the expected times val.

import actors.Actor
import actors.Actor._

trait FooTraitConfiguration { val times : Int }

trait FooTrait { self:FooTraitConfiguration =>
  case object Ping
  case object Pong

  val a = actor {
    loop {
      react {
        case Ping =>
          self ! Pong
        case Pong =>
          for(_ <- (1 to times)) { print(".") }
          System.out.println("pong.")
  } } }

  def ping = a ! Ping
  def pong = a ! Pong
}

class Foo extends FooTrait with FooTraitConfiguration { @Override val times = 5 }

But, alas, this fails to compile:

error: value ! is not a member of FooTrait with FooTraitConfiguration
self ! Pong

It seems that the self-trait has broken the Actor API! And indeed, it has. Because self-traits are not usually specified with self! It should have been:
this:FooTraitConfiguration =>

The self-type means that within FooTrait the type of this is considered to be FooTrait with FooTraitConfiguration. Using a word other than this additionally sets up an alias to that type for e.g. use within nested classes. And there’s the rub: Actors depend on a method named self which is shadowed when the alias to the type is named self.

Note to self: Don’t use self when specifying self types!

Untangling multi-threaded log files

Yesterday I needed to decipher a log file in which a dozen threads were simultaneously logging messages. Surely there must be tools for this out there. But I couldn’t find one, so I wrote a Python script to indent each line differently based on thread id. I then looked at it in LibreOffice, but just reading on the terminal would have sufficed. Here’s a trivial demo:

2011-04-11 09:40:12,004 [INFO] [http-3] Hello
2011-04-11 09:40:13,554 [DEBUG] [http-1] Wikipedia
(pronounced /ˌwɪkɨˈpiːdi.ə/ WIK-i-PEE-dee-ə)
2011-04-11 09:40:13,605 [INFO] [http-2] PCC Natural Markets
2011-04-11 09:40:13,688 [INFO] [http-3] World
2011-04-11 09:40:14,015 [INFO] [http-2] began as a food-buying club of 15 families in 1953.
2011-04-11 09:40:16,032 [INFO] [http-1] is a multilingual, web-based, free-content encyclopedia project based on an openly editable model
2011-04-11 09:40:17,775 [INFO] [http-2] Today, it's the largest consumer-owned natural food retail co-operative in the United States.

becomes:

09:40:12,004	Hello
09:40:13,554		Wikipedia
09:40:13,554		(pronounced /ˌwɪkɨˈpiːdi.ə/ WIK-i-PEE-dee-ə)
09:40:13,605			PCC Natural Markets
09:40:13,688	World
09:40:14,015			began as a food-buying club of 15 families in 1953.
09:40:16,032		is a multilingual, web-based, free-content encyclopedia project based on an openly editable model
09:40:17,775			Today, it's the largest consumer-owned natural food retail co-operative in the United States.
            	http-3	http-1	http-2

Just read down the columns vertical for a clear chain of events on each thread. Code below is maintained on GitHub.

#!/usr/bin/env python

# Looks at token in a particular position in each line and indents the line
# differently for each unique identifier found in the file. For example, given
# a log file which contains a thread identifier, contents for each thread will
# be separated out into distinct columns.
#
# Lines not matching the pattern (e.g. stack traces) are presumed to have
# occurred at the time of and belong to the same identifier as the preceding line.
#
# Default pattern is: <date> <stamp> ignored [thread_id] <message>
# Yielding output: <stamp><tabs><message>
#
# An alternate regular expression can be supplied on the command line; it must
# include named capture groups 'stamp', 'id', and 'message'. The default regex
# is: ^\S+ (?P<stamp>\S+) \S+ \[(?P<id>[^\]]+)\] (?P<message>.*)
#
# If the input contains very long lines it can be helpful to truncate them
# beforehand by e.g. piping through awk '{print substr($0,0,400)}'

import sys,re
if len(sys.argv) > 1:
  pattern = re.compile(sys.argv[1])
else:
  pattern = re.compile('^\S+ (?P<stamp>\S+) \S+ \[(?P<id>[^\]]+)\] (?P<message>.*)')

delimiter='\t'
max_level = 1
categories = {}
legend = None
indent = ""
stamp = ""

try:
  for line in [l.strip() for l in sys.stdin]:
    m = pattern.match(line)
    if m:
      stamp,identifier,message = [m.group(x) for x in ['stamp','id','message']]
      indent = categories.get(identifier)
      if not legend:
        legend = " " * len(stamp)
      if not indent:
        indent = delimiter * max_level
        categories[identifier] = indent
        max_level += 1
        legend += delimiter + identifier
      print stamp + indent + message
    else:
      # carry over stamp and indent from previous line
      print stamp + indent + line

  print legend
except IOError:
  pass

Snipping log files by time

Grepping through log files for lines that match a timestamp is fiddly. It’s hard to catch multi-line entries (e.g. stack traces) and to craft a regex that captures an exact time range. I wrote a little Python script to simpify the process.

Usage:

 <example.log| ./by_time.py 9:40 9:44:15

Code below is maintained on GitHub.

#!/usr/bin/env python

# Selects time range from a log file. Lines with no time (e.g. stack traces)
# are presumed to have occurred at the time of the preceding line.
#
# Assumes first time-like phrase on a line is the timestamp for that line.
#
# Assumes time format is pairs of digits separated by colons with optional , or
# . initiated suffix. E.g. HH:mm:ss,SSS, HH:mm, etc.
#
# Does not strip blank lines; just use awk 'NF>0' for that.

import sys,re
time_pattern = re.compile("(?:^|.*?\D)(\d{1,2}(?::\d{2})+(?:[,.]\d+)?)")
fields_pattern = re.compile("[:,.]")

if len(sys.argv) < 3:
  print >> sys.stderr, "Please specify start and end times (e.g. %s 13:50 14:10:01,101)." % sys.argv[0]
  exit(1)

for item,index in [["start time",1],["end time",2]]:
  if not time_pattern.match(sys.argv[index]):
    raise ValueError("Cannot parse %s: %s" % (item, sys.argv[index]))

start,end = [[int(x) for x in re.split(fields_pattern, s)] for s in sys.argv[1:3]]
too_soon = True

try:
  for line in sys.stdin:
    line = line.strip()
    m = time_pattern.match(line)
    if m:
      t = [int(x) for x in re.split(fields_pattern,m.group(1))]
      if t >= end:
        break
      elif too_soon and t >= start:
        too_soon = False

    if not too_soon:
      print line
except IOError:
  pass

Taming Firefox + Adblock with browser.sessionstore.max_concurrent_tabs

I tend to have lots of browser tabs open. Even more so with Firefox 4′s Panorama feature, which I find handy despite the frustrating limitation that tab groups cannot be moved between windows. Alas, having many tabs open is suspected to trigger/exacerbate a Firefox memory leak when Adblock Plus is running. My own informal testing corroborates this.

In Firefox 3.6 I had used BarTab, a great plug-in that allowed unloading tabs without closing them to reclaim memory. Alas, it is not yet compatible with Firefox 4.

But it turns out Firefox 4 has a new setting (called Cascaded Session Restore) that provides a reasonable work-around. In about:config set

browser.sessionstore.max_concurrent_tabs=0

…and then, when closed and re-opened, Firefox will not load any tab until you click on it. Now it’s extremely fast to quit, restart, and continue on with reduced memory usage.

JSPWiki-translate-perl and HTML::WikiConverter-MoinMoin

moinmoin-client-crypt was the fun part of a recent Wiki migration project I did. The tedious prelude was getting the content out of an aging JSPWiki version and into MoinMoin.

After some aborted attempts at translating the JSPWiki source from scratch, I decided the path of least resistance would be to leverage HTML::WikiConverter to translate the HTML output of JSPWiki. This turned out to be time consuming as well. To anyone else going down this path I offer up:

  1. A patched version of HTML::WikiConverter-MoinMoin that includes fixes for intra-wiki links, inline images, horizontal rules, and definition lists.
  2. A collection of scripts, dubbed JSPWiki-translate-perl, for retrieving HTML from JSPWiki, pre-processing it to make it more palatable for HTML::WikiConverter, and for generating a MoinMoin-style directory layout to contain it.

The original author of HTML::WikiConverter-MoinMoin seems to have abandoned it. I can sympathize; I certainly hope to avoid translating another Wiki any time soon!