Caius Theory

Now with even more cowbell…

Solve volume down button not working on iPhone 5

I noticed this morning that my volume down button (-) wasn’t working on my iPhone 5 running iOS 7. Pushing the physical button in didn’t change the volume. The volume up button increased the volume successfully still.

As is my normal first step debugging iPhone weirdness, I rebooted the phone by turning it off, leaving it off for a few seconds, then booting it back up with the power button. Once powered off and on in this way, the volume down key still didn’t decrease the volume.

Fearing a physical button issue at this point, I turned to google for suggestions on what else to try. Running across this thread on Apple’s discussion forums, I tried out the solution in there.

  1. Open “Settings”
  2. Scroll down and tap on “General”
  3. Tap on “Accessibility”
  4. Scroll down to the bottom and tap on “AssistiveTouch”
  5. Tap the toggle for AssistiveTouch to turn it on, and you should see a little icon appear on screen (white circle contained in a dark grey rounded square)
  6. Tap the AssistiveTouch icon (was in the top left corner on screen for me)
  7. Tap on “Device”
  8. Tap “Volume Down” a bunch of times and you should see the volume being turned down
  9. Tap outside the AssistiveTouch dialog to close it
  10. Try pushing the physical Volume Down button

In my case, following these steps made my physical volume down button start working again. Makes me wonder if the solution author on the apple discussion thread is right, in that this is a software issue and forcing a volume down action through the on-screen interface makes it remember that there’s a physical button to respond to as well.

Either way, I can stop deafening myself whenever I receive a notification now!

Compile & run swift files directly

Turns out you can run a swift file without having to compile it into a binary somewhere and then run that binary. Makes swift behave a bit more like a scripting language like ruby or python when you need it to.

Using the xcrun binary, we can reach into the current Xcode /bin folder and run binaries within there. So xcrun swift lets you run the swift binary to compile files for instance. If you view the help with -h, there’s a useful flag -i listed there:

-i Immediate mode

Turns out immediate mode means “compile & run” in the same command, which is what we’re after.

    $ cat hello.swift
    println("Hello World")

    $ xcrun swift -i hello.swift
    Hello World

Bingo. But what if we want to make hello.swift executable and call it directly without having to know it needs the swift binary to call it. Unix lets files define their shebang to say how the file needs to be executed, so lets go for that here too!

    $ cat hello2.swift
    #!/usr/bin/env xcrun swift -i
    
    println("Hello World 2")

    $ chmod +x hello2.swift
    $ ./hello2.swift
    Hello World 2

No more having to fire up Xcode for quick CLI tools, especially ones using the system frameworks!

Rename Google Drive folder on Mac

  1. Quit Google Drive app
  2. Rename “~/Google Drive/” to whatever you want
  3. Open Google Drive and wait for it to complain the folder is missing
  4. Click the menu item and click the warning item
  5. Click “Locate Folder..” button on the right in window that pops up
  6. Find your renamed folder and hit OK
  7. There is no step seven

Add to iCloud Reading List programmatically

One piece of a larger puzzle I’m trying to solve currently, was how to add a given URL to my Apple “Reading List” that is stored in iCloud and synced across all my OS X and iOS devices. More specifically, I wanted to add URLs to the list from my mac running Mavericks (10.9). I had a quick look at the Cocoa APIs and couldn’t see anything in OS X to do this. (iOS has an API to do it from Cocoa-land it seems though.)

I figured Safari.app was the key to getting this done on OS X, given it has the ability itself to add the current page to the reading list, either via a keyboard command, a menu item, or a button in the address bar. One quick mental leap later, and I was wondering if the engineers at Apple had been nice enough to expose that via Applescript for me to take advantage of.

One quick stop in “Script Editor.app” later, and I had the Applescript dictionary open for Safari.app. Lo and behold, there is rather handily an Applescript command called “add reading list item”, which does exactly what I want. It has a few different options you can call it with, depending on whether you want Safari to go populate the title & preview text, or if you want to specify it yourself at save-time.

As I want to be able to call this from multiple runtimes, I’ve chosen to save it as an executable, which leans on osascript to run the actual Applescript. And here it is:

#!/usr/bin/env osascript

on run argv
    if (count of argv) > 0
        tell app "Safari" to add reading list item (item 1 of argv as text)
    end if
end run

Save it as whatever you want (eg. add_to_reading_list), make it executable (chmod +x add_to_reading_list), and then run it with the URL you want saving as the first argument.

$ add_to_reading_list "http://caius.name/"
$ add_to_reading_list "http://google.com/"
# … etc …

