Archive for the 'Creations' Category

Much faster

Saturday, October 15th, 2011

I’ve just pushed a couple of improvements to my ISO 8601 date formatter. Previously, it was pathetically slow compared to C standard library parsing and unparsing; now, it is faster.

Timing ISO8601DateFormatter
Time taken: 0.130194 seconds
Number of dates and strings computed: 10000 each
Time taken per date: 0.000013 seconds
Timing C standard library parsing and unparsing
Time taken: 0.192645 seconds
Number of dates and strings computed: 10000 each
Time taken per date: 0.000019 seconds

You’ll want at least revision [61d2959c6921] or later.

My thanks to Sam Soffes and Rudy Richter for alerting me to the speed problem.

Edited at 16:35. Previously, it was almost as fast as C stdlib. Now it is faster.

Desktop picture: Yawning Void

Thursday, September 15th, 2011

This is a desktop picture for Macs running at 1366 by 768, such as the 11-inch MacBook Air:

Yawning void

No, it’s not pure black. Yes, that bar at the top is part of it.

It’s meant to be used at that resolution and no other, with menu-bar translucency turned on. Scaling it, especially vertically, will make it look wrong.

If you want to adapt it to a different size, here’s the original document, editable in Lineform. You should scale the document and the background to the desired screen size, and the menu-bar background to the desired width.

SD card sleeve

Sunday, July 10th, 2011

If you have an SD card without a case, you may find this handy.

Front of sleeve, labeled.
The back of the SD card sleeve, closed.
The back of the SD card sleeve, open, showing the card inside.

File: SD-card-sleeve.pdf

A PDF file from which you can print out nine sleeves per US Letter sheet. Make sure you print at 100% scale.

Assembly instructions

  1. Cut out a sleeve along the thick lines.
  2. Place the card in the center of the sleeve so that it is outlined by the thin lines.
  3. Fold the bottom (rectangular flap) over first.
  4. Fold the side flaps over.
  5. Secure the bottom and side flaps with one square piece of three-quarter-inch Scotch tape.
  6. Fold the top flap over and inside.
  7. Flip the sleeve over and label it on the seamless side.

Helping people

Saturday, November 6th, 2010

There’s a recurring theme I keep seeing in questions on Stack Overflow.

I’ve said those words a few times now. I’ve said it twice at my recognizing-Cocoa-bugs presentation, which I’ve given at one CocoaHeads and at the MacTech Conference (just concluded yesterday). I’ve also said it a few other times at CocoaHeads, usually in preface to explaining something that’s both germane to the current conversation and the common source of confusion in the questions I’m then referring to. Plus, I’ve said it a couple of times in posts here.

In the concluding session of the conference, Edward Marczak, MacTech’s executive editor, cited a number of tweets related to various cool things that happened in the past few days. One of them was from me, inviting attendees to flag me down for one of my useful-Cocoa-links cards, which I’d previously offered up to audience members in my session. He told the audience how cool he thought it was that I’d thought ahead and made those cards.

The reason I’d made those cards was because I’d identified a pattern. In my answers on Stack Overflow, I often cite one or more of a few key documents:

or tell the questioner to listen to or turn on some warning or other and link to my warnings blog post as part of that.

My introductory document for Cocoa and Cocoa Touch, in its own introduction, identifies a similar genesis: Everything on that page is something I’d had to explain to multiple people on Stack Overflow, so I decided to put it all in one place for easy linking (by me) and easy reading (by new Cocoa or Cocoa Touch programmers). That document is also among the links on the card.

Each of the things I got praised for in that concluding session, and thanked for (besides Growl, which is mostly a lot of other people’s work) outside of sessions, I made because I’d identified a need by spotting a pattern.

There’s no reason you can’t do this, too. What have you done multiple times lately? Especially, what have you done or made or found for other people multiple times?

