Author Archive

iWork ’09 and .docx files

February 24, 2015

If you happen to rebuild a mac and put 10.9.5 on it and you install iWork ’09 from an older CD/DVD so you get iWork 9.0, you will find that you cannot open .docx files.

Going to the AppStore is fruitless – just wants to get you to update to the current versions of Pages (the rewrite) and then tells you that you have an incompatible system (requires OS X 10.10 or later).  It doesn’t offer to update you to the updates for iWork ’09 that you may have been offered back when you first installed iWork and before the new iWork apps came out.

The solution is to get the updater from Apple’s Support area (search for “iWork 09 update”).  Here’s a link to the newest we found (9.3).

Dad’s dad just recalled a prank I (apparently) did at a young age…

December 19, 2014

Funny to have Dad’s dad talk about stepping on Legos and then recall this other event which I swear I don’t remember doing, but I would have been younger than 7 when this is purported to have happened:

Then there was the Sat morning when I heard massive giggles from the hall,
went out to see and slipped on the Crisco-greased floor one (or both) of you
had so much fun creating…  :-)

It is amazing I survived you kids!

Gladdens my heart to hear I (with help & encouragement from my nearest sister I’m sure) was keeping him on is toes* at such a young age…  :-P

Geek was so much more well behaved than I, sadly.  I have no recollection of him playing such pranks (though the empty milk carton put back into the fridge was pretty funny).

*or perhaps “off his toes” would be more accurate…

Fix for spinning Pizza in Finder (10.9.5): remove dropbox contextual menus

November 7, 2014

Got  really tired for seeing the SPOD (Spinning Pizza of Death) in the Finder while trying to navigate in the folder hierarchy.  Happens off and on every 30 seconds or so.  Finally tracked it down to something dumb that Dropbox’s contextual menu code is doing (version 2.10.41).

It’s a bit of a pain to remove but here’s what you need to know:

/Library/DropboxHelperTools/

is where the nasty is.  Contents:

DropboxHelperInstaller
Dropbox_u###/
DropboxBundle.bundle
FinderLoadBundle
mach_inject_bundle_stub.bundle
dbfseventsd

The “###” is the user id number of the current OS X user (probably 501, 502, etc).

You need to move the “DropboxHelperInstaller” out of this folder or it’ll just keep re-installing the other stuff. I didn’t track down which of the two bundles are causing the problem, but it’s one of the “FinderLoadBundle”, or “DropboxBundle.bundle”. I removed both of these and the “mach_inject_bundle_stub.bundle” and that seems to solve the problem (after you quit Dropbox and relaunch the Finder).

Unfortunately Dropbox really wants to repair itself so it will keep prompting you every time it launches to put these back:

Screen Shot 2014-11-07 at 7.44.40 PM

Just select “Cancel” and it won’t be able to put these buggy files back.  Everything except the Finder integration seems to work fine and the Finder doesn’t keep dying inside dropbox contextual menu code for some indeterminate (but too long) amount of time.  I’ve told them on Twitter but they haven’t fixed this yet :-/

UPDATE:  As of Dropbox v2.10.52, and only when running on OS X 10.10.1, there’s a checkbox for “Enable Finder Integration” that might turn this stuff off more easily.  I haven’t tried it yet, but I’m hopeful.

Objective C Builder Pattern play

April 12, 2014

So I read two posts on the Builder Pattern from Java today that got linked to off of Twitter.

This by Klaas Pieter which referenced this one by Uli Kusterer.  Both good articles.

I haven’t done Java much at all for the last 10 years and so am not used to this pattern, but I thought about how I might do something similar and while I’m not sure my first thought is any better, it seems to meet the requirements and/or benefits noted by the two blog posts in question and the tweet discussion referencing them.

Instead of:

 Pizza pizza = new Pizza.Builder()
     .size(12)
     .pepperoni(true)
     .mushrooms(true)
     .build();

