Paul Calnan's Blog Archives | Tags | About | Github
Published December 21, 2020

I have been reading a Calculus book recently and came across formulas for min and max:

\begin{align} min(x, y) = \frac{x + y - |y - x|}{2} \\ max(x, y) = \frac{x + y + |y - x|}{2} \end{align}

Here $$\frac{x + y}{2}$$ is the average of the two numbers or the midpoint between the two on the number line.

Also $$\frac{|y - x|}{2}$$ is half the distance between y and x. Adding it to the midpoint gives the maximum (rightmost) value and subtracting it from the midpoint gives the minimum (leftmost) value.

This is particularly interesting coming from a programming background where:

min(x, y) := x <= y ? x : y
max(x, y) := x >= y ? x : y


I never thought of coming up with a non-procedural formula for either of these.

We can prove that $$min(x, y) = \frac{x + y - |y - x|}{2}$$ and $$max(x, y) = \frac{x + y + |y - x|}{2}$$ as follows:

If $$x \leq y$$, then $$|y - x| = y - x$$. So $$x + y - |y - x| = x + y - y + x = 2x = 2 \cdot min(x, y)$$, and $$x + y + |y - x| = x + y + y - x = 2y = 2 \cdot max(x, y)$$.

In both cases, swap $$x$$ and $$y$$ to prove the formulas for $$x \geq y$$.

Published December 21, 2020

Euler's formula states that for any real number $$x$$:

$e^{ix} = \cos x + i \sin x$

When $$x = \pi$$, Euler's formula evaluates to:

$e^{i\pi} + 1 = 0$

This is known as Euler's identity and it links five fundamental mathematical constants ($$\pi$$, $$e$$, $$i$$, $$0$$, and $$1$$) in a beautifully simple equation. Richard Feynman called the equation "the most remarkable formula in mathematics."

The formula can be interpreted as saying that the function $$e^{i\phi}$$ is a unit complex number, i.e. it traces out the unit circle in the complex plane as $$\phi$$ ranges through the real numbers. We can derive Euler's formula from the Maclaurin series expansions of $$\sin x$$, $$\cos x$$, and $$e^x$$:

\begin{align} \sin x &= \sum_{n=0}^\infty \frac{(-1)^n}{(2n+1)!} x^{2n+1} \\ &= x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots \\ \cos x &= \sum_{n=0}^\infty \frac{(-1)^n}{(2n)!} x^{2n} \\ &= 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots \\ e^x &= \sum_{n = 0}^{\infty} \frac{x^n}{n!} \\ &= 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \cdots \end{align}

Thus:

\begin{align} e^{ix} &= \sum_{n = 0}^{\infty} \frac{(ix)^n}{n!} \\ e^{ix} &= 1 + ix + \frac{(ix)^2}{2!} + \frac{(ix)^3}{3!} + \frac{(ix)^4}{4!} + \frac{(ix)^5}{5!} + \frac{(ix)^6}{6!} + \frac{(ix)^7}{7!} + \cdots \\ &= 1 + ix - \frac{x^2}{2!} - \frac{ix^3}{3!} + \frac{x^4}{4!} + \frac{ix^5}{5!} - \frac{x^6}{6!} - \frac{ix^7}{7!} + \cdots \\ &= \left( 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} - \cdots \right) + \left( ix - \frac{ix^3}{3!} + \frac{ix^5}{5!} - \frac{ix^7}{7!} + \cdots \right) \\ &= \left( 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} - \cdots \right) + i\left( x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots \right) \\ &= \cos x + i\sin x \end{align}

This yields Euler's identity. Substitute $$\pi$$ for $$x$$. Since $$\cos \pi = -1$$ and $$\sin \pi = 0$$, it follows that:

$e^{i\pi} = -1 + 0i$

or

$e^{i\pi} + 1 = 0$

Published May 13, 2020

Computing cryptographic hashes in Swift has gotten easier in recent times. Prior to Xcode 10, it used to be difficult to import the CommonCrypto library which did the computation. Xcode 10 added a module for that library, making it easier to do the import. But the API still looks like a C API. Using the library directly requires you to write something like this:

import CommonCrypto
import Foundation

// Compute the digest of this string:
let messageString = "The quick brown fox jumps over the lazy dog"

// Convert the string to a byte array.
let messageData = Data(messageString.utf8)

// Compute the hash using CommonCrypto.
var digestData = Data(count: Int(CC_SHA224_DIGEST_LENGTH))
digestData.withUnsafeMutableBytes { (digestBuffer: UnsafeMutableRawBufferPointer) -> Void in
messageData.withUnsafeBytes { (messageBuffer: UnsafeRawBufferPointer) -> Void in
CC_LONG(messageBuffer.count),
}
}

