Archive for the ‘Various Frustrations’ Category

Grepping for parentheses

Just because I had to do this today and thought I’d share. Either use the -E option, for example,

grep -E "let \(" */*.swift

or use egrep directly:

egrep "let \(" */*.swift

Both egrep and grep -E use extended regular expressions, allowing you to use a simple backslash rather than trying to get your shell to cooperate with hyper-escaping. You can use the same approach with sed as well:

echo "(hi)" | sed -E "s/\(/[/"

I hope this helps someone.

Swift Terms: arguments, parameters, and labels

Help me refine some terminology.

Start with this code snippet:

func foo(with a: Int) -> Int { return a }

You use arguments at call sites and parameters in declarations. This example function defines one parameter that accepts one argument from the call site, e.g. foo(with: 2). 

Apple’s Swift Programming Language book uses this approach:

Use func to declare a function. Call a function by following its name with a list of arguments in parentheses. Use -> to separate the parameter names and types from the function’s return type.

The mighty Wikipedia writes:

The term parameter (sometimes called formal parameter) is often used to refer to the variable as found in the function definition, while argument (sometimes called actual parameter) refers to the actual input passed.

The Swift grammar lays out the external and local differentiation available to parameter declarations:

parameter → external-parameter-name local-parameter-name type-annotation default-argument-clause

Like Apple, I use label instead of name to refer to a parameter’s API-facing component outside of the grammar. The Swift Programming Languages refers to these as a custom argument label, naming it from the consumption POV. Apple writes:

By default, functions use their parameter names as labels for their arguments. Write a custom argument label before the parameter name, or write _ to use no argument label.

I generally call it a label or an external label instead. I often use parameter here (external parameter label, for example), especially when talking about the declaration. I don’t think there’s any real harm in doing so.

In this example, the parameter’s local or internal name is a. Some developers also call it the local or internal variable name. I find that word overloaded in meaning. Swift differentiates constants and variables and does not permit variables in function signatures.

I don’t have any problem calling it an internal argument name either because it’s the name given to the argument passed to the function or method. This seems slightly out of sync with SPL standards and practices. What do you think?

How To: Finding your iTunes Connect Vendor ID number

Apple sent me an email:

Apple was recently notified that your bank account information has been manually corrected by the processing bank for iTunes payments to vendor [my personal vendor id number]. Unfortunately Apple cannot continue processing payments with the current banking details provided in iTunes Connect. To avoid unnecessary payment delays or returns, please log into iTunes Connect and provide the correct account information in Agreements, Tax, and Banking. For instructions on how to update banking, see ‘How do I add or edit a new bank account?’ in iTunes Connect Resources and Help. After the banking changes have been entered in our systems, payments will resume.

Oh shiny.

I pull out my latest statement and off I go to update my details. Here’s my problem. I don’t know which vendor account Apple is referring to. Like many developers, I use multiple iTC accounts. When I log into each one, I cannot find the vendor ID. Argh.

To save you lots of time, do this:

  • Log into any iTC account.
  • Manually navigate to https://reportingitc2.apple.com/reports.html
  • The vendor ID is listed next to your name. You should not have to re-authenticate when hopping from iTC to this page.

This helped me figure out which affected account was being referred to in the email and was able to update my info.

To update a direct deposit routing number, you need to hop into Agreements, Tax, and Banking. Click on the Bank Info > View button. You cannot edit the routing number in your existing Current Bank Account. Instead you need to Add Bank Account with the same details and the new routing number and then select that as your new account. Once you do it will take 24-48 hours for the change to go through and you will not be able to make further edits during that time.

Bridging Swift Generics with Darwin Calls

Seth Willits was working on an interpolation protocol that would allow conforming constructs to interpolate from one value to another, regardless of their underlying types. It needed to work for CGFloat as well as Double, and be decomposable and useful for CGPoint and CGRect as well as any custom Swift Polygon struct.

This created interesting challenges, as some of the most fundamental animation curves use exponentiation, which is not built into the Swift standard library. So I turned to pow, which is only defined for float and double:

public func powf(_: Float, _: Float) -> Float
public func pow(_: Double, _: Double) -> Double

In the past, I’ve created horrible bridging solution that permits migration from most floating point values to double. It’s not beautiful but I decided to pull it out from my toolkit and introduce it to this problem.

What I did was to build an extension on BinaryFloatingPoint that returned an interpolated value along a styled curve. My hack let me create a single interpolate method that applied across floating-point. I bridged to Double to use the Darwin pow function:

There’s an interesting CGFloat bug in play here, where the value history does not display as a graph but the numbers are right and work properly during animation.

Here’s the code. Shout out your improvements and alternatives.

