Duplo

Building Blocks & Learning Experiences

Browsing Posts in Software

I’ve often been sad that there is no default keybinding for comment-region in Emacs’s ruby-mode. Eventually it annoyed me enough that I added one:

(add-hook 'ruby-mode-hook
	  (lambda ()
	    (define-key ruby-mode-map "\C-c#" 'comment-or-uncomment-region)
	    )
	  )

This assigns C-c # to comment the current region, or if the current region is already commented, it will uncomment the region.

But what about when there’s no region currently marked? It would be nice if emacs would (un)comment the current line. To do this, I took a page from DJCB at Emacs-fu.

(defadvice comment-or-uncomment-region (before slick-comment activate compile)
  "When called interactively with no active region, comment a single line instead."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (list (line-beginning-position)
	   (line-beginning-position 2)))))

Now with nothing marked, pressing C-c # will cause emacs to toggle commenting on the current line.

In case it isn’t obvious, one should add the abbove snippets to their .emacs file to gain their benefits.

Autotest-inotify is a gem that extends autotest to use Linux’s inotify to monitor changes to your source and test files, running the appropriate tests as files are modified.

By default, autotest implements filesystem polling to detect these changes. This can use a significant amount of CPU cycles1, and can impact battery life in laptops.

Through Linux’s inotify, autotest-inotify inserts callbacks into the underlying filesystem, which allows the filesystem to notify us when files we’re interested in have been modified. This allows autotest to sleep until inotify indicates a change has been made to one our files of interest, i.e. we don’t have to constantly poll the filesystem.

This work was inspired by Sven Schwyn’s work on autotest-fsevent, which extends autotest to use Mac OS X’s FSEvents system, as well as Alban Peignier’s work using the INotify gem. Where autotest-inotify differs from Schwyn’s work, is that autotest-inotify can be used in Linux, whereas autotest-fsevent uses FSEvent, which is Mac OS X specific. Autotest-inotify differs from Peignier’s work in that it offers a simpler gem-based installation, and it is less obtrusive to autotest’s methods for determining which files to watch for changes.

Source code for the autotest-inotify gem can be found at http://github.com/ewollesen/autotest-inotify. It is licensed under the MIT license. See the README for installation instructions.

  1. On one of my machines, ~25% of a single core’s cycles were spent polling the filesystem []

In the process of setting up metric_fu, I found that, one way or another, saikuro’s output wasn’t getting into the correct place. I’ll spare you the long story, and just show the config settings I had to put into my Rakefile to get things working:

config.saikuro = {
  :output_directory => "#{ENV["CC_BUILD_ARTIFACTS"]}/scratch/saikuro", 
  :input_directory => ["app\" --input_directory \"lib"],
  :cyclo => "",
  :filter_cyclo => "0",
  :warn_cyclo => "5",
  :error_cyclo => "7",
  :formater => "text", #this needs to be set to "text"
}
config.flay = {
  :dirs_to_flay => ['app', 'lib',],
  :minimum_score => 10, 
}


My changes in bold.

When my wife recently pointed me to an article by Jim Weirich about Dependency Injection (DI), one of my first thoughts was, “how is this different from the Abstract Factory (AF) pattern?” So I did some searching and found a brief comment from Martin Fowler:

If you have multiple ways to construct a valid object, it can be hard to show this through constructors, since constructors can only vary on the number and type of parameters. This is when Abstract Factory Methods come into play, these can use a combination of private constructors and setters to implement their work. The problem with classic Factory Methods for components assembly is that they are usually seen as static methods, and you can’t have those on interfaces. You can make a factory class, but then that just becomes another service instance. A factory service is often a good tactic, but you still have to instantiate the factory using one of the techniques here.

Fowler’s objections with respect to static methods on interfaces are specific to java, and don’t apply in python or ruby, since neither have native interfaces. Yet I see DI used in both ruby and python, so I still feel like there has to be another difference.

Next I found some interesting thoughts at Stack Overflow, but none of the responses shed a clear light on the subject for me.

