Mac Tips, Tricks and Utilities

I’m always looking for a way to get more out of my setup. In the past year, since moving from Windows to OSX, I’ve accumulated some knowledge and utilities I’d like to share.

Multiple Monitors

These past few years, I’ve grown accustomed to working on a two-monitor setup. I wanted to move forward to three monitors (two external, one internal), but the only way to do this with the MacBook Pro I have (15-inch, Early 2011) was to buy two thunderbolt-enabled Apple monitors. Since I don’t feel like shelling out $1000 for each of those, I started looking for other solutions. The absolute best one I found was using an external USB graphics card. In my case, I use the Plugable UGA-2K-A ($62 at the moment of writing this post) and daisy-chain my two Dell 24″ monitors. It’s based on the DisplayLink DL-195 chipset and has great drivers for OSX, which lately also added the ability to rotate the external monitor 90°. The refresh rate is great even for a resolution of 1920×1200 and I can only imagine what the USB 3.0 based models can do. I’ve had one card die on me and got great customer service from Plugable, who sent me a replacement, no questions asked.

BetterTouchTool (free)

I work with an Apple Magic Mouse, which is based on the great idea of integrating a trackpad on a mouse. Of course, it’s lacking in many respects, but my bigger issue with it is that it doesn’t have a way to middle-click. BetterTouchTool is a utility that lets you define custom actions for your mouse, keyboard and trackpad. I installed it, set three-finger-click to be recognized as middle-click and haven’t looked back since. Later on I started adding more shortcuts, like having the top three points of my trackpad being, from left to right, close, minimize and maximize, in the same order as these actions appear on windows. I also like the author’s SecondBar utility, but personally I don’t find it as useful.

Little Snitch (not free)

Powerful firewall, though it gets kind of annoying if you don’t define broad rules. Already helped me catch one too many applications trying to call home. I don’t think there’s much left to say about it that hasn’t already been said.

Skitch (free)

The ⌘⇧4 shortcut and its friends in OSX let you capture parts of your screen, but this functionality is very basic. Enter Skitch, which sits in your tray and when you press ⌘⇧5, gives you some basic editing functionality and the ability to drag the screenshot as a file (for instance if you want to upload it). I use it heavily when moderating submissions to Unfortunately it has the downside of being very pesky about its integration with Evernote (which bought the company last year).

.osx (free)

Always ask for more from your OS. The link is to a Hacker News discussion about tweaks you can perform in OSX. Here’s my list:

defaults write NSGlobalDomain AppleKeyboardUIMode -int 3
defaults write NSGlobalDomain AppleFontSmoothing -int 2
defaults write showhidden -bool true
defaults write NSGlobalDomain AppleEnableMenuBarTransparency -bool false
defaults write NSGlobalDomain AppleShowAllExtensions -bool true
defaults write ShowPathbar -bool true
defaults write ShowStatusBar -bool true
defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode -bool true
defaults write NSGlobalDomain PMPrintingExpandedStateForPrint -bool true
defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false
defaults write NSGlobalDomain KeyRepeat -int 0.02
defaults write NSGlobalDomain InitialKeyRepeat -int 12
defaults write BrowseAllInterfaces -bool true
defaults write _FXShowPosixPathInTitle -bool true
defaults write DSDontWriteNetworkStores -bool true
defaults write FXEnableExtensionChangeWarning -bool false
/usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/
defaults write WarnOnEmptyTrash -bool false
defaults write DebugSnapshotsUpdatePolicy -int 2
defaults write disablePingSidebar -bool true
defaults write disablePing -bool true
chflags nohidden ~/Library
defaults write LSQuarantine -bool false
defaults write AppleShowAllFiles TRUE
defaults write dearchive-reveal-after -bool TRUE

for app in Safari Finder Dock Mail SystemUIServer; do killall "$app" >/dev/null 2>&1; done

f.lux (free)

Do you find yourself waking up at night sometimes, thinking about a cool idea, opening your laptop’s lid drowsily only to have your pupils catch fire by the glow of the monitor? f.lux automatically sets the temperature of your monitor to match the amount of light outside. Now your eyes can adjust more easily and your brain won’t send out an OMG WAKE UP IT’S MORNING alarm.

TotalFinder (not free)

This is the most recent addition to the list. Though it still lacks tested support for OSX Mountain Lion, it still works and works great. It adds tab support, side-by-side panes, etc. to the Finder. Also valuable is the global key combination to pop-up a finder window. Unfortunately it’s not free unless X.

Homebrew (free)