(from Uli’s post), or

  Image* theImage =
    (new Image.Builder)->SetWidth(100)
    ->SetHeight(80)->SetDepth(8)->Build();

(from Klaas’ post)

I tried something like:

Foo * aFoo = [Foo fooWithData: @{
     @"width" : @21, @"height" : @22 }];

Here’s one way to implement that – there are multiple, clearly
(pardon the formatting, trying to fit into our narrow blog them is annoying):

// .h file
#import <Foundation/Foundation.h>

@interface Foo : NSObject

+ (instancetype) fooWithData: (NSDictionary*) initParams;

@end

// .m file
@interface Foo ()
@property (nonatomic, assign) long width;
@property (nonatomic, assign) long height;
@property (nonatomic, assign) long depth;
@end

@implementation Foo

+ (instancetype) fooWithData: (NSDictionary*) initParams
{
  Foo *result = [[Foo alloc] init];

  // If one uses setValue:forKey: in a loop as
  // as Uli notes then we can't support integral
  // properties like ints.
  // Also doing it explicitly as below
  // means we don't have to have the same name
  // for our private internal properties as we
  // document for our public parameters because
  // we can map them here.
  // e.g.,
  //  result.imageWidth = [initParams[@"width"] longValue];

  if ( initParams[@"width"] != nil )
    result.width = [initParams[@"width"] longValue];

  if ( initParams[@"height"] != nil )
    result.height = [initParams[@"height"] longValue];

  if ( initParams[@"depth"] != nil )
    result.depth = [initParams[@"depth"] longValue];

  return result;
}

- (instancetype) init
{
  self = [super init];
  if ( self )
  {
    // init with defaults
    _width = 10;
    _height = 10;
    _depth = 1;
  }
  return self;
}

- (NSString*) description
{
  return [NSString stringWithFormat:
           @"Foo: (%p), width: %ld, height: %ld, depth: %ld",
           self, self.width, self.height, self.depth];
}
@end

// main.m
#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
  @autoreleasepool {
      // note no depth specified, taking default of 1
    Foo * aFoo =
      [Foo fooWithData: @{ @"width" : @21, @"height" : @22 }];
    NSLog(@"aFoo: %@", aFoo );
  }
}

Paste the above into CodeRunner and run it and you get:

2014-04-12 16:22:38.918 Untitled 7[71144:707]
aFoo: Foo: (0x7f8842c0af00), width: 21, height: 22, depth: 1

In the above I only typed in the class method as taking the full parameter list but normally I would have made the init method take the same parameter and do the initialization & mapping there. Something I’d likely add if I was going to actually use this, which I’m not likely to. Why not? Because to use the construct above you’d have to document the parameter keys available to use in the dictionary and what type of value each takes. This is where ObjectiveC’s named parameters comes in handy: they are self documenting.

Anyway, an interesting procrastination from what I was supposed to be doing this Saturday afternoon… :-)

I think Craig is right on track with his wearables & Apple

March 13, 2014

I think Craig Hockenberry @chockenberry is right on track with his Wearing Apple post.

I’ve been thinking and talking about a “personal secure network” among a collection of devices you are wearing or carrying for a while now and it seems like a no-brainer to me.  Seems totally silly to put all the battery, radios, antennas, storage and whatnot in a single device (google glass for example).

You need less battery in what I call the ‘motes’ if the LTE/WiFi radios and antennas are in the ‘core’ (“hub” in Craig’s post). What are ‘motes’ ? Think rings, earrings, necklace, bracelet, phone in pocket, flexible battery in belt, piezo generator in shoes, motion generator in umbrella/walking stick, bluetooth earpiece, display in glasses and/or contacts, high performance computing cube in our backpack, and sure, even a watch :)

What’s the problem with this vision? Lots really :)  Charging all these devices will be a pain.  Clearly you need something like a flat pad you set ‘motes’ on while you sleep and they charge inductively.  Better yet would be if they had small energy harvester chips with fractal antennas that harvested ambient energy (microwaves, cellular signals, AM, FM, etc) to extend their battery life.  Oh, yah, better batteries would be a big win and this may not get cool until that happens.