MacBook Pros and External Displays

Today, I hooked a newly purchased display to my MBP. (Looks like they’re out of stock right now, but it was $80 for 24″ when I bought it last week.) This isn’t intended to be my display. It’s replacing an old 14″ monitor for a kid. I thought I’d just steal it now and then during the day. It’s extremely lightweight and easy to move between rooms.

What I didn’t expect was how awful the text looked on it. I hooked up the monitor to the MBP using my Apple TV HDMI cable. The text was unreadable. I use similar TV-style monitors for my main system and they display text just fine. However, I’m using normal display ports and cables for my mini. This is the first time I’ve gone HDMI direct.

So off to websearch I went. Sure enough this is a known longstanding problem that many people have dealt with before. The MBP sees the TV as a TV and not a monitor. It produces a YUV signal instead of the RGB signal that improves text crispness. Pictures look pretty, text looks bad.

All the searches lead to this ruby script. The script builds a display override file containing a vendor and product ID with 4:4:4 RGB color support. The trick lies in getting macOS to install, read, and use it properly. That’s because you can’t install the file directly to /System/Library/Displays/Contents/Resources/Overrides/ in modern macOS. Instead, you have to disable “rootless”.

I wasn’t really happy about going into recovery mode. Disabling system integrity protection feels like overkill for a simple display issue. But it  worked.  It really only took a few minutes to resolve once I convinced myself it was worth doing. If you have any warnings and cautions about installing custom display overrides, please let me know. It  feels like I did something morally wrong even if it did fix my problem.

My external display went from being unusable to merely imperfect. The text is still a bit blurry but you can read it without inducing a migraine. Not nearly as crisp as normal display ports (which looks fine when used with this monitor) but I don’t have to buy a new cable and I don’t plan to use this much.

If I were going to use this monitor regularly with the MBP, I’d definitely purchase a proper cable. As it is, I’m happy enough to have found a workable-ish solution. The monitor is quite nice especially in “shop mode”, and has so far worked well with Chromecast, AppleTV, and Wii.

Overdrive, DRM, and Adobe Digital Editions

The Denver library recently migrated its ebook system. Incidentally, it wiped all my holds in the process and I have no idea what stuff I was waiting to read. So if you recced anything over the past 6 months and it was popular, chances are that I need you to remind me to read it again.

Anyway, today my first hold came in on the new system. I downloaded the ascm file as usual, double clicked, and when Adobe Digital Editions opened, I got this on my screen:

Yikes. I immediately assumed it was time to update Adobe Digital Editions. So I did that. And I tried opening it up again and I got this:

While you can see the massive UI improvements Adobe has made to its signature Mac e-reader, I was still rather stuck.

So I googled for E_ACT_NOT_READY and “IO Error on Network Request” and tried all the things that didn’t work until I found something that did work.

What didn’t work:

  • Clearing out ~/Documents/Digital Editions
  • Creating a new ~/Documents/My Digital Editions
  • Quitting and restarting the apps
  • Rebooting

What did work was reauthorizing my computer. Dunno why. I deauthorized and then reauthorized — good thing I remembered my username and password because it has been a gadzillion years since I did this last — and boom it finally worked.

(If you want to remove authorization by hand, toddle over to ~/Library/Application Support/Adobe/Digital Editions and kill the activation.dat file.)

Anyway, Scott Sigler’s “Alive” is now on my system ready for reading. I have no idea why I put this title on hold and who recommended it to me. I hope it’s good. Here’s finger’s crossed that this is a good read.

Apple TV, Home Sharing, and Missing Movies

I rented Hunt for the Wilderpeople last week, while it was the $0.99 featured rental. I’ve heard good things about this Kiwi movie (I’m a bit of a kiwiholic) and couldn’t wait to watch it.

screen-shot-2016-12-13-at-2-41-44-pm

So today, with a draft of Swift Style pushed up to Pragmatic, I thought I’d set it up for a nice family watch tonight. I opened the Computers > Rentals section on Apple TV and saw this:

screen-shot-2016-12-13-at-2-47-11-pm

I wasted about 20 minutes googling things like “why doesn’t my rental show up on my Apple TV” and checking my iTunes accounts and home sharing setup, when I suddenly remembered this had happened to me before.

With that spark of inspiration lingering in my mind, I went to iTunes on my computer (where I had rented it) and sure enough, it was still up in the cloud. I clicked the download button and got it down to my computer:

screen-shot-2016-12-13-at-2-41-42-pm

About 1.41 Gigabytes later (and several pause/resumes when the download speed got slow — seriously, at one point the ETA jumped from over 40 minutes to under 3), I returned to Apple TV and hopped into my home-sharing library.