Somewhere on Eric Raymond’s site, there’s an explanation of the difference between newbies and wizards. It’s not that the wizards know all that much more than the newbies (though they often do have a stronger/deeper conceptual understanding); asked for the name of a function, say, the wizard will probably not know it exactly (unless it is very simple, such as CFRetain, or one they use very frequently, such as CFRetain).

The difference between them is that the wizard knows where to look stuff up. I sometimes refer to this as “swapping things in”, the analogy being virtual memory: I remember very little at any given moment, precisely because I know where I can get it from when I need to get it back into my mental working set.

The wizard knows how to help themself.

How can you enable people to help themselves?


Here’s that card, if you want one.

NaNoDrawMo ten-minute challenge

Saturday, October 30th, 2010

Last year, a lot of us who attempted NaNoDrawMo, Steven Frank’s 50-drawings-in-one-month challenge, failed to meet the 50-drawing goal. I think I came up with 30… ish.

The problem is that drawing something takes so damned long that it’s hard to find time to do it.

Solution: Make it take less time!

I propose the following self-enforced constraint: Pick a subject, then draw as much of it as you can in ten minutes.

This should train us through trade-offs to realize which parts of the drawing are most important to communicating what it’s supposed to be. I won’t mind if you draw the same things multiple times in order to get it down—I’m sure I will.

In order to help you follow this ten-minute limit, I’ve created a timer. Start the timer, then start your drawing. When the bell rings, you’re done—scan it (if appropriate) and upload it to the group.

(Aside: The bell doesn’t work in MobileSafari. Anyone know how to fix it?)

I hope this will help each of us achieve a higher success rate in this year’s NaNoDrawMo.

Ship-It Saturday: PRHEmptySingleton repository

Saturday, September 4th, 2010

The singleton-done-right example from my article on the subject is now in a Mercurial repository on Bitbucket. The repository includes not only the class (which I’ve put in the public domain), but also a test suite for some of the test cases listed in the post.

There are some adventurous testing techniques at work here.

First, since we don’t want multiple test runs to use the same singleton instance, the test cases actually run in subprocesses. Each test method is prefaced with this code:

if (!isInSubprocess) {
    [self runTestInSubprocess:_cmd];
    return;
}

That method calls fork.

In the child process, the test case sets isInSubprocess to YES, then tells itself to perform that selector; this gets execution back to the test method, which checks the variable again, finds that it’s true this time, and continues on with the test.

The parent process calls waitpid and checks the result; if the child failed, the parent propagates the failure. If the child crashed (got a signal), the parent raises the same signal; if the child simply exited abnormally, then the parent exits with the same status.

Second, there’s test case #6:

  • If [super init] returns a different object, alloc/init won’t break.

That one is hard to test, because PRHEmptySingleton’s superclass is NSObject, and -[NSObject init] doesn’t return a different object. (Not in any version of Foundation I’ve ever encountered, anyway.)

So, the first step is to create an intermediate class that does return a different object. But that doesn’t help as long as PRHEmptySingleton is still a direct subclass of NSObject.

The simple solution would be to just change PRHEmptySingleton’s superclass, but that reduces the purity of the testing: A test should be able to work without modifying the code under test, and any changes to the code under test should be permanent changes that aren’t only to enable the test; you should be able to explain the changes as if the test case did not exist.

So what I did was to import everything in my prefix header, even more than I usually do, and then import my intermediate class’s header, and then use the preprocessor to ensure that any direct subclasses of NSObject declared elsewhere are declared as subclasses of the intermediate class. Thus, the prefix header causes PRHEmptySingleton to be a subclass of the intermediate class with no changes to PRHEmptySingleton’s header. It’s a bit of a hack, and doing this sort of thing could potentially cause problems in a larger program or test suite, but in this context, it works.