Want to get even more “out there?” Check this out:  Sugar-powered biobattery has 10 times the energy storage of lithium.  Pretty cool but one of the implications of this might be devices that could be powered from our body’s internal processes directly.  So to charge your devices you just eat more.  Be a boon for obesity.  Need to lose weight? Play more flappy birds!  :-P

This then lets us surgically implant devices so you don’t have to worry about forgetting it at home.  You may think I’m being silly, but the convenience will win people over.  Also, note the long-time existence and surgical implantation of pacemakers & defibrillators.  Then look at how common tattoos and body piercing are in youth today (in parts of the USA anyway).  We are not that far from this.

Ok Geek’s hungry so leaving it at this quick “jot this down” for now.

Brother® stops & refuses to print. Annoying! So I hack their TN-360 toner cartridges to get all the toner in them.

March 2, 2014

I purchased a Brother® MFC-7840w multifunction laser printer some years ago and I have to say that it’s one of the better modern printers I’ve owned.  Mac OS X software for it isn’t great (buggy), but it’s better than most of the others I’ve tried and the printer performs quite well.  I’ve been recommending them to anyone who’s asked me (and I get asked quite a bit).

After finishing the small starter toner cartridge they supply with the printer I put in my first TN-360 “High Yield” toner cartridge which claims 3500 pages under “normal use”.  I use this printer under what I’d consider normal conditions – mostly simple text documents.

Worked well but all of a sudden it just stopped printing with a message about the toner needed to be replaced.  “That’s odd,” I thought to myself.  “I’ve owned a lot of laser printers over the last 22+/- years and they’ve always started gradually printing more and more faintly when the toner was running out and I’ve never had a printer just refuse to print until I changed the toner cartridge before! Seems pretty heavy handed.  Then I calculated the number of pages it had printed (2120) and had an uncomfortable thought: “If they just stop and refuse to print and the printouts were looking just fine right up until that point, how do I know it’s really out of toner?”

I didn’t get my money’s worth and the forced toner replacement was feeling heavy handed and annoying.  So I wondered, “how do they decide to put up that alert anyway?”  Pulled the toner cartridge out and started examining it looking for electrical contacts (sensors inside?) or some other mechanism.  I found this:

IMG_3142

Note the arrow.  It’s pointing to a clear plastic “window” on the right side of the toner cartridge when you’re looking at the top from the front where the handle is.  It appeared like it might give the printer an optical view into the insides of the toner cartridge. “Ah HA!” I thought.  Small piece of Gorilla tape (sticks much better than electrical tape) later and I had this:

IMG_3140

Put it back in and time for a test…

Printer prints PERFECTLY… We are being ripped off by Brother and that really sucks.

This fixed worked for another 1001 perfect printouts and then it stopped again…

“DANG IT! The printouts were still looking *fine*!”

Take the toner out to put in the replacement and notice something on the side when you’re looking at the bottom:

IMG_3145

There’s Another Sensor Window!  (With Gorilla tape on it in this image).  Here’s a close-up:

IMG_3144

This piece of tape added and, sure enough, working FINE again… ARG FARG SNARG – BROTHER!  I want to like you but this is robbery!  AND it’s bad for the environment which makes it even more offensive.  Rarely do I want to call for a class action lawsuit, but this situation was definitely making me feel that way…

How many perfectly fine beautiful printouts did I get after blocking the second window?  I can’t tell you yet because it’s still going strong 200 sheets later.  :-/

So, if you want to get the full life out of your Brother TN-360 High Yield printer cartridge you may want to pick up a roll of Gorilla Tape and prepare to “fix” the cartridge.  Be careful to make sure the tape is stuck on there will because a loose piece of tape being drawn through your printer will probably do bad things to it (Follow these instructions at your own risk!).