(Adding support for specifying preview text and title is left as an exercise for the reader!)

Have fun reading later!

Happy Villanelle

The writing group that Carole and Liberty belong to had a homework this month to write a Villanelle. It’s a very specific kind of poem, written to both a repeating line structure and a rhyming pattern. (If you go read Liberty’s villanelle she explains it properly at the start.)

However, after reading both Carole’s and Liberty’s, I was feeling they’d both done very depressing poems. It might be a strict structure of poem, but there’s no need to make the subject matter so down!

So here’s my overly enthusiastically attempt to try and balance the world of villanelle’s into something less depressing!

Striding out down the street at last,
Like I own this town,
Tipping my hat to all that I passed.

Smiling at a friendly chugger who asked,
Grinning at an exuberant clown,
Striding out down the street at last.

Saluting the bookie behind his glass,
Turning frowns upside down,
Tipping my hat to all that I passed.

Tapping my feet and having a blast,
Abusing verbs like they were a noun,
Striding out down the street at last.

Being amused by kids playing on grass,
Seeing the queen in her glorious crown,
Tipping my hat to all that I passed.

Compared to sadness I am a contrast,
Cheering folk up in my dressing gown,
Striding out down the street at last,
Tipping my hat to all that I passed.

Pair new device with Nexxus Drive Transmit Pro

The device is a bluetooth to FM transmitter with Model number NEX-FMTX-BTCK. (Hereafter DTP.)

The set of instructions I use to pair it to a new device, having lost the user manual/instruction booklet, is as follows:

  1. Remove all previously paired devices from range (turn them off/move them away from the DTP.)
  2. Turn the power on to the DTP without touching any buttons.
  3. Let it flash the blue call button a couple of times as it searches for known devices.
  4. Hold the call button down until the call/hangup buttons flash blue/red respectively.
  5. Find the “Drive Transmit Pro” on your device you want paired to it and pair with DTP.
  6. Test out the pairing by calling your girlfriend and talking to her in a funny accent.
  7. Celebrate with a beer!

Church intertwined with State

In the UK currently we’re moving (slowly) toward the same sex marriage bill making it’s way into law. (It’s got a way to go still, but support seems to be there now at least.)

For the record, I’m glad to see the state moving toward allowing two people to be united under law, irrespective of terminology used - and with equal rights to those currently enjoyed by the uniting of a man & woman to date. But for a while now I’ve been thinking that the discussion is presented in an unclear fashion, which causes people to jump to polarising positions on it, without any common ground.

The way I see it is the UK has been a country with Religion and State intertwined for many, many hundreds of years - and therefore we have some constructs that exist both in law, and religion, but are conflated under one word and changing one appears to be changing them both.

The Church of England is Protestant, because Henry VIII wanted to get a divorce and the Catholics wouldn’t allow him that, so we as a country “forked” our own religion that wasn’t so different, but allowed divorce of marriage. Times were slightly different back then, the church had a lot more direct power in terms of laws & how people lived. We’re a more diverse society today, and the church has less (direct?) involvement in our laws, although older laws are still based upon that original conflation of state and church.

I almost wonder if in this case (and others) we need to start diverging church from state and allowing the state to change things irrespective of the church, whilst still allowing the church to continue unhindered with practices it’s held for many years. Seems like the best of both worlds almost - in law we are a very generic and equal society, and if you wish to belong to or align with a group that has more specific beliefs, then that is open to you as well.

Lets jump back to gay marriage here as an example then. If we define state marriage to be “the unity of two human beings, irrespective of their attributes”, then everyone is equal to join with a partner in the eyes of the law, and all such partnerships are afforded the lawful benefits that come with that unity. The church (and indeed, all religions) are also then free to define religious marriage in their doctrine as they wish, so they can say that for them it’s only permissible between a man and a woman. And if you wish to join with a partner following that doctrine, then you have to meet their rules.

In this circumstance, I wonder how much of it is a hangup on the word “marriage”. I can see how the state wants to keep hold of it to describe partnerships between two people, and also that religions want to keep hold of it as they’ve been using it for years and neither wish to yield the word for the other to use. Which possibly means people think solely of this issue as just being an intertwined construct between state and religion, and not as the state giving everyone equality being a separate issue.

evil.rb

Here be hax. Don’t ever do these. ;-)

Reduce local variables with instance_eval

Sometimes (usually in a one-liner) I want to do some work with a value without assigning it to a variable. Chucking an #instance_eval call in there will set self to the value, which saves having to assign it to a local value. Pretty much only used by me in one-off scripts or cli commands.