screen-shot-2016-12-13-at-3-19-15-pm

Tada.

So if you’re looking for a lost movie, or you can’t find your rental on Apple TV, make sure that if you rented it on your home computer, that you’ve downloaded it from the cloud before attempting to play it from ATV.

Enter the Python: Peeking at a language

Last week, I wrote about how I set up Xcode to run Python. It’s been working great. Xcode may not be everyone’s cup of tea, but I love it. Syntax highlighting, familiar keybindings, symbol completion. I couldn’t be happier. A lot of people pushed me to use Pycharm community edition, but while I’ve installed it and tried it a few times, I keep going back to Xcode. Warts and all.

I haven’t logged many hours in Python but it’s been a fascinating language experience. Let me go all metaphor on you. Way back in the 90’s there was this show called “Sliders“, about a bunch of people moving between parallel worlds. Almost everything was the same from world to world — normal humans, trees, buildings, whatever — but there were always fundamental differences in the culture and the people that always reminded you that you weren’t home.

Python is the Sliders version of Swift, the one where Chris Lattner was never born. Everything is eerily familiar and nothing is quite right. Where are my value types? My generics? My type extensions. Let me throw out another metaphor — one that will probably resonate with even fewer people: Python is the language version of the Nethack Rogue Level, where you enter “what seems to be an older, more primitive world.” It’s all familiar. Nothing is exactly the same.

This morning, I attempted to extend a type. I’m working with Anki’s Cozmo robot SDK, which is written for Python 3.5.1 or later. I’m trying to reconfigure many of the basic calls into more appropriate chunks suitable for teaching kids some programming basics.

Instead of focusing on asynchronous callbacks and exceptions, I want to provide really simple blocks that extend the robot type API in a way that hides nearly all the implementation details. I’m trying to build, in a way, a Python version of Swift Playgrounds but with a real robot. (And it’s going well, but more about that in another post.)

What I found was that Python really doesn’t want to extend types. You can subclass. You can compose. But so far, I haven’t found a way to add an extension that services an existing type. When I asked around, the Python gurus on freenode recommended I stop worrying about polluting the global namespace and embrace freestanding functions as needed.

Oh, my delicate Swift sensibilities! Adding global functions and constants? Cluttering the global namespace? I find myself clinging to Swift conventions. I create enumerations and type my arguments:

class Direction(IntEnum):
    '''Permitted driving directions.'''
    forward = 1
    backward = -1

def drive(robot: cozmo.robot.Robot, 
    direction: Direction = Direction.forward): ...

The Cozmo SDK defines its constants like this:

LEFT = 1
RIGHT = 2
TOP = 4
BOTTOM = 8

I don’t think I’m in Swift-land anymore.

A lot of the things I like most about Python appear to be fairly new, like that ability to type arguments. I’m assured by some Pythonistas that this is almost entirely syntactic sugar, and there appears to be no type-checking, inference, or casting applied to calls.

I thought I would really hate the indentation-based scoping but I don’t. It’s easy to use (start a scope with a colon, indent 4 spaces for that scope). It reads well. It’s clean. Non-braced scoping ended up being a complete non-issue for me, and I mildly admire its clean look.

I’m less excited by Python’s take on structured documentation. The standard is outlined in PEP-257. Unlike Apple’s Swift Documentation Markup, Python markup doesn’t seem to support specific in-line tool use in addition to document generation. I’m sensitive to how much better Swift creates a structured system for detailing parameters, error conditions, return types, and descriptions, and how it scales from types to functions and methods to individual instances and provides Xcode integration.

So much in Python is very similar to Swift but with a slight twist to it. Closures? Lambdas are in there. Mapping? That’s there too. Partial application? Seems to be. Most times that I reach for a tool in my existing proficiencies, I can usually find a Python equivalent such as list comprehension, which is basically mapping across sequences and collections.

I’m sorely missing my value types. One of the first things I did when trying to work through some tutorials was to try to create a skeleton dictionary rather than type out full dictionaries for each instance. I quickly learned Python uses reference types:

# the original dict was more complicated
studentDict = {"name" : "", "tests" : []} 

joe = studentDict # create joe
joe["name"] = "joe"
bob = studentDict # create bob
bob["name"] = "bob"

# reference type
print(joe) # {'tests': [], 'name': 'bob'}
print(bob) # {'tests': [], 'name': 'bob'}

Oops.

In any case, I’m still really really new to the language given my full-court-press on finishing Swift Style. As much as I wish I were writing this code in Swift, I’m glad that I have the opportunity to explore Python and hope I get to spend some time with Scala in the near future. This project is offering me a lot of valuable insights about where Swift came from and increased appreciation for the work the core Swift team put in to give us the language we have now.