Please add a comment if you try this with a different printer model and it works for that one also; likewise for other Brother toner cartridges. Thanks!

Cheers.

Note: All trademarks noted are the property of their respective trademark owners.

Simple BBEdit Text Filter that’s been useful: PrettyJSON.py

February 18, 2014

Dad’s been working with some JSON output from a web service lately and it comes back lacking line-feeds and indentation which is great for transmission but hard to read for humans.  Dad’s not a python programmer and Geek’s busy writing a Humanities 110 paper, but the simple python script PrettyJSON.py (below) seems to work if you put it into

~/Library/Application Support/BBEdit/Text Filters/

It can be used to beautify the front window in BBEdit if that contains JSON:


#!/usr/bin/env python
import fileinput
import json
if __name__ == "__main__":
  jsonStr = ''
  for a_line in fileinput.input():
    jsonStr = jsonStr + ' ' + a_line.strip()
  jsonObj = json.loads(jsonStr)
  print json.dumps(jsonObj, sort_keys=True, indent=2)

Because Bare Bones Software is so cool this works with their free Text Wrangler editor as well except you just put the files in

~/Library/Application Support/TextWrangler/Text Filters/

instead, as one would expect.

This gives you a new item in the “Text” -> “Apply Text Filter” sub-menu named whatever you named the file (PrettyJSON.py in my case).  Open a messy JSON file, select “Text” -> “Apply Text Filter” -> “PrettyJSON.py” and watch your file contents magically become beautiful! Thanks BBEdit!

Core Data – efficient fetching of portions of Entities

February 14, 2014

Quick write up of an active conversation on twitter and the results of some research.

Brent Simmons posted about something I’d started looking into today: Efficient Core Data fetching when you only need a few fields of a database Entity.  The name of setPropertiesToFetch: in NSFetchRequest looks promising however the documentation says:

This value is only used if resultType is set to NSDictionaryResultType.

Well that’s a bummer because we’d really like our nice subclass of NSManagedObject to be used by our view controller (say) or we only need to access one property of the complex object.  Here’s something odd I noticed though: the comment in the NSFetchRequest.h file (OS X 10.8 SDK & 10.9 SDK) for setPropertiesToFetch: says this:

If NSManagedObjectResultType is set, then NSExpressionDescription cannot be used, and the results are managed object faults partially pre-populated with the named properties

Well hey! That’s exactly what we want it to do for efficiency when we only need a couple of properties out of many for a given entity.

Thanks to some twitter dialog with @pgor and others, and especially a reminder from @JimRoepcke about setting -com.apple.CoreData.SQLDebug 1 to show the sql logging for Core Data when talking to an sqlite backend, I was able to verify that this does work the way we want it to, at least on OS X running under 10.8.4:

If you use code like the following:


NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName: @"AppEntry"];
[request setPredicate: [NSPredicate predicateWithFormat: @"app_id in %@", inAppIDs]];
[request setIncludesSubentities: NO];
[request setPropertiesToFetch: @[ @"app_id", @"fooprop"]];
// [request setIncludesPropertyValues: NO]; // you need YES, which is the default
[request setResultType: NSManagedObjectResultType];
[request setReturnsObjectsAsFaults: NO]; // maybe not needed.  It will still be a fault,
                                         // but the properties are preloaded
NSError * error = nil;
NSArray * fetchedArray = [self.managedObjectContext executeFetchRequest: request error: &error ];
if ( fetchedArray != nil )
{
  if ( [fetchedArray count] > 0 )
  {
    AppEntry * entry = [fetchedArray firstObject];
    NSLog(@" isFault? %@", entry.isFault ? @"YES" : @"NO" );
    NSNumber * appID = entry.app_id;
    NSLog(@" appID: %@", appID );
    NSLog(@" isFault? %@", entry.isFault ? @"YES" : @"NO" );
      // accessing property not in setPropertiesToFetch:
      // causes fault to fire & load whole object
    NSString * otherProperty = entry.otherProperty;
    NSLog(@" isFault? %@", entry.isFault ? @"YES" : @"NO" );
    NSLog(@"otherProperty: %@", otherProperty );
  }
  else
    NSLog(@"no resuts");
}