With that, five of the six test cases in the original post are now covered (I’m not sure how to cover #3 without changing PRHEmptySingleton.[hm]), and the code is under version control, so you can subscribe to and track changes.

Please use singletons responsibly.

Portable centimetric measuring tape

Saturday, August 14th, 2010

This is a roll-up measuring tape that tucks neatly into my wallet, mostly so that I can compare sizes of products in the store without having to buy them or go find a ruler.

File: Centimetric_Ruler-portable.pdf

A US Letter page containing the ruler (20 cm long) and a specification for the cardboard handle you glue the ruler to.

Photos:

Photo of the portable centimetric measuring tape, rolled up, sitting on a table.

Photo of the portable centimetric measuring tape, with 6 cm unrolled, sitting on a table.

In case you’re wondering about the pattern of the mm markings, I borrowed it from this New Zealand ruler that Dave posted about.

If I were to assemble this again, I would glue the “tape” to the other end of the handle, so that I can unroll the tape from left to right using my right hand. If you’re left-handed, you might prefer to assemble yours the same way I did assemble mine.

My homemade A7 notebook

Monday, July 19th, 2010

I wanted a Moleskine Volant, but I didn’t want to pay $3 each for them.

So I made my own notebook instead. It’s A7, which is just a little wider than the Volants I’d been looking at.

Overall shot of the notebook.

I’d initially lettered the cover (to distinguish front from back) by hand, but wanted to make it a little more professional, so I bought a Fiskars Ultra ShapeXpress shape-cutter. Here’s a video showing it in action. I printed out a template of the cover text, cut it out, and filled it in with my pen.

The notebook is ruled, and I keep a Zebra TS-3 mechanical pencil clipped into it.

Photo of me holding it open.

Here’s the PDF of the rulings. I printed it double-sided onto regular copy paper. Obviously, I made it for US Letter, but it would be no different for A4, because each section is a little larger than A7, for reasons that will become clear in a moment.

Once printed, I cut the sections out with a paper-trimmer, then used a “medium” rounded corner punch, bought at Target in their scrapbooking section, to round off the corners (square corners will bunch up).

The cover is scrap cardboard from one of my T-shirt packs, cut to size using scissors (plus a ruler and pencil to mark where to cut) and rounded off with the same punch.

The binding is simple enough: Two staples in the spine of the book. This is why the sections I cut out are slightly larger than A7: Each page is A7, but I included a 5 mm gap between pages for the staples to go in. (This matters more for the outer sheets than for the inner ones.) If I were to leave out this gap, or shrink each notebook page by 2.5 mm to compensate, it would be possible to get four notebook sheets instead of three from an A4 sheet.

With this, I have a pocket-size notebook that’s very inexpensive (being made from materials I have anyway), recyclable, and customizable to my taste. For a future notebook, I might make it with half ruled pages and half plain pages.

Centimetric ruler/measuring tape

Saturday, July 3rd, 2010

One mistake a lot of people make when trying to learn the metric system is trying to memorize and use conversion factors. Do you think people in other countries measure everything in inches and then convert to centimeters?

No, they have measuring tapes and rulers in centimeters or millimeters. Such rulers are easy to come by here in the US, but the measuring tapes are not.

So, in order to solve that problem and make it easier for fellow Americans to measure lengths in metric units, I present my Centimetric Ruler. It totals 2.5 meters, and looks like this:

Tick marks every 1 mm, with numbers over centimeter marks.

Despite the name, I use it as a measuring tape, coiled up and held in that shape (when not in use) by a small rubber band.

The page is US Letter (because that’s the paper I have), and you’ll need to cut out the pieces and tape them together. I recommend cutting through the tick marks so that there is no gap between them and the bottom of the “tape”.

Note that every 25th centimeter appears twice in the printout. This is to give you one centimeter in which to lay each segment over the previous/next one.

There’s nothing I can do for you for measuring mass (but scales that measure in grams are easy to come by; you can buy a digital one at Target for $20), but volume is easy, and demonstrates the elegance of the metric system pretty well:

  1. A liter is equal to the volume of a cube that is 1 decimeter (= ¹⁄₁₀ meter = 10 cm) to a side. That volume is 1 dm × 1 dm × 1 dm, or 1 dm³—one cubic decimeter.
  2. ¹⁄₁₀ of a decimeter is one centimeter (¹⁄₁₀₀ of a meter).
  3. Imagine, or construct, a cube one decimeter to a side. Starting from one corner, make a cut in each edge, one-tenth of the way from the corner. This will produce a cube that is one centimeter to a side—one cubic centimeter.
  4. Note that this cube is ¹⁄₁₀ of the larger cube in each dimension, which means its volume is (¹⁄₁₀ × ¹⁄₁₀ × ¹⁄₁₀) = ¹⁄₁₀₀₀ of the volume of the larger cube.
  5. The volume of the larger cube being one liter, the volume of the smaller cube is ¹⁄₁₀₀₀ of that. ¹⁄₁₀₀₀ of a liter. One milliliter.
  6. QED: One cubic centimeter (1 cc) = one milliliter (1 ml).

Knowing how volume and length relate to each other in metric, you can use the measuring tape (most easily on cuboid objects) to measure volume as well.

Non-obvious solutions

Sunday, May 9th, 2010

I’ve started a site cataloging non-obvious, simple, superior ways of performing everyday tasks.

The visual theme is Fluid by Andrew Wilkinson, with a custom background image I made in Pixelmator:

Feel free to use that image on your own site.

Capture Cursor

Saturday, March 13th, 2010

Most people don’t know how to get the cursor that’s currently on the screen—a useful ability, especially if you’re writing screenshot or screen-recording software. I’ve written an app that demonstrates the technique, or at least tries to.

It’s a bit flaky. The API it uses, IOFramebuffer, doesn’t tell me how many frames there are or what format they’re in, so the app assumes ARGB in native byte-order and doesn’t worry about frames. This gives wrong results more of the time than I like.

I’ve filed a request for a higher-level API, which would make the task much easier and the app much shorter.

I’ve posted a build in the repository’s downloads area, in case you’d like to see it in action. If you want to build it yourself, you’ll need to download SGHotKeysLib and put the source where the Capture Cursor Xcode project expects it to be.

UPDATE 2010-08-28: I’ve pushed a change, [9cbec7dd5169], that deletes the IOFramebuffer-based category method and uses Snow Leopard’s new, far more reliable [NSCursor currentSystemCursor] instead. I suggest you do the same.

Easy main-thread performing category

Saturday, February 13th, 2010

Anyone who’s ever had to perform a message on the main thread knows how ugly the code can be:

[obj performSelectorOnMainThread:@selector(receiveAnswer:)
                      withObject:[NSNumber numberWithUnsignedInteger:42]
                   waitUntilDone:NO];

I’ve written a category that changes the above code to something much simpler:

[[obj performOnMainThread_PRH] receiveAnswer:42];

Notice that not only is the code much easier to read and to write, but you no longer need to box and unbox primitive values.

You can get the code, under a BSD license, from the higher-order main-thread perform repository.

Back when I originally mentioned my creation of the category on Twitter, Dave Dribin replied that he had already written one of his own. His is part of his DDFoundation framework, and requires DDInvocationGrabber (a fork of Jonathan Wight‘s CInvocationGrabber), also part of that framework.

My category requires nothing but Cocoa and is not part of a larger framework. That said, it’s interesting to read in his code how the functionality of the Invocation Grabber makes his implementation nothing but a thin wrapper around it. (Also, his version lets you say waitUntilDone:YES.)

Nearest Neighbor Image Unit

Saturday, February 6th, 2010

I originally wrote this as an application using NSImage (with NSImageInterpolationNone), but decided to rewrite it as an Image Unit. So, here it is.

An introduction to Cocoa and Cocoa Touch

Wednesday, February 3rd, 2010

If you know someone who’s recently taken up programming the Mac or the iPhone (or both), please give them one (or both) of these links:

As a frequent answerer of questions on Stack Overflow, I see certain patterns—not just frequently-asked questions, but also frequently-unasked questions: Things that are biting the questioner that they don’t know about.

Sometimes they’re thinking about things the wrong way (e.g., using property list objects where they should have a model). Sometimes there is a route to a solution (“my app is slow” “run Instruments”), but they don’t know about that route. Often, they’ll use wrong terms that are right on another platform (like “member variable”), like a speaker using their native language’s pronunciation rules when speaking a foreign one.

To help people over these speed bumps, I’ve composed an introduction for new Cocoa and Cocoa Touch programmers. (Both of the above links redirect to it.)

If any part of it doesn’t help them (i.e., is unclear or wrong), I’d appreciate it if you’d let me know, either here or by email.

Ship-It Saturday: Shorten URLs service

Saturday, January 30th, 2010

When posting links on Twitter, your Twitter client will automatically shorten the URLs to make them fit.

There are many, many general shorteners, including TinyURL, Notlong, Metamark, and Bit.ly. One of the complaints about these is that they hide the true destination of the link: From the URL alone, you don’t know whether you’re going to be educated, RickRolled, or worse. (TinyURL and Bit.ly both offer a way to preview the link, but that’s not as easy as just looking at the URL.)

To help with this, several non-shortening-related websites have added their own shorteners that use their own domains, particularly for use on their official Twitter accounts or with a built-in post-to-Twitter feature.

The problem is that it’s not always easy to tell what the shortened link will be. Flickr is among the most difficult: Their regular links use decimal numbers, but their shortened links use base-58, which is not a trivial conversion to perform in any programming environment I know how to use. (Not so easy as, say, decimal to octal.) It’s certainly doable, but would require extensive tests to verify that your base-58 numbers match Flickr’s. There’s sample code, but it’s in PHP, so if you’re writing in anything else, that means porting it, which means (again) extensive tests.

So, rather than write my own shortener, it’s much easier to just use Flickr’s: curl the canonical long URL, then scrape the short one out of the body. (Yay for <link rev="canonical">!) I wrote a service to do this.

For Ship-It Saturday, I retooled it. No longer is it just a Flickr shortening service: It now handles YouTube, Amazon, and a few other sites as well. A single service invocation shortens all links to websites that have their own shorteners.

So, here you go: The Shorten URLs service.

finder, a command-line tool

Sunday, January 24th, 2010

Today’s Ship-It Saturday is a command-line interface to the Finder.

The two most useful commands are:

  • finder reveal file, which will select the file in a Finder window, and
  • finder update (or updated) file, which will tell the Finder that the file has been updated.

The latter command probably is not too useful anymore, but the command-line tool should work on no less than 10.4, and could probably be recompiled for even older versions of Mac OS X, so you may still have a use for it.

CocoaHeads Lake Forest videos

Monday, January 18th, 2010

It’s been in editing for over a month, but now, it’s finally done. I’ve just uploaded the second part of last month’s meeting of CocoaHeads Lake Forest. There’s one more to go from last month, and then I can start posting the video from this month.

This one’s a lot more random than the first one. Portions of my own presentation are only part of what you’ll see in this video.

More long-term, I’ve created a channel on Vimeo for all past and future CocoaHeads LF videos.

Pointers tutorial 1.3

Saturday, January 16th, 2010

At long last, a new version of Everything you need to know about pointers.

The most significant changes are long-overdue corrections regarding declarations of const pointers and the difference between arrays and pointers. You can—and, if you learned how to work with pointers from this tutorial, should—read all of the changes in the delta between 1.2 and 1.3.

Application Locator

Friday, January 8th, 2010

This is a little one, inspired by a Growl discussion list thread. Enter the bundle identifier or name of an application, and Application Locator will reveal it in the Finder.

Translate Text 1.0.1

Tuesday, January 5th, 2010

The new version adds a Sparkle public key, which should fix updating. Since updating was broken in all versions before 1.0.1, you’ll need to update manually from the Translate Text web page.