/dev/trouble
Eric Roller's Development Blog

General

General development topics.

Google Search Tips

- Posted in General by

Added this blog post to get that piece of scrap paper off my desk and also to remember these tips by means of typing them in.

apples oranges Search for pages with both apples and oranges.

apples OR oranges -worms Either or, not others.

"candied apples" Exact phrase.

+fruit filetype:ppt Only the exact word, in PowerPoint presentations.

~fruit site:meals.com Include synonyms, but only on that site.

define:egoism Search after definitions.

BMW 318...328 Search for ranges, e.g. not the bad 316 model.

link:macworld.com Search after sites linking to macworld.com.

info:www.apple.com/se Show information about apple.se.

related:cdon.com Search for similar sites.

**mac*** All words beginning with mac, e.g. macworld, macintosh.

ARN BSL Search for routes between airports.

Harry Potter For books with harry potter, select the book icon.

stocks:AAPL Stock information.

weather Stockholm Search for weather information.

time Cupertino Get the current time for other places.

sunrise Kuusamo Get the sunrise times, try also "sunset".

5*9+(sqrt 10)^3= Evaluate calculations.

10.5 cm in inches Unit conversions.

66 GBP in EUR Currency conversions.

**Shakespeare wrote *** Let Google fill in the blanks.

P.S. Of course, Google has its own help page on this topic.

We can use iTunes to play music while we do circuit training, i.e. 40 seconds music while we work out, and 15 seconds pause while we rest or go to the next station:

  • save the following AppleScript in ~/Library/iTunes/Scripts; you will probably have to create the Scripts directory;
  • open iTunes with a suitable playlist; we recommend a good song and a Genius playlist;
  • select the first song;
  • launch the script from Scripts menu.

NB. This is an updated version of a previous script.

(* AppleScript for circuit training with iTunes.
The default circuits are 40 seconds each, with pauses of 15 seconds.
At the beginning, the script allows you to set different times.
After every second set, iTunes is asked to go to the middle section
of the next song.

version 2.1, ©2010, Eric Roller
*)

property wCount : 40
property tWork : 40
property tRest : 20
property tFudge : 1.0 -- use this to adjust the rest times

on run
    -- begin by asking for the workout and delay times
    set wCount to askUser("Number of Workouts", wCount)
    set tWork to askUser("Workout Time in Seconds", tWork)
    set tRest to askUser("Rest Time in Seconds", tRest)
   
    -- whether to skip to the next song, but only every other time
    set skip to false
    set remaining to wCount
   
    try
        with timeout of 6000 seconds
            -- enter the workout loop
            repeat while (remaining > 0)
                announceCount(remaining, wCount)
                -- wait, play the music, wait and then stop it again
                sleepFor(tRest, "Rest")
                tell application "iTunes" to play
                sleepFor(tWork, "Workout")
                tell application "iTunes" to pause

                if skip is true then
                    -- every other time, change the track
                    tell application "iTunes" to next track

                    -- skip to the middle section of the next track
                    set tForward to trackSeconds() / 2 - tWork
                    tell application "iTunes" to ¬
                        set the player position to tForward
                end if
                set skip to not skip
                set remaining to remaining - 1
            end repeat
        end timeout
    on error errText number errNum
        if errNum is not -128 then ¬
            display dialog "Error: " & errNum & return & errText
    end try
   
    -- finish by pausing iTunes
    tell application "iTunes" to stop

    -- work out how many iterations we did
    set remaining to wCount - remaining
    if remaining is greater than 0 then ¬
        say "Well done! You completed " & (remaining as text) ¬
        & " workouts."
end run

-- small helper to ask the user for an integer
on askUser(aText, aDefault)
    set anInt to the text returned of ¬
        (display dialog "Set the " & aText default answer aDefault)
    return (anInt as integer)
end askUser

-- helper to announce how many more workouts there are
on announceCount(aCount, maxCount)
    if aCount = maxCount then
        set message to "Starting " & (aCount as text) & " workouts."
    else if aCount = 1 then
        set message to "Last one."
    else if ((2 * aCount) as integer = maxCount) then
        set message to "Half time."
    else if (random number from -1.0 to 1.0) > 0.0 then
        set message to (aCount as text) & " more"
    else
        set message to (aCount as text) & " to go"
    end if
    delay (tFudge / 2)
    say message without waiting until completion
end announceCount