THE package manager for OSX. In stark opposition to MacPorts, it doesn’t require you to sudo it all the time. Unfortunately, the quality of the packages varies widely, so caveat emptor.

If you have any utilities or tips and tricks you’d like to share, please do. I’d love to get more out of my setup.

Unit Testing MySQL-Bound Code

I’m currently working on a product that is very tightly bound to MySQL. It’s so tightly coupled, in fact, that unit testing it while mocking the database access is meaningless. Unfortunately, accessing a MySQL database from the build server (or any machine) is not something that we can take for granted, not to mention concurrency (one person running the unit tests in parallel to another, messing each other’s sandbox) and the network I/O to an external server.

The solution I came up with would be to use an in-process, in-memory database to mock MySQL, so I looked to H2 (good) and HyperSQL (better), but neither had the same power as MySQL had.

Browsing through the Interwebs, I stumbled into mysql-je, a hack from back in 2006 which let you run MySQL as an in-process database, but it was so unstable and unmaintained that I kept looking and came across MySQL Connector/MJX. MJX is an in-process database that, unfortunately, needs access to the filesystem to store its files (you can use the temporary files’ directory), but comes in the form of handy (not so little) jars and works well when invoked from the JVM.

We need two things from this experiment:

  1. To be able to isolate and access our own MJX database.
  2. To intercept any and all calls to MySQL and handle them instead of the usual MySQL driver.

Let’s start by adding it to SBT:

val aspectj = "org.aspectj" % "aspectjrt" % "1.5.4" % "test"
val mxj = "mysql" % "mysql-connector-mxj" % "5.0.12" % "test"
val mxjdb = "mysql" % "mysql-connector-mxj-db-files" % "5.0.12" % "test"

And now we reload and wait, because the mysql-connector-mxj-db-files jar is almost 140MB in size (since it contains the binaries to run MySQL on multiple platforms) and takes while to download. While waiting, let’s take a look at the code, which lives in the ScalaTest unit testing environment:

package mysqlmock

import java.lang.String
import org.scalatest._
import java.sql.{Connection, DriverManager}
import util.Random
import collection.JavaConversions._
import java.util.Properties
import{MysqldResourceI, MysqldResource}

trait MySqlIntercepting extends AbstractSuite {
    this: Suite =>