What finally got the light in my head to switch on, oddly enough, was an article by Jakob Jenkov. After reading Jenkov, I understood that both AF and DI are responsible for creating instances of objects. Furthermore, they both decouple the class requesting object creation from having to know any details about the created object that they’ll receive. Where they’re different, is that when AF is being used, the class desiring the creation of an object needs to know about—and send a message to—an AF, whereas with DI, the class desiring the creation of an object is simply handed that object during it’s own initialization. To put it another way, the object on which it relies is “injected” into it at its own creation. This is the inversion, that rather than the class needing to ask for an object to be created, it is instead handed the object.

Dependency Injection as compared with Abstract Factory.

Characteristic DI AF
Is responsible for instantiating classes? Yes Yes
Class needs to know details of the created object? No No
Class needs to explicity request creation of desired object? No Yes
Class is dependent upon the DI/Factory that creates objects on its behalf? No Yes

Now that the light was on, I re-read the first few references, and I found that may of them made more sense. Funny how that works.

There are a number of different ways to handle custom error pages in rails. Most use rails’s rescue_from method. This approach allows your error pages to be dynamically rendered in response to errors.

The way I see it, if my site has just encountered an error, I want to immediately go into damage control mode. Do I want to risk dynamically generating an error page? No, not at all. There could be an error in the page rendering that will cause another error when I try to render the error page. Not an ideal situation to say the least. It’s much safer to serve up previously generated static content.

While rails does come with a default, static, error page, said page is largely unstyled, and contains no links to help the user get back to what they were doing. I feel that it’s bad enough that I have to display an error to the user; leaving them with nowhere to go, looking at a jarring, or even ugly, error page isn’t going to make them the happy users that we all want.

Lastly, I don’t want to have to remember to keep the site’s error pages up to date with the latest layout and style.

To summarize, I want static error pages, rendered using rails’s ActionView, and I want them updated automatically any time the site’s style or layout changes.

To accomplish these goals I wrote a rake task and a capistrano recipe. The rake task visits the site, collects the rendered error pages, and stores them in the <RAILS_ROOT>/public directory, where rails will automatically look for them when errors occur. Here’s the rake task:

desc "Generate static error pages (404 and 500)"
task :generate_static_error_pages => [:environment] do
  require "console_app"

  urls_and_paths.each do |url, path|
    r = app.get(url)
    if 200 == r
      File.open(Rails.public_path + path, "w") do |f|
        f.write(app.instance_variable_get(:@body))
      end
    else
      $stderr.puts "Error generating static file #{path} #{r.inspect}"
    end
  end
end

def urls_and_paths
  [["/static/404_not_found", "/404.html"],
   ["/static/500_internal_server_error", "/500.html"],]
end

The capistrano recipe simply runs the rake task each time the application is deployed. Here’s the recipe:

desc "Generate static error pages"
task :generate_static_error_pages, :except => {:no_release => true} do
  run "cd #{current_path} ;
       RAILS_ENV=production rake generate_static_error_pages"
end


I’ve instructed capistrano to execute this recipe each time I deploy my application by using one of capistrano’s many handy callbacks:

after "deploy:symlink", "generate_static_error_pages"

The result is that I have consistently styled, static error pages, that are updated automatically each time I deploy my application.

I found a way to make e17 work with the GNOME Keyring Daemon (GKD), so that I do not have to manually add my ssh keys to ssh-agent every time I login.

I didn’t discover the method myself, but I was on the right track, which led me to this Ubuntu bug report, which contains a successful workaround:

# in ~/.profile
if [ -n "$GNOME_KEYRING_PID" ]; then
    eval $(gnome-keyring-daemon --start)
    export SSH_AUTH_SOCK
fi

The bug report goes into detail, but basically the issue seems to stem from some out of order initialization of ssh-agent, ~/.profile, and the GKD, perhaps with e17’s lack of support for xdg autostart directives.

I was able to search out the bug report after a lot of comparing the output of ps xa and export while logged in via e17 and comparing it to the same from within GNOME. The output of the latter showed two different SSH_AUTH_SOCK formats:

# gnome
SSH_AUTH_SOCK="/tmp/keyring-HvW1Yb/socket.ssh"
# e17
SSH_AUTH_SOCK="/tmp/ssh-RMKCQa4949/agent.4949"