-- helper to wait for a given amount of seconds
on sleepFor(tDelay, workType)
    set tOut to tDelay
    -- apply a fudge factor for the rest times
    if workType is "Rest" then set tOut to tDelay - tFudge
    -- we use a dialog message with a delay
    set answer to display dialog (tDelay as text) & " Seconds " ¬
        & workType buttons "Stop" with title "Circuits Loop"  ¬
        giving up after tOut
    -- trigger an error if we want to stop
    if the button returned of the answer is "Stop" then ¬
        error "User canceled." number -128
end sleepFor

-- helper to determing the length of the current track in seconds
on trackSeconds()
    -- ask iTunes for the track length (MM:SS)
    tell application "iTunes" to get the time of the current track
    set the tLength to the result

    -- split the length into minutes and seconds
    set saveDeli to AppleScript's text item delimiters
    set AppleScript's text item delimiters to {":"}
    set tMinutes to the first text item of the tLength
    set tSeconds to the last text item of the tLength
    set AppleScript's text item delimiters to saveDeli

    -- add up the total length in seconds
    return (tSeconds + 60 * tMinutes)
end trackSeconds

Symptoms: When 'mounting' the external disk, shared over the AirPort Extreme WiFi network, it is not added to the Finder's sidebar; instead, you get an error like this:

The alias can't be opened because the original item can't be found.

Also, dragging the disk icon from the SHARED section in Finder's sidebar to the DEVICES section is not possibe; the Finder just displays a "can't drop it here" icon.

Searching online, I found a discussion on Apple's forums which contained the solution.

Fixing permissions with Disk Utility was not an option since a network-shared disk is not accessible within the app.

Apparently, the disk acquired an "alias" attribute by mistake. This can be checked in the Terminal, where the alias attribute is the capital 'A':

% /usr/bin/GetFileInfo /Volumes/AirDisk
directory: "/Volumes/AirDisk"
attributes: Avbstclinmedz

You can use the following command to turn the alias attribute off (then check again with the above GetFileInfo command and look for a lowercase 'a'):

% /usr/bin/SetFile -a a /Volumes/AirDisk

After that, the mounting problem disappeared.

One sign to check whether the monthly scripts have been executed is to look at the log file in /var/log/monthly.out. If that file were missing of if it did not show results from regular monthly runs, then here's why:

The default setup is to execute the scripts on the first of every month at 5.30 a.m. To change that on Mac OS X, you will want to modify this file: /System/Library/LaunchDaemons/com.apple.periodic-monthly.plist