    // Note: This is almost an exact copy from the BeforeAndAfterAll trait, just so we don't force anyone to mix it in
    abstract override def run(testName: Option[String], reporter: Reporter,
                              stopper: Stopper, filter: Filter,
                              configMap: Map[String, Any],
                              distributor: Option[Distributor], tracker: Tracker) {
        var thrownException: Option[Throwable] = None

        // Force registering of mysql driver

        // Kill mysql driver
        val drivers = enumerationAsScalaIterator(DriverManager.getDrivers)

        // Register our new faking driver
        val driver = new MockMySqlDriver()

        try {
  , reporter, stopper, filter, configMap, distributor, tracker)
        catch {
            case e: Exception => thrownException = Some(e)
        finally {
            try {
                thrownException match {
                    case Some(e) => throw e
                    case None =>
            catch {
                case laterException: Exception =>
                    thrownException match {
                        // If both run and shutdown throw an exception, report the test exception
                        case Some(earlierException) => throw earlierException
                        case None => throw laterException

    // This is a shortcut to getting a connection
    protected def createConnection(): Connection = {

protected[mysqlmock] object MockMySqlDriver {
    val internalConnectionStringPrefix = "jdbc:test"

protected[mysqlmock] class MockMySqlDriver extends com.mysql.jdbc.Driver {
    private val databaseName: String = Random.alphanumeric.take(50).mkString
    private val databaseDir: File = new File(new File(System.getProperty("")), databaseName)
    private val portNumber = (Random.nextInt(10049 - 10011) + 10011).toString // Unused port range
    private val databaseInstance = new MysqldResource(databaseDir)
    private var connectedAtLeastOnce: Boolean = false
    private val username = "test"
    private val password = "test"

    private def initializeDatabase() {
        if (!connectedAtLeastOnce) {
            // Only initialize the database once
            val options = Map(
                (MysqldResourceI.PORT -> portNumber),
                (MysqldResourceI.INITIALIZE_USER -> "true"),
                (MysqldResourceI.INITIALIZE_USER_NAME -> username),
                (MysqldResourceI.INITIALIZE_PASSWORD -> password)

            databaseInstance.start("mysqld-" + databaseName, options)

            if (!databaseInstance.isRunning) {
                throw new RuntimeException("MySQL did not start.")

            connectedAtLeastOnce = true

    def shutdown() {
        if (connectedAtLeastOnce)

    override def acceptsURL(url: String) =
        // MySQL mocking
        url.startsWith("jdbc:mysql://") ||
        // Internal database
            url == MockMySqlDriver.internalConnectionStringPrefix ||
        // Or direct calls to mxj

    override def connect(connectionString: String, props: Properties): Connection = {
        if (props.size() > 0) // If we came here with properties, then it's a call from ourselves
            return super.connect(connectionString, props)

        props.put("createDatabaseIfNotExist", "true")
        props.put("server.initialize-user", "true")
        props.put("--default-character-set", "utf8")
        props.put("--default-collation", "utf8_general_ci")
        props.put("user", username)
        props.put("password", password)

        // Make sure the database is running

        // Create a connection string to use with our database
        val string: String = "jdbc:mysql:mxj://localhost:" + portNumber + "/" + databaseName

        super.connect(string, props)

As you can see from the code above, what we’re doing is creating a database for each test suite and throwing it away in the end. In addition to having the MySqlIntercepting trait intercept any attempt to connect to MySQL and redirect it to the temporary instance, let’s take a look at how we can mix it into our tests:

class MyTests extends Suite with BeforeAndAfter with MySqlIntercepting {
    before {
        val myConnection = super.createConnection()
        try {
            val statement = myConnection.createStatement()
            try {
                statement.execute("some sql here to initialize the database before each test")
            } finally {
        } finally {

    after {
        val myConnection = super.createConnection()
        try {
            val statement = myConnection.createStatement()
            try {
                statement.execute("some sql here to clean up the database after each test")
            } finally {
        } finally {

    // tests...

We ended up mocking MySQL without really mocking it. Access is extremely fast (with a little bit of time for bootstrapping per suite), and we’ve stripped away all of the unknown variables of using a shared, non-dedicated database server.

Addendum: Stopping in the middle of a test (without letting the test finish), for instance while debugging a test, will leave the mysqld process running, so to kill all dangling processes, use this:

ps -ef | grep | grep -v grep | awk '{print "kill "$2}' | bash

When To Leave

I’ve been using Waze for a long time now and I love how it can predict very accurately how much time a drive somewhere would take. However, I didn’t like the fact that when I want to know when to leave one place to get to another, I had to keep re-opening the app and to check whether I would arrive on time if I left at that exact moment.

So I wrote a little something to find out when I need to leave.

I took the opportunity to learn some bash scripting, since I’m new to Unix. I welcome any critique of my work, if you have any.

The script queries the Google Geocoding API for both addresses and sends a routing request to Waze’s servers (warning: that’s somewhat of an unstable hack there). It then polls every now and then and when you have to leave, it sends a notification using Boxcar to your phone. It then nags you until you Ctrl-C the script (yeah, I didn’t care to make something prettier). If you open the notification in Boxcar and click the link, it opens Waze on the spot you want to go and all you need to do is set that as your destination.

Please note that this script Works On My Machine and I don’t guarantee it would on yours too.

What You Need:

  1. An iPhone with Boxcar (it’s free) installed.
  2. A Unix machine (I’m using Mac OSX Lion).


  1. Go to Boxcar and create a new provider. Note down its API key and the email you registered with.
  2. Copy the script below to a file and make it executable. Change the two variables at the top of it to the API key and email you kept when you registered for Boxcar.
  3. Create a file called wtl.presets with presets you want to use, such as home or work. The file’s structure is lines of: [preset name] [address]
    The preset’s name must not include spaces.

Calling It:

./ [address/preset of origin] [address/preset of destination] [when to arrive] [minutes head-start]
  • Address / Preset – Either a well-defined address (e.g. 1600 Pennsylvania Avenue, Washington, DC or even The White House – if Google can find it automatically on a map, then you’re good) or a preset from the file (see #3 above).
  • When To Arrive – The time you want to arrive at your destination, formatted as %Y-%m-%d %H:%M (e.g. 2011-12-13 15:00).
  • Minutes Head-Start – How many minutes you want the notifications to start coming before you need to leave.
Example: ./ home "The Western Wall" "2011-12-05 10:00" 10

This will notify me 10 minutes before I need to leave home to get to The Western Wall at 10am, December 5th, 2011.

Future Work:

Writing a web application that would replace this bash script is a great direction, since a native iOS application would be somewhat useless here, since it can’t poll the server while closed.

The Source Code:


BOXCAR_EMAIL=#Add your Boxcar email here
BOXCAR_API_KEY=#Add your Boxcar API key here

EPOCH_TO_ARRIVE=`date -j -f "%Y-%m-%d %H:%M" "$3" "+%s"`

FROM_ADDRESS=`grep "$1" wtl.presets | awk '{ $1=""; gsub(/^ /,""); print }'`

if [ "$FROM_ADDRESS" = "" ]; then

FROM_ADDRESS=`echo $FROM_ADDRESS | sed 's# #+#g'`

TO_ADDRESS=`grep "$2" wtl.presets | awk '{ $1=""; gsub(/^ /,""); print }'`

if [ "$TO_ADDRESS" = "" ]; then

TO_ADDRESS=`echo $TO_ADDRESS | sed 's# #+#g'`
FORMATTED_2=`echo $2 | sed 's# #+#g'`

echo Looking up origin address...

ORIGIN=`curl -s --get --data sensor=false --data address=$FROM_ADDRESS | ./jsawk 'if (this.status != "OK" || this.results.length != 1) return "ERROR"; return "x%3A" + this.results[0].geometry.location.lng + "+y%3A" + this.results[0];'`

if [ "$ORIGIN" = "ERROR" ]; then
    echo Unable to parse origin address

echo Looking up destination address...

DESTINATION=`curl -s --get --data sensor=false --data address=$TO_ADDRESS | ./jsawk 'if (this.status != "OK" || this.results.length != 1) return "ERROR"; return "x%3A" + this.results[0].geometry.location.lng + "+y%3A" + this.results[0];'`

if [ "$DESTINATION" = "ERROR" ]; then
    echo Unable to parse destination address

echo Starting time calculations.

while [ true ]
    TIME_TO_DRIVE=`curl -s --get -d from=$ORIGIN -d to=$DESTINATION -d returnJSON=true -d returnGeometries=false -d returnInstructions=false -d timeout=60000 -d nPaths=1 | ./jsawk "var total = 0; for (var i = 0; i < this.response.results.length; i++) { total += this.response.results[i].crossTime; } return total;"`

    EPOCH_NOW=`date +%s`

    let "TIME_LEFT = ($WHEN_TO_LEAVE - $EPOCH_NOW) / 60"

    if [[ $TIME_LEFT -le 0 ]]; then
        let "TIME_LATE = 0 - TIME_LEFT"
        LL=`echo $DESTINATION | sed -E 's/x%3A(.+)\+y%3A(.+)/\2,\1/'`
        curl -d "email=$BOXCAR_EMAIL" -d "notification[message]=Leave!+You+are+$TIME_LATE+minute/s+late+to+leave+to+$FORMATTED_2!" -d "notification[source_url]=waze://?ll=$LL"$BOXCAR_API_KEY/notifications
        echo Leave! You are $TIME_LATE minute/s late to leave to $2!
        sleep 60
        echo Not yet. You still have $TIME_LEFT minute/s left.

        if [[ $TIME_LEFT > 10 ]]; then
            let "SLEEP_TIME = $TIME_LEFT / 2 * 60"
            sleep $SLEEP_TIME
            sleep 60


Working with HDFS has many benefits, but there’s one disadvantage that for me, at least, was very painful and that is that it doesn’t behave like other POSIX file system. If you want to access the filesystem, you have to use it via the hadoop -fs commands.

To work around this limitation, there’s FUSE for HDFS, which exposes HDFS as a mount point on your machine. This means that you can now expose files from HDFS to any service that speaks POSIX and also to the command line. A nice side effect is that you can now use a visual client, like WinSCP, to explore your HDFS.

In my case I’ve gone with Cloudera’s implementation, which is still quite raw (as in “do not use in production” raw), and installed it on a 64-bit CentOS 5.5 server. Here’s a quick guide of how to install it.

First, install Cloudera’s repository:

yum --nogpgcheck localinstall cdh3-repository-1.0-1.noarch.rpm

Now, install Java, Hadoop Client and FUSE:

yum install java-1.6.0-openjdk-devel
yum install hadoop-0.20-native.x86_64
yum install hadoop-0.20-libhdfs.x86_64
yum install fuse-libs.x86_64

Next, install the FUSE implementation for HDFS:

yum install hadoop-0.20-fuse.x86_64

Since JAVA_HOME is hard-coded to be /usr/lib/j2sdk1.6-sun, you need to create a link to it (this gave me quite a bit of grief):

ln -s $JAVA_HOME /usr/lib/j2sdk1.6-sun

Now create the mount-point for HDFS:

mkdir [mount point]
hadoop-fuse-dfs dfs://[server]:[hdfs port] [mount point]

And you’re good to go.

Bonus Reading: What is FUSE?