This gave me a hunch that my SSH_AUTH_SOCK was coming from ssh-agent, rather than from GKD. A google search for the terms “pam SSH_AUTH_SOCK” then turned up the bug report above.

In comment #8 of said bug report, Mikel Ward mentions that in xfce4, it’s possible that the GKD’s SSH_AUTH_SOCK is being overwritten by an incorrectly guarded call to ssh-agent in /etc/xdg/xfce4/xinitrc. e17 doesn’t have any such initialization (of which I’m aware), so I presume that my SSH_AUTH_SOCK stems from ssh-agent being called as part of /etc/X11/Xsession.d/90x11-common_ssh-agent, though admittedly I’ve done no work to confirm this hypothesis.

… it has function scope.  Okay, I get that, but apparently I hadn’t totally wrapped my head around just what that means.  In essence, it means that all variables that have a declaration in the function, are declared, regardless of whether or not the line of code which declares them would be executed.  Given the following code:

var foo = "bar";

function test() {
  console.debug("foo is (1st time)" + foo);
  if (false) {
    var foo = "baz";
  }
  console.debug("foo is (2nd time)" + foo);
}

Your console will show something like this:

foo is (1st time) undefined
foo is (2nd time) undefined

Which is a little weird since the local declaration of foo was never executed.  A quick search didn’t turn up any promising hits, but I imagine that there must be a preprocessing step that executes all variable declarations before the function is run.  The very similar function below (diffs in bold):

var foo = "bar";

function test() {
  console.debug("foo is (1st time)" + foo);
  if ("undefined" == typeof(foo)) {
    var foo = "baz";
  }
  console.debug("foo is (2nd time)" + foo);
}

Yields:

foo is (1st time) undefined
foo is (2nd time) baz

A more intentional use is probably (diffs also in bold):

var foo = "bar";

function test() {
  console.debug("foo is (1st time)" + foo);
  if ("undefined" == typeof(foo)) {
    foo = "baz";
  }
  console.debug("foo is (2nd time)" + foo);
}

Which has output:

foo is (1st time) bar
foo is (2nd time) bar

So this isn’t anything groundbreaking, or even weird.  It’s clearly defined1, and discussed2, but the consequences eluded me for about an hour last night.  Hopefully by writing this article, I’ll remember for next time.

  1. http://docstore.mik.ua/orelly/webprog/jscript/ch04_03.htm#jscript4-CHP-4-SECT-3.1 []
  2. http://stackoverflow.com/questions/1711173/declaration-for-variable-in-while-condition-in-javascript []

Just a note to those of you that have tried my MP3 streaming patches for MPD; the patches have been accepted and will be included in the next release of MPD (version 0.14.0).  If you want to try out the development version of MPD, that includes these patches, you can now do so by cloning the master git branch at git://git.musicpd.org/master/mpd.git.

Here’s another little patch for MPD’s git repos that allows FLAC files to return md5sum as if it were a bit of metadata, like artist, title, or album.  A FLAC file’s md5sum is about the closest thing you can get to a unique identifier for that file.  The md5sum is generated from the wav file that is encoded when the FLAC file is created, so even if you change the filename, or its tags (vorbis comments), the md5sum will remain the same.  This code is how Mildred correlates songs playing in MPD with songs in its database.

You can find the patch here: http://kill-0.com/patches/0001-Adds-FLAC-md5sum.patch

After applying the patch, you’ll want to re-create your MPD database file.  You can use the --create-db flag to do so, or just delete your old database file before restarting MPD.

Update: due to wide-spread changes in the MPD git repository, this patch no longer applies and builds correctly.  You can still play with the shout MP3 plugin by cloning my shiny-new git repository at: http://git.musicpd.org/encoded/mpd.git See the comments section below for information about configuration changes.  The plugin is currently on the roadmap for the 0.14.0 release, so keep your fingers crossed.

I’ve updated my patch so that it can be applied against the current MPD git repository.  Hopefully it will be rolled into MPD for the 0.14.0 release.  The patch has been improved to do better configuration-time checking for the lame library.  I also found a bug where I wasn’t setting the bit rate properly if constant bit rate was requeted.

I’m hoping to roll this out to Mildred soon.

Here’s the link:  0001-Creation-of-shout_mp3-audio-output-plugin.-Basicall.patch