Good

start_date, end_date = ["24 Dec 2011", "23 Jan 2013"].map {|d| Date.parse(d) }
puts "#{start_date} to #{end_date} is #{(end_date - start_date).to_i} days"

Bad

puts ["24 Dec 2011", "23 Jan 2013"].map {|d| Date.parse(d) }
  .instance_eval { "#{first} to #{last} is #{(last - first).to_i} days" }

See, way less code! cough, cough

Bonus usage: Misdirection

I also dropped some instance_eval on our campfire bot at EmberAds to always blame one person, but without the code reading as such.

%w{Dom Mel Caius CBetta Baz}.sample.instance_eval { "(4V5A8F5T=&$`".unpack("u")[0] }

That does not return one of the array elements as you might think it does from quickly scanning the code…

Set method-local variables in default arguments

You have a method and it takes one argument, which has a default value of nil specified. You then run into the situation where you need to know if nil was passed to the method, or if you’re getting the default value of nil. You could change the default value to something you choose to be the “default value” and unlikely to be passed from elsewhere as the argument’s value, and reset the parameter to nil after checking it, like this:

def output name=:default_value
  if name == :default_value
    name = "caius"
    default = true
  end

  "name: #{name.inspect} -- default: #{default.inspect}"
end

output() # => "name: \"caius\" -- default: true"
output("fred") # => "name: \"fred\" -- default: nil"

That’s quite a lot of code added to the method just to find out if we passed a default value or not. And if we forget to reset the value when it’s :default_value then we end up leaking that into whatever the method does with that value. We also have the problem that one day the program could possibly send that “default value” we’ve chosen as the actual parameter, and we’d blindly change it thinking it was set as the default value, not the passed argument.

Instead we could (ab)use the power of ruby, and have ruby decide to set default = true for us when, and only when, the variable is set to the default value.

def output name=((default=true); "caius")
  "name: #{name.inspect} -- default: #{default.inspect}"
end

output() # => "name: \"caius\" -- default: true"
output("fred") # => "name: \"fred\" -- default: nil"

As you can see, the output is identical. Yet we have no extra code inside the method to figure out if we were given the default value or not. And as a bonus to that, we no longer have to check for a specific value being passed and presume that is actually the default, and not one passed by the program elsewhere.

I posted this one in a gist a while back (to show Avdi it looks like), and people came up with some more insane things to do with it, including returning early, raising errors or even redefining the current method, all from the argument list! I’d suggest going to read them, it’s a mixture of OMG HAHA and OMFG NO WAY WHYY?!?!.

Don’t do this.

Don’t do the above. No really, don’t do them. Unless you’re writing a one-off thing. But seriously, don’t do them. :-D

Some Small Refactorings in Ruby

Here’s a few things I refactor as I write code down initially. Not entirely convinced it’s strictly refactoring, but it’s how I amend from one pattern I see in a line or three of code into a different structure that I feel achieves the same result with cleaner or more concise code.

Multiple equality comparisons

Testing the equality of an object against another is fairly simple, just do foo == "bar". However, I usually try to test against multiple objects in a slightly different way. Your first thought might be that the easiest way is just to chain a series of == with the OR (||) operator.

foo == "bar" || foo == "baz" || foo == :sed || foo == 5

I much prefer to flip it around, think of the objects I’m testing against as a collection (Array), and then ask them if they contain the object I’m checking. And for that, I use Array#include?

    ["bar", "baz", :sed, 5].include?(foo)

(And if you’re only testing against strings, you could use %w(bar baz) as a shortcut to create the array. Here’s more ruby shortcuts.)

Assigning multiple items from a nested hash to variables

Occasionally I find myself needing to be given a hash of a hash of data (most recently, an omniauth auth hash) and assign some values from it to separate variables within my code. Given the following hash, containing a nested hash:

details = {
  uid: "12345",
  info: {
    name: "Caius Durling",
    nickname: "caius",
  },
}

Lets say we want to extract the name and nickname fields from details[:info] hash into their own local variables (or instance variables within a class, more likely.) We should probably handle the case of details[:info] not being a hash, and try not to read from it if that’s the case - so we might end up with something like the following:

name = details[:info] && details[:info][:name]
nickname = details[:info] && details[:info][:nickname]

name # => "Caius Durling"
nickname # => "caius"

And then in the spirit of DRYing up our code, we see there’s duplication in both lines in checking details[:info] exists (not actually that it’s a hash, but hey ho, we rely on upstream to send us nil or a hash.) So we reduce it down using an if statement and give ourselves slightly less to type at the same time.