(code changed to mask client project details so typos are because of that)

and the output is:

// the fetch does this - only the two properties we indicated are fetched:
 CoreData: sql: SELECT t0.Z_ENT, t0.Z_PK, t0.ZAPP_ID, t0.ZFOO FROM 
                  ZAPPENTRY t0 WHERE t0.ZAPP_ID IN (?,?,?)
 isFault? YES
 appID: 281940292
 isFault? YES
 CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZAPP_ID, t0.ZOTHERPROPERTY, 
                   t0.ZDATESTAMP, t0.ZNAME, t0.ZFOO, t0.ZTITLE FROM ZAPPENTRY t0 
                   WHERE t0.Z_PK = ?
 CoreData: annotation: sql connection fetch time: 0.0025s
 CoreData: annotation: total fetch execution time: 0.0030s for 1 rows.
 CoreData: annotation: fault fulfilled from database for : 0x100150590 ...
 isFault? NO
 otherProperty: it works!

So you can see that the main fetch request only grabbed the two properties that were in setPropertiesToFetch:. The result object is a faulted NSManagedObject (see where we checked isFault) but the property values for the properties listed in setPropertiesToFetch: are available without faulting the object and doing another database fetch. You’ll see we accessed appID to check this.

However, if you then access a property that was not in the setPropertiesToFetch: list (otherProperty in the above code) you can see that another sql call is made and the object is faulted and fully loaded.  The next check for isFault returns NO because it is no longer a fault.

So to me this indicates that setPropertiesToFetch: IS useful exactly as we’d like even when you’re not getting the NSDictionaryResultType and so is ideal for exactly the situation Brent was asking about for his timeline view.    I’ve filed a radar on the documentation error rdar://16073227 so hopefully that’ll get updated sooner than later.

Update:

I was curious if one could modify one of these limited properties without faulting the entire object and all of it’s properties (which seemed unlikely) and so I did an additional test and the answer is: nope.  Modifying a prefetched property on the object causes a fault and the whole object and all it’s properties are loaded into memory and isFault returns NO.

Update #2: 

So this technique above turns out to work and be handy when you only need to fetch an item in a one-to-many property/relation off of an object with lots of properties to avoid loading all those properties into memory.  In our sample data an AppEntry has a bunch of properties including a relation to a list of prices and we’d like the most recent price (just any price for this sample code) but we don’t need to load in the rest of the data in the App Entry entity.  Works like this:

NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName: @"AppEntry"];
[request setPredicate: [NSPredicate predicateWithFormat: @"app_id == %@", inAppID]];
[request setIncludesSubentities: NO];
[request setReturnsObjectsAsFaults: NO];
[request setPropertiesToFetch: @[ @"app_id" ]];
[request setRelationshipKeyPathsForPrefetching: @[ @"prices" ]];
NSError * error = nil;
NSArray * fetchedArray = [self.managedObjectContext executeFetchRequest: request error: &error ];
if ( fetchedArray != nil )
{
  if ( [fetchedArray count] > 0 )
  {
    AppEntry * appData = [fetchedArray firstObject];
    if ( appData != nil )
    {
      PriceEntry * price = [appData.prices anyObject];
      NSLog(@"a price is: %@", price.price );
    }
  }
}

and the logging looks like this:

CoreData: sql: SELECT t0.Z_ENT, t0.Z_PK, t0.ZAPP_ID FROM ZAPPENTRY t0 WHERE t0.ZAPP_ID = ?
CoreData: annotation: sql connection fetch time: 0.0005s
CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZDATESTAMP, t0.ZPRICE, t0.ZAPP_ID
   FROM ZPRICEENTRY t0 WHERE t0.ZAPP_ID IN (?) ORDER BY t0.ZAPP_ID