// Convert the digestData byte buffer into a hex string.
let digestString = digestData.map { String(format: "%02hhx", $0) }.joined() // prints 730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525 print(digestString)  That's a fair amount of boilerplate. The meat of that code — the withUnsafeMutableBytes and withUnsafeBytes calls — changed between Swift versions. I had to rewrite that code a few times to eliminate new compiler warnings and deprecations. Rather than deal with that in production code, I wrote a small Swift library called HashAlgorithm to simplify the process. Using it is pretty simple. Instead of the code above, you just do this: import Foundation import HashAlgorithm // Compute the digest of this string: let messageString = "The quick brown fox jumps over the lazy dog" let digest = HashAlgorithm.SHA224.digest(messageString) // prints 730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525 print(digest)  The digest(_:) function returns a Digest value that wraps a Data value. Its description property converts the data into a hex-string. It supports all of the (non-deprecated) cryptographic hash algorithms currently provided by CommonCrypto: SHA1, SHA224, SHA256, SHA384, and SHA512. Published May 13, 2020 Has Xcode stopped working for you? Builds acting funny? Autocomplete stopped working? You've quit and restarted it, cleaned the build folder, and it's still broken? Try running this. #!/usr/bin/env bash set -euo pipefail echo "Exiting Xcode" osascript -e 'quit app "Xcode"' echo "Deleting DerivedData" rm -rf ~/Library/Developer/Xcode/DerivedData/* echo "Deleting llvm module cache" rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache"

echo "Relaunching Xcode"
open -a Xcode

Published May 10, 2020

I'm working on a side project that has required some on-device troubleshooting. I find myself loading a build on my phone and using it for several days. There's been a lot of trial-and-error debugging in this project, so I often run code from an experimental branch for extended periods of time. It's easy to lose track of what source configuration I have loaded on my phone at any given time.

I wanted to get a way to get the current Git revision and branch into the app. I figured a good start would be the following:

• The branch name (using git rev-parse --abbrev-ref HEAD)
• The abbreviated hash of the current commit (using git rev-parse --short HEAD)
• Whether the working copy was clean or not. I got this by checking the output of git status -s. If the working copy is clean (i.e., no untracked files and no changes to tracked files), that command prints nothing. If the working copy is dirty, the command prints something.

I wanted to get this information into each build, not just release builds. Getting this information from a shell script into a build is tricky. One of the problems is that you can't modify the working copy. Doing so would change the "is clean" flag. The build would always show dirty and a commit would be needed to clean it, changing the commit hash.

The approach I settled on was to write an untracked Swift file as part of the build process.

First, add generate-git-revision.sh (see below) to your project's bin directory (or wherever you keep your project's scripts).

#!/usr/bin/env bash

set -euo pipefail

cat <<SWIFT
//
//  GitRevision.swift
//
//  This file was automatically generated. Do not edit manually. It will be overwritten on every build.
//
//  IMPORTANT: This file must be added to .gitignore or it will dirty the working tree every time there is a build.
//

/// Information about the current Git revision.
struct GitRevision {

/// The name of the current branch.
static let branch = "$(git rev-parse --abbrev-ref HEAD)" /// The abbreviated hash of the current commit. static let commit = "$(git rev-parse --short HEAD)"

/// Whether the working tree is clean. If false, indicates that there are uncommitted or untracked files in the working tree.
static let clean = $([[ -z$(git status -s) ]] && echo 'true' || echo 'false')

/// Build timestamp. Set when this file was generated at the beginning of the build process.
static let timestamp = "$(date +%Y-%m-%dT%H:%M:%S)" /// A string summarizing the current Git revision. static var description: String { return "\(commit)\(clean ? "" : "-dirty") \(branch) \(timestamp)" } } SWIFT  Next, in Xcode add a new Run Script build phase at the top of the list of Build Phases (directly under Dependencies). Call the new build phase Generate GitRevision.swift. Make the body of the build phase script: "${PROJECT_DIR}/path/to/generate-git-revision.sh" > "\${PROJECT_DIR}/path/to/GitRevision.swift"


Build the project. This causes the script to run and generate GitRevision.swift.

Now, add the new GitRevision.swift file to the project. Also add GitRevision.swift to the project's .gitignore file.

That's it. The generated GitRevision.swift file will look something like this:

//
//  GitRevision.swift
//
//  This file was automatically generated. Do not edit manually. It will be overwritten on every build.
//
//  IMPORTANT: This file must be added to .gitignore or it will dirty the working tree every time there is a build.
//

/// Information about the current Git revision.
struct GitRevision {

/// The name of the current branch.
static let branch = "development"

/// The abbreviated hash of the current commit.
static let commit = "3c747d5"

/// Whether the working tree is clean. If false, indicates that there are uncommitted or untracked files in the working tree.
static let clean = false

/// Build timestamp. Set when this file was generated at the beginning of the build process.
static let timestamp = "2020-05-10T23:03:15"

/// A string summarizing the current Git revision.
static var description: String {
return "\(commit)\(clean ? "" : "-dirty") \(branch) \(timestamp)"
}
}


If you leave that file open in Xcode when you build, you can see the property values change as the file gets regenerated.

You can now reference GitRevision.description from your app's code to show the commit, branch, and build time.