if (( info = details[:info] ))
  name = info[:name]
  nickname = info[:nickname]
end

name # => "Caius Durling"
nickname # => "caius"

Returning two values conditionally

Sometimes a method will end with a ternary, where depending on a condition it’ll either return one or another value. If this conditional returns true, then the first value is returned. Otherwise it returns the second value. You could quite easily write it out as an if/else longer-form block too.

def my_method
  @blah == foo ? :foo_matches : :no_match
end

My brain finds picking the logic in this apart slightly harder mentally, than if I drop a return early bomb on the method. Then it reads more akin to how I’d think through the logic. Return the first value if this conditional returns true. Otherwise the method returns this second value. I think the second value being on a completely separate line helps me make this mental distinction quicker too.

So I’d write it this way:

def my_method
  return :foo_matches if @blah == foo
  :no_match
end

Returning nil or a value conditionally

Following on from the last snippet, but taking advantage of the ruby runtime a bit more, is when you’re wanting to return a value if a conditional is true, or otherwise false. The easy way is to just write nil in the ternary:

def my_method
  @foo == :bar ? :foo_matches : nil
end

However, we know ruby returns the result of the last expression in the method. And that if a single line conditional isn’t met, it returns nil from the expression. Combining that, we can rewrite the previous example into this:

def my_method
  :foo_matches if @foo == :bar
end

And it will still return nil in the case that @foo doesn’t match :bar.

Returning a boolean

Sometimes you have a method that returns the result of a conditional, but it’s written to return true/false in a conditional instead.

def my_method @foo == :bar ? true : false end

The really easy refactor here is to just remove the ternary and leave the conditional.

def my_method @foo == :bar end

And of course if you were returning false when the conditional evaluates to true, you can either negate the comparison (use != in that example), or negate the entire conditional result by prepending ! to the line.

Why I love DATA

In a ruby script, there’s a keyword __END__ that for a long time I thought just marked anything after it as a comment. So I used to use it to store snippets and notes about the script that weren’t really needed inline. Then one day I stumbled across the DATA constant, and wondered what flaming magic it was.

DATA is in fact an IO object, that you can read from (or anything else you’d do with an IO object). It contains all the content after __END__ in that ruby script file*. (It only exists when the file contains __END__, and for the first file ruby invokes though. See footnote for more details.)

How can we use this, and why indeed do I love this fickle constant? I mostly use it for quick scripts where I need to process text data, rather than piping to STDIN.

Given a list of URLs that I want to open in my web browser and look at, I could do the following for instance:

DATA.each_line.map(&:chomp).each do |url|
  `open "#{url}"`
end

__END__
http://google.com/
http://yahoo.com/

which upon running (on a mac) would open all the URLs listed in DATA in my default web browser. (For bonus points, use Launchy for cross-platform compatibility.) Really handy & quick/simple when you’ve got 500+ URLs to open at once to go through. (I once had a job that required me to do this daily. Fun.)

Or given a bunch of CSV data that you just want one column for, you could reach for cut or awk in the terminal, but ruby has a really good CSV library which I trust and know how to use already. Why not just use that & DATA to pull out the field you want?

require "csv"

CSV.parse(DATA, headers: true).each do |row|
  puts row["kName"]
end

__END__
kId,kName,kURL
1,Google UK,http://google.co.uk
2,"Yahoo, UK",http://yahoo.co.uk

# >> Google UK
# >> Yahoo, UK

I find when the data I want to munge is already in my clipboard, and I can run ruby scripts directly from text editors without having to save a file, it saves having to write the data out to a file, have ruby read it back in, etc just to do something with the data. I can just write the script reading from DATA, paste the data in and run it. Which also lets me run it iteratively and build up a slightly more complex script that I don’t want to keep. Then do what I need with the output and close the file without saving it.

* technically DATA is an IO handler to read __FILE__, which has been wound forward to the start of the first line after __END__ in the file. And it only exists for the first ruby file to be invoked by the interpreter.

$ cat > tmp/data.rb <<RB
p DATA.read
__END__
data.rb
RB

$ ruby tmp/data.rb
"data.rb\n"

$ cat > tmp/data-require.rb <<RB
require "./tmp/data"
RB

$ ruby tmp/data-require.rb
/Users/caius/tmp/data.rb:1:in `<top (required)>': uninitialized constant DATA (NameError)

And because it’s a handle to __FILE__ though, you can rewind it and read the entire ruby script into itself…

$ ruby tmp/readself.rb 
DATA.rewind
print DATA.read

__END__
something goes here