Running Python in Xcode: Step by Step

As I’m preparing for a project that will involve Python programming, I need to get up to speed with at least a basic level of Python mastery. However, I’m not a big fan of using the interactive Python REPL, or whatever it is actually called:

screen-shot-2016-12-04-at-11-37-21-am

I decided to use Xcode instead, and I’m finding it a much better solution for my needs:

screen-shot-2016-12-03-at-8-31-15-pm

Here’s the steps I took to set up this project:

Step 1: Install Python 3.5

If you run python -V at the command line, macOS reports “Python 2.7.10”, or at least it does on my system. Bzzt. I want 3.5.2, which is the most recent non-beta release, and dates to June of this year.

I grabbed my installer from the Python.org downloads page: https://www.python.org/downloads/release/python-352/

Step 2: Locate python3

I use tcsh, so where python3 reports /usr/local/bin/python3. The location is surely the same for you, but I don’t know what the equivalent for where is in bash.

Step 3: Create an Xcode project

File > New > Project > Cross-platform > External Build System > Next.

screen-shot-2016-12-04-at-11-44-06-am

Enter a name (e.g. Python), and enter the path from Step 2 into the “Build Tool” line. Click Next.

screen-shot-2016-12-04-at-11-44-43-am

Navigate to whatever location you like, and click Create.

Step 4. Create a Python file

Choose File > New,  select macOS > Other > Empty. Click  Next.

screen-shot-2016-12-04-at-11-48-04-am

You should already be in your project’s top level folder. If not, go there. Name your file Whatever.py, choosing whatever name you like. I went with Work.py. Make sure the “add to target Python” box is checked. Click Create.

screen-shot-2016-12-04-at-11-49-43-am

Step 5. Edit your Run Scheme

The Xcode default should have the Run scheme selected:

cap

Click and hold on the Python target in the jump bar. Select Edit Scheme…

screen-shot-2016-12-04-at-11-50-56-am-2

The Run scheme displays, with the Info tab selected.

Step 6. Choose the Executable

I warn you now that this step is going to be delicate, fragile, and stupid. That’s because Xcode, for whatever reason, will not let you use the symbolic link at /usr/local/bin/python3. I don’t know why.

In the Info tab. Select “Other” from the Executable pop-up list. A file selection dialog appears.

cap

 

Return to the terminal. Type: open /usr/local/bin. Select python3 and control-click/right-click. Select Show Original. This will probably be named python3.5. It’s not a symbolic link but unfortunately Xcode continues to be fussy about allowing you to select it as your executable because of the period in its name. Sigh.

Drag python3.5 onto the file dialog and click Choose, if you’re allowed to. If so, great. If not, you need to work around Xcode: create a hard link and then drag the link onto the dialog.

% ln python3.5 python35

I know, I know. Ew. But it’s better than copying, or worse, renaming the file. And no, symbolic links don’t seem to work here. Better solution? Let me know.

Finally, uncheck “Debug executable”. You don’t want to debug the Python language itself.

screen-shot-2016-12-04-at-12-05-26-pm

Step 7. Add Launch Arguments

Now, click the Arguments tab. Click + under “Arguments Passed On Launch” and type $(SRCROOT)/ followed by the name of the Python file you created in Step 4.

screen-shot-2016-12-04-at-12-07-02-pm

Step 8. Test it out.

Click Close to dismiss the scheme editor. Enter a program (don’t forget all those colons and tabs) and run it:

screen-shot-2016-12-04-at-12-38-05-pm

It’s a very odd thing to be jumping into Python with a Swift background. Clearly Swift has inherited a lot of Python genes. It also feels sinful to use such lax typing without compiler oversight. That said, my first experiences in Python can wait for another day and another post. More to follow.

Cocoapods and Copyright claims

So what do I do about this? Or more particularly about this: “Copyright (c) 2016 tangzhentao <tangzhentaoxl@sina.cn>”? I don’t mind people using sources from my repos, but I do mind them claiming copyright. I would appreciate advice and thoughts.

Update: On Jeremy Tregunna’s advice, I sent an email: “You are welcome to create Cocoapods using my repositories, but you are not welcome to claim copyright ownership, change the license (BSD attribution in this case), or otherwise misattribute my code. ” I asked tangzhentao to correct the matter immediately.

Update: Tangzhentao responds: “I just saw this problem today in Github and then I went to check my email. Thank everybody to piont out this mistake, especially Erica Sadun. Now I have corrected this mistake. But I don’t know if I really correct this mistake. If not, please remind me, thanks.” There are no changes to the authorship or copyrights, I have asked him/her to update within 24 hours or I will contact Github.