Tech Book: Effective Python, Brett Slatkin

I’ve been learning Python for a few months and am starting to use it at work, so I thought it was about time to read a book about Python. This book has been excellent. No only does it follow format of the time-honoured ‘Effective’ series pioneered by Scott Meyers, it also features practical, useful code examples. In particular, his JsonMixin class was immediately relevant to some work I’ve been doing to generically serialise to/from JSON documents – see Item 26 “Use Multiple Inheritance Only for Mix-In Utility Classes”.

The author has also taken the time to record hours of video lessons for Safari Online subscribers, so you can view additional material as he works through the items in the book.

Leave a comment

Filed under Python, Tech Book

How to draw a triangle in Apple Watch

I’ve previously covered how to draw circles and rectangles into an image when writing an Apple Watch app. I had an idea for another watch face that needed triangles – these need a different approach using Watch Kit. Basically, you have to draw a path around the perimeter of the triangle (or any other shape), then fill in the shape. Here’s a function to draw a triangle that points to the left:

    internal func drawTriangle( _ context : CGContext?, centreX : CGFloat, centreY : CGFloat, size : CGFloat, colour : CGColor )
    {
        context?.beginPath()
        context?.move(to: CGPoint(x: centreX - size/2.0, y: centreY))
        context?.addLine(to: CGPoint(x: centreX + size/2.0, y: centreY - size/2.0))
        context?.addLine(to: CGPoint(x: centreX + size/2.0, y: centreY + size/2.0))
        context?.closePath()
        
        context?.setFillColor(colour)
        context?.fillPath()
    }

And this is the code for drawing a rectangle:

    internal func drawRectangle( _ context : CGContext?, centreX : CGFloat, centreY : CGFloat, width : CGFloat, height : CGFloat, colour : CGColor )
    {
        let origin = CGPoint( x: centreX - width/2.0, y : centreY - height/2.0 )
        let rect = CGRect( origin : origin, size : CGSize(width: width, height: height) )
        
        context?.setFillColor(colour)
        context?.fill(rect)
    }

Once you can do those primitive triangle/rectangle operations, you can put them together to render any digit you like. So I used them to draw a ‘timeometer’ in this speedo watch face:

The dial is rendered as a series of ticks – at the moment, it shows minutes and hours. I have to admit I still tend to read the time from the digits at the bottom, so I may change the dial to show seconds and minutes instead.

Leave a comment

Filed under Programming, Swift

Book Review: Night School, Lee Child

For me, there’s a lot of suspense before I read a Jack Reacher thriller. A recent tradition is that Lee Child is interviewed by Phil Williamson Radio 5Live, discusses the book that’s just been published, and reveals the first line of the next book. So in September 2015, we knew the title was Night School and the first line would be: “In the morning they gave Reacher a medal, and in the afternoon they sent him back to school”. And in September 2016, he talked more about the plot. Then I received a lovely hardback edition of the book for Christmas and finally picked it up to read a week ago.  A long build-up, plenty of suspense – would the book be up to the usual standard?

Yes, of course it is.  It’s a flashback to the 1990’s, the days that Reacher was still in the army, at the top of his game, sent on a special investigation to find and destroy a terrorist cell in Germany.  The book features the enigmatic Frances Neagley as well, his top sergeant from the 110th Military Police.  It has all the hallmarks of a classic Jack Reacher thriller, even cheekily putting the standard description of him as “six feet five and two hundred fifty pounds”, even though Tom Cruise is probably picturing himself playing the role in the next movie as  I write this.  The book starts with the premise of an overheard conversation: “The American wants 100 million dollars” – Lee Child doesn’t disappoint.

Here’s the first line of the next book, which carries on from Make Me: “Jack Reacher and Michelle Chang spent three days in Milwaukee.  On the fourth morning, she was gone.”

Leave a comment

Filed under Book Review

Book Review: Con Law, Mark Gimenez

I’ve read several books by Mark Gimenez before and really enjoyed them, so I was surprised to look back and see that I hadn’t read one for over 2 years! Gimenez’ best work are the novels featuring A. Scott Fenney, but in this novel he introduces a new character, John Bookman (known as ‘Book’).

By profession, Book is a professor of constitutional law – he is apparently sort after for his views on media shows and has published widely. Yet, as well as being a celebrity by today’s standards, he is also known for pursuing legal cases on a pro-bono basis, often getting himself and his interns into trouble (they get to come along for the ride, literally, on his Harley). And in another quirk of fate, Book can look after himself – he’s highly proficient in Tae Kwon Do.