CoreData: annotation: sql connection fetch time: 0.0004s
CoreData: annotation: total fetch execution time: 0.0007s for 1 rows.
CoreData: annotation: Prefetching with key 'prices'. Got 1 rows.
CoreData: annotation: total fetch execution time: 0.0022s for 1 rows.
a price is: 0

So you can see that it only loads the app_id property from the AppEntry object but still you can get to the prices relation.  Unfortunately I’m not seeing a way to cascade the setPropertiesToFetch: down into the related entities and so all the fields in the PriceEntity in this example get fetched.  I’d love to find a way to do that so if you figure that out please let me know – thanks!

Update #3: 

(I know, I know! What’s with all these updates?! – I wanted to get the basics out there and then I kept thinking of other angles/aspects of this topic).

So one thing that might be helpful is to show how to use the -com.apple.CoreData.SQLDebug 1 setting to examine what Core Data is doing when you’re using it. Setting this was critical to understanding what was happening in the above research.  You want to pass this as an argument to your app. So if you’re launching your app from the terminal you’d pass -com.apple.CoreData.SQLDebug 1 as a command line argument as usual. If you’re running from within Xcode then you set the arguments to pass to your app in the Scheme settings which you access via Edit Scheme… or Manage Schemes… + Edit Scheme….  Here’s a screenshot of the Edit Scheme sheet where you can see how to enter this flag:

Set Command Line Agrument

A Legend Awakens

February 10, 2014

“A Legend Awakens” in the Tengwar script written using a Fraktur black-letter calligraphic style, by Geek. A snow day project.

IMG_3100_web

 

 

NSURLConnection & GDC

January 9, 2014

Using NSURLConnection combined with GCD for the first time and noticed that if you invoke NSURLConnection on anything other than the main queue it seems to lock up and nothing happens.  Actually something happens but your delegate never gets called.  Easy fix though; you just need to set the delegate queue (or run loop) before starting the download.

 

Here’s some sample code setting the delegate queue for you to play with if you like. Just make a sample cocoa app from the standard template and then setup the application delegate like this


@interface AppDelegate ()
  @property (strong) NSURLConnection* connection;
  @property (strong) NSMutableData * downloadedData;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
  // Insert code here to initialize your application

  dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), 
   ^{  
      self.downloadedData = [NSMutableData new];
      NSURLRequest * request = [NSURLRequest requestWithURL: 
      [NSURL URLWithString: @"http://wp.me/av6Bm-pZ"]];
      self.connection = [[NSURLConnection alloc] initWithRequest: request 
                          delegate: self 
                        startImmediately: NO];  // This *must* be "NO". 
                                                // Can't switch delegate queue 
                                                // after download starts
      [self.connection setDelegateQueue: [NSOperationQueue mainQueue]];  // *** set queue
      [self.connection start];   // *now* you can start the fetch
      NSLog(@"request queued!");
   });
}

// delegate calls just so let us know when it's working or when it isn't

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog( @"download failed with an error: %@, %@", 
        error, [error description] );

    // release this stuff, test is done.
    self.connection = nil;
    self.downloadedData = nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog( @"connection did receive response: %@", response );
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"download data received %lu", [data length] );
    [self.downloadedData appendData: data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"didFinishLoading.  total data is: %lu", [self.downloadedData length] );

    // release this stuff, test is done.
    self.connection = nil;
    self.downloadedData = nil;
}

@end

Line 22 is the key (the setDelegateQueue: call). If you leave that line out then you’ll wonder why it’s not downloading your data. If you change the queue passed to line 12 with dispatch_get_main_queue() then it’ll work without the setDelegateQueue: call).

Obvious once you see it but maybe this’ll save someone a bit of time.

P.S. This was done with Xcode 5 under 10.8.5 fwiw.


Follow

Get every new post delivered to your Inbox.

Join 1,261 other followers