[Update: If the plist uses Interval and GracePeriod then don't change it; it is already solved].

This blocking effort appears to have started in the Windows world but it is applicable to all UNIX-based systems where a hosts file is used.

Basically, copy the contents of this example hosts file to the end of your /etc/hosts file (requires root access).

[more]

In /etc/hosts, make sure not to remove the pre-defined settings, but you may comment out the duplicate "127.0.0.1 localhost" line. It should look similar to this:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
fe80::1%lo0     localhost

# Custom entries (not shown)


# This MVPS HOSTS file is a free download from:            #
# http://www.mvps.org/winhelp2002/                         #
#                                                          #
# Notes: the browser does not read this "#" symbol         #
# You can create your own notes, after the # symbol        #
# This *must* be the first line: 127.0.0.1     localhost   #
# *********************************************************#
# ---------------- Updated: Sept-02-2009 ------------------#
# *********************************************************#
#                                                          #
# Entries with comments are all searchable via Google.     #
#                                                          #
# Disclaimer: this file is free to use for personal use    #
# only. Furthermore it is NOT permitted to copy any of the #
# contents or host on any other site without permission or #
# meeting the full criteria of the below license terms.    #
#                                                          #
# This work is licensed under the Creative Commons         #
# Attribution-NonCommercial-ShareAlike License.            #
# http://creativecommons.org/licenses/by-nc-sa/3.0/        #

##DUPLICATE:
##127.0.0.1  localhost

#start of lines added by WinHelp2002
# [Misc A - Z]
127.0.0.1  fr.a2dfp.net
127.0.0.1  m.fr.a2dfp.net
127.0.0.1  ad.a8.net
[...]

Finally, remember to check the example hosts file for updates; it is updated quite frequently.

To automate this process, I have created this script. You would need to execute it with "sudo" (or it could be placed into /etc/periodic/monthly ?).

#!/bin/sh
# File: 900.host_db_update

echo "Started /etc/hosts update"

# Download the current version without progress info:
curl -so /tmp/hosts.zip https://winhelp2002.mvps.org/hosts.zip

if [[ -s /tmp/hosts.zip ]]; then
    # Unzip quietly and convert CRLF -> LF
    unzip -aoqq -d /tmp /tmp/hosts.zip HOSTS
    rm /tmp/hosts.zip
fi

if [[ ! -fs /tmp/HOSTS ]]; then
    echo "Error: Download of hosts file failed."
    rm -f /tmp/HOSTS
    exit 1
fi

tmpdate=$(grep -m 1 Updated: /tmp/HOSTS|awk '{print $4}')
etcdate=$(grep -m 1 Updated: /etc/hosts|awk '{print $4}')

if [[ "$tmpdate" == "$etcdate" ]]; then
    echo "Info: Hosts file is already up-to-date ($etcdate)"
    rm -f /tmp/HOSTS
    exit 0
fi

# Remove the previous MVPS additions from /etc/hosts
sed '/^# This MVPS HOSTS/,$ d' /etc/hosts > /tmp/hosts.new

# Append the new settings
sed '/^[^#].* localhost$/ s/^/##/' /tmp/HOSTS >> /tmp/hosts.new
rm /tmp/HOSTS

# Make a backup and move the new file:
cp /etc/hosts{,~}
mv /tmp/hosts.new /etc/hosts

# Print a message:
echo "Updated /etc/hosts with settings from $tmpdate"
exit 0

Essential Mac Applications

- Posted in General by

When installing Snow Leopard, it occurred to me that there are a number of applications that I like and that I (almost) always use. They are, in alphabetical order:

Calico ($59 keskus.com)

An easy to use tool to stitch together multiple photos into panoramas.

Camino (open source, caminobrowser.org)

While I use Safari almost throughout, my bank is the only one that is deliberately refusing to support it. Firefox is good a good browser, but for my purposes it is too big. Camino, being specifically for the Mac, is just what I need for my bank.

Chicken of the VNC (open source, sourceforge.net)

A simple VNC client.

Cyberduck (donateware, cyberduck.ch)

An FTP client will all the bells and whistles to keep you happy (for those cases where "Conntect To Server" in the Finder is not sufficient to your needs).

DrawBerry (donateware, raphaelbost.free.fr)

A simple graphics app.

Fission ($32 rogueamoeba.com)

An easy to use audio editor with a nice waveform viewer (where Garageband is just overkill).

GraphicConverter ($35, lemkesoft.com)

I still use version 5.9.2 since it works fine for my needs.

HexEdit (open source, sourceforge.net)

For those rare cases where you like to dig in and see the guts of a file. Unless you are Japanese, you should stay away from the Japanese "J" version (look under Files for the one without the "J").

iLife ($79 or free with every new Mac, apple.com)

I mainly use iPhoto and iWeb. Most recently, I opted out of installing iMovie and GarageBand since I simply never use them.

iVolume ($30, mani.de)

Analyses and adjusts the loudness of your songs in iTunes.

iWork ($79, apple.com)

I mostly use Pages, but have also discovered that Keynote can be used as a vector-based drawing tool. The only problem is that every new major version cost again $79, which is why I feel inclined to skip one or two versions before upgrading.

Pixelmator ($59, pixelmator.com)

A photo editor. Not quite yet on the same level as Photoshop, but much more affordable and it keeps getting better and better.

TextWrangler (freeware, barebones.com)

Not quite willing to pay for the infamous BBEdit, I find that TextWrangler is an excellent alternative. I particularly like the graphical "diff" tool and that you can launch it from the Terminal (via custom edit and twdiff commands)

Tunnelblick (open source, code.google.com/p/tunnelblick/)

An OpenVPN client for the Mac. Only useful if you use OpenVPN.

An old trap that I keep to be falling into is this one:

> find . -name "Frameworks" -prune -or -name "Info.plist"
./Frameworks
./Info.plist

Notice how the Frameworks folder is also returned (since -prune defaults to true), but the intention was to exclude it! The solution is to add -print:

> find . -name "Frameworks" -prune -or -name "Info.plist" -print
./Info.plist

We can use iTunes to play music while we do circuit training, i.e. 40 seconds music while we work out, and 15 seconds pause while we rest or go to the next station:

  • save the following AppleScript in ~/Library/iTunes/Scripts; you will probably have to create the Scripts directory;
  • open iTunes with a suitable playlist; we recommend a good song and a Genius playlist;
  • select the first song;
  • launch the script from Scripts menu.

Note: There exists a newer version of this script!

(* AppleScript for circuit training with iTunes.
The default circuits are 40 seconds each, with pauses of 15 seconds.
At the beginning, the script asks for different times.

©2009, Eric Roller
*)

-- begin by asking for the workout and delay times
set tWork to the text returned of ¬
    (display dialog "Set the Workout Time [s]" default answer "40")
set tPause to the text returned of ¬
    (display dialog "Set the Delay Time [s]" default answer "15")

-- whether to skip to the next song, but only every other time
set skip to false

-- enter the forever loop
repeat
    -- start playing the music
    set volume without output muted
    tell application "iTunes" to play

    -- delay for 40 seconds by means of a dialog
    set answer to display dialog tWork & " Seconds Workout" ¬
        buttons "Stop" with title "Circuits Loop" ¬
        giving up after tWork
    -- stop if requested
    if the button returned of the answer is "Stop" then exit repeat

    -- stop the music, actually just mute it
    set volume with output muted
    if skip is true then
        -- every other time, change the track
        tell application "iTunes" to next track
    end if
    set skip to not skip

    -- wait 15 seconds (playing the song muted)
    set answer to display dialog tPause & " Seconds Pause" ¬
        buttons "Stop" with title "Circuits Loop" ¬
        giving up after tPause
    if the button returned of the answer is "Stop" then exit repeat
end repeat

-- finish by unmuting the volume and pausing iTunes
tell application "iTunes" to pause
set volume without output muted

Note that we go to the next track after every other workout. Also, since the volume is muted, we skip the first 15 seconds of every song. This is deliberate!

Let's first take a look at how Apache is configured (for Mac OS X 10.5.6 Leopard). In the Terminal:

> httpd -V
Server version: Apache/2.2.9 (Unix)
Server built:   Sep 19 2008 10:58:54
Server's Module Magic Number: 20051115:15
Server loaded:  APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
Architecture:   32-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/prefork"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_FLOCK_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT="/usr"
 -D SUEXEC_BIN="/usr/bin/suexec"
 -D DEFAULT_PIDLOG="/private/var/run/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_LOCKFILE="/private/var/run/accept.lock"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="/private/etc/apache2/mime.types"
 -D SERVER_CONFIG_FILE="/private/etc/apache2/httpd.conf"

Notice where the configuration file is (see last line); this is the file we would use if we enabled the web server from the System Preferences : Sharing : Web Sharing. However, we much rather not change that configuration file; instead we shall simply supply a different one that we keep outside the /private/etc area.

[more]

Before we go ahead with our personal configuration file, it is a good idea to compare our settings to those provided by Apple; use a "diff" tool of your choice (I like twdiff that comes with BareBones' TextWrangler). Once our settings are complete, we shall begin with a syntax check:

> apachectl -f /path/to/conf/httpd-debug.conf -t
Syntax OK

To launch Apache with our own configuration, we run:

> sudo apachectl -f /path/to/conf/httpd-debug.conf -k start

To verify that it is running, we can issue this command (when o.k. we will get multiple lines for multiple httpd instances):

> ps -e | grep httpd | grep usr

Finally, to view the web site in Safari, we simply open the location: http://localhost/ .

Following the instructions on DroboShare, the Drobo disk must be reformatted as "MacOS Extended", i.e. not journalled. Furthermore, to prevent Time Machine from filling up the Drobo indefinitely, one may like to partitioned it:

Partition 1: Tardis (500GB) ... for Time Machine Partition 2: Dalek (1.5TB) ... for general use

Next problem was to copy the previous Time Machine image onto the new partition. For better performance, we did this with both the old backup disk (Diskus) and the Drobo (Tardis & Dalek) connected. This suggestion from an arstechnica forum appeared to do the trick:

sudo /usr/local/rsync/bin/rsync -aNHAXx --protect-args --fileflags \
    --force-change /Volumes/Diskus/Backups.backupdb /Volumes/Tardis

NB. that this is not the rsync that came with Mac OS X, but version 3.0.1 that we have compiled with support for extended attributes.