Although I enjoyed this book, I didn’t buy into the main character as much as other characters imagined by Gimenez. Book has many similarities to Lee Child’s Jack Reacher – including the womanising, the fights, the investigations and the maverick attitude. I’d rather read Jack Reacher any day – and the latest thriller, Night School, is next on my reading list.

Four stars

Leave a comment

Filed under Book Review

How to switch watch faces using swipe gestures

A welcome addition to WatchKit 3.0 is the swipe gesture recognizer.  Previously, I used an ordinary button to switch between modes in my Watch Face app, but now I can mimic the behaviour of official watch faces by swiping left or right.

The change is quite simple to make too. First, you just need a Group control that contains an image (into which you’ll draw the watch face). Then, you drag a couple of Swipe Gesture Recognizers into the group, and change the properties so that one is a left swipe and the other is a right swipe.

Having done that, you need to insert an action for each of the gestures – you can do that by control-dragging from the gesture in the storyboard outline into the InterfaceController code. Make sure to add an action (rather than an outlet) – that way, Xcode will create a stub method for you with the correct signature.

The logic for the swipe gesture just switches between watch faces then re-draws the time:

    // Tissot --> Hermes --> Roman
    @IBAction func swipeRight(_ sender: Any) {
        switch (watchFace.id())
        {
        case WatchFaceId.tissot: watchFace = HermesWatchFace()
        case WatchFaceId.hermes: watchFace = RomanWatchFace()
        case WatchFaceId.roman: watchFace = TissotWatchFace()
        }
        
        drawTime() // refresh with updated background & different styles
    }

and the left swipe reverses the transition order.

See also this earlier post that explains how you can draw directly into an image in WatchKit – combined with the swipe gesture recogniser, it provides a neat way to switch between different modes in any app.

Leave a comment

Filed under Swift

C++ London Meetup: Dependency Injection and Clang Tooling

meetup-c-londonPhil Nash organised another C++ London meet-up at SkillsMatter last week. The first talk was by Pete Goldsborough, who gave a rapid overview of the Clang tooling libraries. The second talk was by Kris Jusiak, who talked through the motivation and usage of his Boost::DI dependency injection library. This was more relevant to my work because Kris’s example showed how Boost.DI aims to reduce the overhead in setting up test scenarios for GTest/GMock. I’ve been pretty happy with the way my unit tests look so far, but next time I’ll definitely look at whether his injector object could simplify my code.

Leave a comment

Filed under Meetup

How to prevent F# union case names leaking into parent scope

Suppose you are writing some F# code to model the workings of a coffee shop. You might start by defining a small choice of snacks:

type Cost = int

type Muffin =
| RaspberryAndWhiteChocolate of Cost
| Blueberry of Cost
                          
[<EntryPoint>]
let main argv = 
    // No need for "Muffin." qualifier on Blueberry
    let muffin = Blueberry 250 

    printfn "%A" muffin
    0

This compiles and runs just fine – notice that there’s no requirement to prefix the union case “Blueberry” with the type name “Muffin”. All is well.

However, suppose you then proceed to define some more types for coffee:

              
type Milk =
| Skimmed
| Whole
| SemiSkimmed

type Modifier =
| Milk of Milk
| Cream
| None   // <--- Oops, clashes with FSharpOption.None
             
type Coffee =
| Filter of Modifier
| Cappuccino
| Latte

[<EntryPoint>]
let main argv = 

    let muffin = Blueberry 250

    let coffee = Filter( None )

    printfn "%A %A" muffin coffee
    0

This still compiles and runs – but there’s a lurking problem. As soon as you add the use of optional values, the program fails to compile. For example, you might offer free coffee as a promotion, and model the cost as optional:

    let coffee = Filter( None )
    let cost : int option = None

compileerror
The problem is that None is now used as both a union case in Modifier and a union case in FSharpOption.

Whilst you could choose to workaround this by changing the “None” union case in Modifier to “Nothing”, you may not have that flexibility. Instead, you can use the RequireQualifiedAccess attribute on the Modifier type to stop union case names leaking into the surrounding scope:

[<RequireQualifiedAccess>]
type Modifier =
| Milk of Milk
| Cream
| None 

[<EntryPoint>]
let main argv = 
    let muffin = Blueberry 250 // still no qualifier required
    let coffee = Filter( Modifier.None ) // now requires qualifier
    let cost : double option = None // ok, uses FSharpOption.None

    printfn "%A %A %A" muffin coffee cost
    0

Leave a comment

Filed under F#