import Foundation

/// NSUUID adopts DatabaseValueConvertible
extension NSUUID : DatabaseValueConvertible {

    /// Returns a value that can be stored in the database.
    public var databaseValue: DatabaseValue {
        var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
        return uuidBytes.withUnsafeMutableBufferPointer { buffer in
            getBytes(buffer.baseAddress!)
            return NSData(bytes: buffer.baseAddress, length: 16).databaseValue
        }
    }

    /// Returns an NSUUID initialized from *dbValue*, if possible.
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
        guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else {
            return nil
        }
        return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
    }
}

/// UUID adopts DatabaseValueConvertible
extension UUID : DatabaseValueConvertible { }

Make the bug-fix conditional to continue building on 3.1

import Foundation

/// NSUUID adopts DatabaseValueConvertible
extension NSUUID : DatabaseValueConvertible {

    /// Returns a value that can be stored in the database.
    public var databaseValue: DatabaseValue {
        var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
        return uuidBytes.withUnsafeMutableBufferPointer { buffer in
            #if swift(>=3.2)
                getBytes(buffer.baseAddress!)
            #else
                getBytes(buffer.baseAddress)
            #endif
            return NSData(bytes: buffer.baseAddress, length: 16).databaseValue
        }
    }

    /// Returns an NSUUID initialized from *dbValue*, if possible.
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
        guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else {
            return nil
        }
        return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
    }
}

/// UUID adopts DatabaseValueConvertible
extension UUID : DatabaseValueConvertible { }


//
//  String.swift
//  Toolbelt
//
//  Created by Alexander Edge on 08/12/2015.
//  Copyright © 2015 Alexander Edge. All rights reserved.
//

import Foundation

extension NSData {

    public var hexadecimalString : String {
        var str = String()
        var bytes = [UInt8](count: self.length, repeatedValue: 0)
        self.getBytes(&bytes, length: self.length)
        for byte in bytes {
            str += String(format: "%02x",byte)
        }
        return str
    }

}

Use `reduce` for hex string implementation

//
//  String.swift
//  Toolbelt
//
//  Created by Alexander Edge on 08/12/2015.
//  Copyright © 2015 Alexander Edge. All rights reserved.
//

import Foundation

extension NSData {

    public var hexadecimalString : String {
        var bytes = [UInt8](count: self.length, repeatedValue: 0)
        self.getBytes(&bytes, length: self.length)
        return bytes.reduce(""){ return $0 + String(format:"%02x",$1)}
    }

}


//
//  AppDelegate.swift
//  SwiftySensorsExample
//
//  https://github.com/kinetic-fit/sensors-swift
//
//  Copyright © 2017 Kinetic. All rights reserved.
//

import UIKit
import SwiftySensors

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // Customize what services you want to scan for
        SensorManager.instance.setServicesToScanFor([
            CyclingPowerService.self,
            CyclingSpeedCadenceService.self,
            HeartRateService.self])

        // Add additional services we want to have access to (but don't want to specifically scan for)
        SensorManager.instance.addServiceTypes([DeviceInformationService.self])

        // Set the scan mode (see documentation)
        SensorManager.instance.state = .aggressiveScan

        // Capture SwiftySensors log messages and print them to the console. You can inject your own logging system here if desired.
        SensorManager.logSensorMessage = { message in
            print(message)
        }

        return true
    }

}

Add FTMS to the example scan list

//
//  AppDelegate.swift
//  SwiftySensorsExample
//
//  https://github.com/kinetic-fit/sensors-swift
//
//  Copyright © 2017 Kinetic. All rights reserved.
//

import UIKit
import SwiftySensors

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // Customize what services you want to scan for
        SensorManager.instance.setServicesToScanFor([
            CyclingPowerService.self,
            CyclingSpeedCadenceService.self,
            FitnessMachineService.self,
            HeartRateService.self])

        // Add additional services we want to have access to (but don't want to specifically scan for)
        SensorManager.instance.addServiceTypes([DeviceInformationService.self])

        // Set the scan mode (see documentation)
        SensorManager.instance.state = .aggressiveScan

        // Capture SwiftySensors log messages and print them to the console. You can inject your own logging system here if desired.
        SensorManager.logSensorMessage = { message in
            print(message)
        }

        return true
    }

}


import UIKit

class SCRoundedButton: SCButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.backgroundColor = UIColor.spycodesGreenColor()
        self.layer.borderColor = UIColor.clearColor().CGColor
        self.layer.cornerRadius = 22.0
        self.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        self.titleLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 20)
    }

    override var highlighted: Bool {
        didSet {
            if highlighted {
                self.backgroundColor = UIColor.spycodesDarkGreenColor()
            }
            else {
                self.backgroundColor = UIColor.spycodesGreenColor()
                self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
            }
        }
    }
}

Return title color to white after highlighting

import UIKit

class SCRoundedButton: SCButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.backgroundColor = UIColor.spycodesGreenColor()
        self.layer.borderColor = UIColor.clearColor().CGColor
        self.layer.cornerRadius = 22.0
        self.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        self.titleLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 20)
    }

    override var highlighted: Bool {
        didSet {
            if highlighted {
                self.backgroundColor = UIColor.spycodesDarkGreenColor()

            }
            else {
                self.backgroundColor = UIColor.spycodesGreenColor()
            }

            self.titleLabel?.textColor = UIColor.whiteColor()
        }
    }
}


// RUN: %target-typecheck-verify-swift -warn-long-expression-type-checking=1 -warn-long-function-bodies=1 %s
func foo<T>(_ x: T) -> T { return x }
func foo(_ x: Int) -> Int { return x }

func test(m: Double) -> Int {
  // expected-warning@-1 {{global function 'test(m:)' took}}
  return Int(foo(Float(m) / 20) * 20 - 2) + 10
  // expected-warning@-1 {{expression took}}
}

Fix test failure by removing function bodies.

// RUN: %target-typecheck-verify-swift -warn-long-expression-type-checking=1 -warn-long-function-bodies=1 %s
@_silgen_name("generic_foo")
func foo<T>(_ x: T) -> T

@_silgen_name("foo_of_int")
func foo(_ x: Int) -> Int

func test(m: Double) -> Int {
  // expected-warning@-1 {{global function 'test(m:)' took}}
  return Int(foo(Float(m) / 20) * 20 - 2) + 10
  // expected-warning@-1 {{expression took}}
}


// REQUIRES: OS=windows-msvc
// This test is special-cased on Windows because dependencies in Two.swift don't
// appear to be registered against the tracker. rdar://60030114

// RUN: %empty-directory(%t)
// RUN: %{python} %S/../gen-output-file-map.py -o %t %S/Inputs -r %t.resp
// RUN: cd %t
// RUN: not %target-swiftc_driver -no-color-diagnostics -typecheck -output-file-map %t/output.json -incremental -module-name main -verify-incremental-dependencies @%t.resp 2>&1 | sort | %FileCheck %s

// CHECK: unexpected cascading member dependency: main.Base.init
// CHECK: unexpected cascading potential member dependency: main.Base
// CHECK: unexpected provided entity: Base
// CHECK: unexpected provided entity: BaseProtocol

Remove a missing dependency edge on Windows

// REQUIRES: OS=windows-msvc
// This test is special-cased on Windows because dependencies in Two.swift don't
// appear to be registered against the tracker. rdar://60030114

// RUN: %empty-directory(%t)
// RUN: %{python} %S/../gen-output-file-map.py -o %t %S/Inputs -r %t.resp
// RUN: cd %t
// RUN: not %target-swiftc_driver -no-color-diagnostics -typecheck -output-file-map %t/output.json -incremental -module-name main -verify-incremental-dependencies @%t.resp 2>&1 | sort | %FileCheck %s

// CHECK: unexpected cascading member dependency: main.Base.init
// CHECK: unexpected provided entity: Base
// CHECK: unexpected provided entity: BaseProtocol


//
//  AUView.swift
//  AppUtilityExample
//
//  Created by Apple on 01/03/17.
//  Copyright © 2017 Sunil Sharma. All rights reserved.
//

import UIKit

extension UIView
{
    func copyView<T: UIView>() -> T? {
        return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as? T
    }

  func courner(with radius: CGFloat) {
    self.clipsToBounds = true
    self.layer.cornerRadius = radius
  }
}

/*class AUView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}*/

Rename function from courner to corner

//
//  AUView.swift
//  AppUtilityExample
//
//  Created by Apple on 01/03/17.
//  Copyright © 2017 Sunil Sharma. All rights reserved.
//

import UIKit

extension UIView
{
    func copyView<T: UIView>() -> T? {
        return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as? T
    }

  func corner(with radius: CGFloat) {
    self.clipsToBounds = true
    self.layer.cornerRadius = radius
  }
}

/*class AUView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}*/


//
//  GeoVector.swift
//  Compass
//
//  Created by Fabian Canas on 6/3/15.
//  Copyright (c) 2015 Fabian Canas. All rights reserved.
//

import CoreLocation

extension Vector3 {
    public init(coordinate: CLLocationCoordinate2D) {
        let latitude :Radian = Radian(angle: Degree(coordinate.latitude))
        let longitude :Radian = Radian(angle: Degree(coordinate.longitude))
        dx = sin(longitude) * cos(latitude)
        dy = cos(longitude) * cos(latitude)
        dz = sin(latitude)
    }
}

extension CLLocationCoordinate2D {
    init(v: Vector3) {
        longitude = atan( v.dy / v.dx )
        latitude = acos( v.dz / magnitude(v) )
    }
}

Fix geo-vector function and add bearing function

//
//  GeoVector.swift
//  Compass
//
//  Created by Fabian Canas on 6/3/15.
//  Copyright (c) 2015 Fabian Canas. All rights reserved.
//

import CoreLocation

func bearing(start: CLLocationCoordinate2D, end: CLLocationCoordinate2D)  -> Radian {
    let (lat1, lng1) = start.asRadians
    let (lat2, lng2) = end.asRadians
    return Radian(atan2(sin(lng1 - lng2) * cos(lat2), cos(lat1)*sin(lat2) - sin(lat1)*cos(lat2)*cos(lng1-lng2)))
}

extension Vector3 {
    public init(coordinate: CLLocationCoordinate2D) {
        let latitude :Radian = Radian(angle: Degree(coordinate.latitude))
        let longitude :Radian = Radian(angle: Degree(coordinate.longitude))
        dx = sin(longitude) * cos(latitude)
        dy = cos(longitude) * cos(latitude)
        dz = sin(latitude)
    }
}

extension CLLocationCoordinate2D {
    init(v: Vector3) {
        longitude = Degree(angle:Radian(atan2( v.dy, v.dx ))).value
        latitude = Degree(angle: Radian(acos( v.dz / magnitude(v) ))).value
        assert(CLLocationCoordinate2DIsValid(self), "Making an invalid coordinate from a vector")
    }

    var asRadians :(latitude: Radian, longitude: Radian){
        get {
            return (latitude: Radian(angle:Degree(self.latitude)), longitude: Radian(angle:Degree(self.latitude)))
        }
    }
}


/**
 * Question Link: https://leetcode.com/problems/merge-intervals/
 * Primary idea: Sort the original intervals and then append them one by one
 * Time Complexity: O(nlogn), Space Complexity: O(n)
 *
 * Definition for an interval.
 * public class Interval {
 *   public var start: Int
 *   public var end: Int
 *   public init(_ start: Int, _ end: Int) {
 *     self.start = start
 *     self.end = end
 *   }
 * }
 */

class MergeIntervals {
    func merge(intervals: [Interval]) -> [Interval] {
        guard intervals.count > 0 else {
            return intervals
        }

        var intervals = intervals.sort() {
            if $0.start != $1.start {
                return $0.start < $1.start
            } else {
                return $0.end < $1.end
            }
        }

        var res = [intervals.first!]

        for i in 1..<intervals.count {
            let (last, current) = (res.last!, intervals[i])

            if current.start > last.end {
                res.append(current)
            } else {
                last.end = max(last.end, current.end)
            }
        }

        return res
    }
}

Optimize syntax for Merge Intervals

/**
 * Question Link: https://leetcode.com/problems/merge-intervals/
 * Primary idea: Sort the original intervals and then append them one by one
 * Time Complexity: O(nlogn), Space Complexity: O(n)
 *
 * Definition for an interval.
 * public class Interval {
 *   public var start: Int
 *   public var end: Int
 *   public init(_ start: Int, _ end: Int) {
 *     self.start = start
 *     self.end = end
 *   }
 * }
 */

class MergeIntervals {
    func merge(intervals: [Interval]) -> [Interval] {
        var result = [Interval]()

        let intervals = intervals.sorted {
            if $0.start != $1.start {
                return $0.start < $1.start
            } else {
                return $0.end < $1.end
            }
        }

        for interval in intervals {
            guard let last = result.last else {
                result.append(interval)
                continue
            }

            if last.end < interval.start {
                result.append(interval)
            } else {
                last.end = max(last.end, interval.end)
            }
        }

        return result
    }
}


import UIKit

public class CellPresenterDataSource: NSObject {
  var cellPresenters: [CellPresenter]?

  public func display(cellPresenters cellPresenters: [CellPresenter], tableView: UITableView?) -> Void {
    self.cellPresenters = cellPresenters
    if let tableView = tableView {
      tableView.dataSource = self as UITableViewDataSource?
      performOnMainQueue {
        tableView.reloadData()
      }
    }
  }
}

extension CellPresenterDataSource: UITableViewDataSource {
  public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let cellPresenters = cellPresenters {
      return cellPresenters.count
    } else {
      return 0
    }
  }

  public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if let cellPresenters = cellPresenters {
      let cellPresenter = cellPresenters[indexPath.row]
      let cell = tableView.dequeueReusableCellWithIdentifier(cellPresenter.cellIdentifier(), forIndexPath: indexPath)
      cellPresenter.present(cell)
      return cell
    }

    return UITableViewCell()
  }
}

Initialize cellPresenters with an empty array in data source

import UIKit

public class CellPresenterDataSource: NSObject {
  var cellPresenters: [CellPresenter] = []

  public func display(cellPresenters cellPresenters: [CellPresenter], tableView: UITableView?) -> Void {
    self.cellPresenters = cellPresenters
    if let tableView = tableView {
      tableView.dataSource = self as UITableViewDataSource?
      performOnMainQueue {
        tableView.reloadData()
      }
    }
  }
}

extension CellPresenterDataSource: UITableViewDataSource {
  public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cellPresenters.count
  }

  public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellPresenter = cellPresenters[indexPath.row]
    let cell = tableView.dequeueReusableCellWithIdentifier(cellPresenter.cellIdentifier(), forIndexPath: indexPath)
    cellPresenter.present(cell)
    return cell
  }
}


//
//  FolioReaderSharingProvider.swift
//  FolioReaderKit
//
//  Created by Heberti Almeida on 02/09/15.
//  Copyright (c) 2015 Folio Reader. All rights reserved.
//

import UIKit

class FolioReaderSharingProvider: UIActivityItemProvider {

    var subject: String!
    var text: String!
    var html: String?

    init(subject: String, text: String, html: String?) {
        self.subject = subject
        self.text = text
        if let ht = html {
            self.html = ht
        }
        super.init(placeholderItem: "")
    }

    override func activityViewController(activityViewController: UIActivityViewController, subjectForActivityType activityType: String?) -> String {
        return subject
    }

    override func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {

        if activityType == UIActivityTypeMail {
            if let html = html {
                return html
            } else {
                return text
            }
        }

        return text
    }
}

Remove unnecessary let-binding, use where clause

//
//  FolioReaderSharingProvider.swift
//  FolioReaderKit
//
//  Created by Heberti Almeida on 02/09/15.
//  Copyright (c) 2015 Folio Reader. All rights reserved.
//

import UIKit

class FolioReaderSharingProvider: UIActivityItemProvider {

    var subject: String
    var text: String
    var html: String?

    init(subject: String, text: String, html: String?) {
        self.subject = subject
        self.text = text
        self.html = html

        super.init(placeholderItem: "")
    }

    override func activityViewController(activityViewController: UIActivityViewController, subjectForActivityType activityType: String?) -> String {
        return subject
    }

    override func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
        if let html = html where activityType == UIActivityTypeMail {
            return html
        }

        return text
    }
}


//  Copyright (c) 2015 Rob Rix. All rights reserved.

final class InferenceTests: XCTestCase {
	func testGraphsWithoutReturnsHaveUnitType() {
		assert(constraints(Graph()).0, ==, .Unit)
	}

	func testGraphsWithOneParameterAndNoReturnsHaveFunctionTypeReturningUnit() {
		let generated = constraints(Graph(nodes: [Identifier(): .Parameter((0, .Unit))], edges: []))
		assert(simplify(generated.0), == ,.function(0, .Unit))
	}
}

private func simplify(type: Term) -> Term {
	return Substitution(lazy(enumerate(type.freeVariables |> (flip(sorted) <| { $0.value < $1.value }))).map { ($1, Term(integerLiteral: $0)) }).apply(type)
}

import Assertions
import Manifold
import Prelude
import TesseractCore
import XCTest

Add a helper to extract the simplified type from constructed constraints.

//  Copyright (c) 2015 Rob Rix. All rights reserved.

final class InferenceTests: XCTestCase {
	func testGraphsWithoutReturnsHaveUnitType() {
		assert(constraints(Graph()).0, ==, .Unit)
	}

	func testGraphsWithOneParameterAndNoReturnsHaveFunctionTypeReturningUnit() {
		let generated = constraints(Graph(nodes: [Identifier(): .Parameter((0, .Unit))], edges: []))
		assert(simplify(generated.0), == ,.function(0, .Unit))
	}
}

private func type(graph: Graph<Node>) -> Term {
	return simplify(constraints(graph).0)
}

private func simplify(type: Term) -> Term {
	return Substitution(lazy(enumerate(type.freeVariables |> (flip(sorted) <| { $0.value < $1.value }))).map { ($1, Term(integerLiteral: $0)) }).apply(type)
}

import Assertions
import Manifold
import Prelude
import TesseractCore
import XCTest


//
//  Union.swift
//  Union
//
//  Created by Hirohisa Kawasaki on 2/19/15.
//  Copyright (c) 2015 Hirohisa Kawasaki. All rights reserved.
//

import UIKit

public enum Error: ErrorType {
    case AnimationPreviousNotIncludedInAnimations
}

public protocol Delegate {
    func animationsBeforeTransitionTo(viewController: UIViewController) -> [Animation]
    func animationsDuringTransitionFrom(viewController: UIViewController) -> [Animation]
}

extension Delegate {

    func animationsBeforeTransitionTo(viewController: UIViewController) -> [Animation] {
        return []
    }
    func animationsDuringTransitionFrom(viewController: UIViewController) -> [Animation] {
        return []
    }
}

Add arguments from and to viewControllers in Delegate

//
//  Union.swift
//  Union
//
//  Created by Hirohisa Kawasaki on 2/19/15.
//  Copyright (c) 2015 Hirohisa Kawasaki. All rights reserved.
//

import UIKit

public enum Error: ErrorType {
    case AnimationPreviousNotIncludedInAnimations
}

public protocol Delegate {
    func animationsBeforeTransition(from fromViewController: UIViewController, to toViewController: UIViewController) -> [Animation]
    func animationsDuringTransition(from fromViewController: UIViewController, to toViewController: UIViewController) -> [Animation]
}

extension Delegate {

    func animationsBeforeTransition(from fromViewController: UIViewController, to toViewController: UIViewController) -> [Animation] {
        return []
    }
    func animationsDuringTransition(from fromViewController: UIViewController, to toViewController: UIViewController) -> [Animation] {
        return []
    }
}


// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource) -parse -I %S/Inputs/no-import-objc %s -verify

// REQUIRES: objc_interop

// Note that we don't import ObjectiveC.
import People

class MyFrank : Frank {
  override func frank() {}
}

Fix importer test to not use 'nosource'.

// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -I %S/Inputs/no-import-objc %s -verify

// REQUIRES: objc_interop

// Note that we don't import ObjectiveC.
import People

class MyFrank : Frank {
  override func frank() {}
}


//
//  CalcupadUITests.swift
//  CalcupadUITests
//
//  Created by Will Kwon on 7/30/16.
//  Copyright © 2016 Will Kwon. All rights reserved.
//

import XCTest

class CalcupadUITests: XCTestCase {
    var app = XCUIApplication()

    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        XCUIApplication().launch()
        app = XCUIApplication()
    }

    override func tearDown() {
        super.tearDown()
    }

    func testAddition() {
        app.buttons["3"].tap()
        app.buttons["+"].tap()
        app.buttons["6"].tap()
        app.buttons["="].tap()
        let resultLabelValue = app.staticTexts.element(matching: .any, identifier: "Results").label

        XCTAssertEqual(resultLabelValue, "9")
    }

    func testMultiply() {
        app.buttons["2"].tap()
        app.buttons["×"].tap()
        app.buttons["3"].tap()
        app.buttons["="].tap()
        let resultLabelValue = app.staticTexts.element(matching: .any, identifier: "Results").label

        XCTAssertEqual(resultLabelValue, "6")
    }
}

Add test to handle continuation of equation from solution

//
//  CalcupadUITests.swift
//  CalcupadUITests
//
//  Created by Will Kwon on 7/30/16.
//  Copyright © 2016 Will Kwon. All rights reserved.
//

import XCTest

class CalcupadUITests: XCTestCase {
    var app = XCUIApplication()

    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        XCUIApplication().launch()
        app = XCUIApplication()
    }

    override func tearDown() {
        super.tearDown()
    }

    func testAddition() {
        app.buttons["3"].tap()
        app.buttons["+"].tap()
        app.buttons["6"].tap()
        app.buttons["="].tap()
        let resultLabelValue = app.staticTexts.element(matching: .any, identifier: "Results").label

        XCTAssertEqual(resultLabelValue, "9")
    }

    func testMultiply() {
        app.buttons["2"].tap()
        app.buttons["×"].tap()
        app.buttons["3"].tap()
        app.buttons["="].tap()
        let resultLabelValue = app.staticTexts.element(matching: .any, identifier: "Results").label

        XCTAssertEqual(resultLabelValue, "6")
    }

    func testContinuationOfEquationAfterSolution() {
        app.buttons["2"].tap()
        app.buttons["×"].tap()
        app.buttons["3"].tap()
        app.buttons["="].tap()
        app.buttons["×"].tap()
        app.buttons["2"].tap()
        app.buttons["="].tap()
        let resultLabelValue = app.staticTexts.element(matching: .any, identifier: "Results").label

        XCTAssertEqual(resultLabelValue, "12")
    }
}


//
//  UrlImporter.swift
//  Vandelay
//
//  Created by Daniel Saidi on 2016-08-31.
//  Copyright © 2016 Daniel Saidi. All rights reserved.
//

/*

 This exporter can import strings and data from custom
 urls, e.g. a file on the Internet, a REST api etc.

 */

import UIKit

public class UrlImporter: NSObject, DataImporter, StringImporter {

    // MARK: Initialization

    public init(url: NSURL) {
        self.url = url
        super.init()
    }

    // MARK: Properties

    public private(set) var importMethod = "URL"

    private var url: NSURL

    // MARK: Public functions

    public func importData(completion: ((result: ImportResult) -> ())?) {
        do {
            let data = try NSData(contentsOfURL: url)
            if (data != nil) {
                completion?(result: getResultWithData(data!))
            } else {
                completion?(result: self.getResultWithErrorMessage("No data in url \(url)"))
            }
        } catch {
            completion?(result: self.getResultWithError(error as NSError))
        }
    }

    public func importString(completion: ((result: ImportResult) -> ())?) {
        do {
            let string = try String(contentsOfURL: url)
            completion?(result: getResultWithString(string))
        } catch {
            completion?(result: self.getResultWithError(error as NSError))
        }
    }
}

Make url importer use NSURLSession

//
//  UrlImporter.swift
//  Vandelay
//
//  Created by Daniel Saidi on 2016-08-31.
//  Copyright © 2016 Daniel Saidi. All rights reserved.
//

/*

 This exporter can import strings and data from custom
 urls, e.g. a file on the Internet, a REST api etc.

 */

import Foundation

public class UrlImporter: NSObject, DataImporter {

    // MARK: Initialization

    public init(url: NSURL) {
        self.url = url
        super.init()
    }

    // MARK: Properties

    public private(set) var importMethod = "URL"

    private var url: NSURL

    // MARK: Public functions

    public func importData(completion: ((result: ImportResult) -> ())?) {
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url) { (data, response, error) in
            if (error != nil) {
                completion?(result: self.getResultWithError(error!))
            } else if (data != nil) {
                completion?(result: self.getResultWithData(data!))
            } else {
                completion?(result: self.getResultWithErrorMessage("No data in url \(self.url)"))
            }
        }
        task.resume()
    }
}


//: # Swinject Sample for iOS

import UIKit
import Swinject

//: ## Basic Use

protocol AnimalType {
    var name: String? { get }
}

class Cat: AnimalType {
    let name: String?

    init(name: String?) {
        self.name = name
    }
}

protocol PersonType {
    func play() -> String
}

class PetOwner: PersonType {
    let pet: AnimalType

    init(pet: AnimalType) {
        self.pet = pet
    }

    func play() -> String {
        let name = pet.name ?? "someone"
        return "I'm playing with \(name)."
    }
}

let container = Container()
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
container.register(PersonType.self) { r in
    PetOwner(pet: r.resolve(AnimalType.self)!)
}

let person = container.resolve(PersonType.self)!
print(person.play())

Add a named registration example to the playground.

/*:
# Swinject Sample for iOS
*/

import Swinject

/*:
## Basic Use
*/

protocol AnimalType {
    var name: String? { get }
    func sound() -> String
}

class Cat: AnimalType {
    let name: String?

    init(name: String?) {
        self.name = name
    }

    func sound() -> String {
        return "Meow!"
    }
}

protocol PersonType {
    func play() -> String
}

class PetOwner: PersonType {
    let pet: AnimalType

    init(pet: AnimalType) {
        self.pet = pet
    }

    func play() -> String {
        let name = pet.name ?? "someone"
        return "I'm playing with \(name). \(pet.sound())"
    }
}

// Create a container and register service and component pairs.
let container = Container()
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
container.register(PersonType.self) { r in PetOwner(pet: r.resolve(AnimalType.self)!) }

// The person is resolved to a PetOwner with a Cat.
let person = container.resolve(PersonType.self)!
print(person.play())

/*:
## Named Registration
*/

class Dog: AnimalType {
    let name: String?

    init(name: String?) {
        self.name = name
    }

    func sound() -> String {
        return "Bow wow!"
    }
}

// Add more registrations to the container already containing the PetOwner with the Cat.
container.register(AnimalType.self, name: "dog") { _ in Dog(name: "Hachi") }
container.register(PersonType.self, name: "doggy") { r in PetOwner(pet: r.resolve(AnimalType.self, name: "dog")!) }

// Resolve the service with the registration name to differentiate from the cat owner.
let doggyPerson = container.resolve(PersonType.self, name:"doggy")!
print(doggyPerson.play())


//
//  Theme.swift
//  SwiftyPress
//
//  Created by Basem Emara on 2018-10-06.
//  Copyright © 2019 Zamzam Inc. All rights reserved.
//

import UIKit

public protocol Theme {
    var tint: UIColor { get }
    var secondaryTint: UIColor { get }

    var backgroundColor: UIColor { get }
    var secondaryBackgroundColor: UIColor { get }
    var tertiaryBackgroundColor: UIColor { get }

    var separatorColor: UIColor { get }
    var opaqueColor: UIColor { get }

    var labelColor: UIColor { get }
    var secondaryLabelColor: UIColor { get }
    var tertiaryLabelColor: UIColor { get }
    var quaternaryLabelColor: UIColor { get }
    var placeholderLabelColor: UIColor { get }

    var buttonCornerRadius: CGFloat { get }

    var positiveColor: UIColor { get }
    var negativeColor: UIColor { get }

    var isDarkStyle: Bool { get }

    #if os(iOS)
    func apply(for application: UIApplication)
    #else
    func apply()
    #endif
}

public extension Theme {

    #if os(iOS)

    var statusBarStyle: UIStatusBarStyle {
        return isDarkStyle ? .lightContent : .default
    }

    var barStyle: UIBarStyle {
        return isDarkStyle ? .black : .default
    }

    var keyboardAppearance: UIKeyboardAppearance {
        return isDarkStyle ? .dark : .default
    }
    #endif
}

Add extra background color for theme

//
//  Theme.swift
//  SwiftyPress
//
//  Created by Basem Emara on 2018-10-06.
//  Copyright © 2019 Zamzam Inc. All rights reserved.
//

import UIKit

public protocol Theme {
    var tint: UIColor { get }
    var secondaryTint: UIColor { get }

    var backgroundColor: UIColor { get }
    var secondaryBackgroundColor: UIColor { get }
    var tertiaryBackgroundColor: UIColor { get }
    var quaternaryBackgroundColor: UIColor { get }

    var separatorColor: UIColor { get }
    var opaqueColor: UIColor { get }

    var labelColor: UIColor { get }
    var secondaryLabelColor: UIColor { get }
    var tertiaryLabelColor: UIColor { get }
    var quaternaryLabelColor: UIColor { get }
    var placeholderLabelColor: UIColor { get }

    var buttonCornerRadius: CGFloat { get }

    var positiveColor: UIColor { get }
    var negativeColor: UIColor { get }

    var isDarkStyle: Bool { get }

    #if os(iOS)
    func apply(for application: UIApplication)
    #else
    func apply()
    #endif
}

public extension Theme {

    #if os(iOS)

    var statusBarStyle: UIStatusBarStyle {
        return isDarkStyle ? .lightContent : .default
    }

    var barStyle: UIBarStyle {
        return isDarkStyle ? .black : .default
    }

    var keyboardAppearance: UIKeyboardAppearance {
        return isDarkStyle ? .dark : .default
    }
    #endif
}


import UIKit

let CellId = "PlaylistCell"

class PlaylistViewController: UICollectionViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
  let dataSource = PlaylistDataSource()
  let trackService = AbletonTrackService()

  // MARK: UIViewController

  override func viewDidLoad() {
    super.viewDidLoad()
    collectionView!.backgroundColor = UIColor.whiteColor()
  }

  // MARK: UICollectionViewDelegate

  override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    println("TODO play track")
  }

  // MARK: UICollectionViewDelegateFlowLayout

  func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: collectionView.bounds.width, height: 100)
  }

  // MARK: Init & dealloc

  override init() {
    super.init(collectionViewLayout: UICollectionViewFlowLayout())
    collectionView!.registerClass(PlaylistCell.self, forCellWithReuseIdentifier: CellId)
    collectionView!.dataSource = dataSource

    trackService.listTracks { tracks in
      self.dataSource.tracks = tracks
      self.collectionView!.reloadData()
    }
  }

  required init(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

Print track to be played

import UIKit

let CellId = "PlaylistCell"

class PlaylistViewController: UICollectionViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
  let dataSource = PlaylistDataSource()
  let trackService = AbletonTrackService()

  // MARK: UIViewController

  override func viewDidLoad() {
    super.viewDidLoad()
    collectionView!.backgroundColor = UIColor.whiteColor()
  }

  // MARK: UICollectionViewDelegate

  override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let track = dataSource.tracks[indexPath.indexAtPosition(1)]
    println("TODO play track \(track)")
  }

  // MARK: UICollectionViewDelegateFlowLayout

  func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: collectionView.bounds.width, height: 100)
  }

  // MARK: Init & dealloc

  override init() {
    super.init(collectionViewLayout: UICollectionViewFlowLayout())
    collectionView!.registerClass(PlaylistCell.self, forCellWithReuseIdentifier: CellId)
    collectionView!.dataSource = dataSource

    trackService.listTracks { tracks in
      self.dataSource.tracks = tracks
      self.collectionView!.reloadData()
    }
  }

  required init(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}


//
//  ImagesColorTest.swift
//  MochaUtilities
//
//  Created by Gregory Sholl e Santos on 09/06/17.
//  Copyright © 2017 CocoaPods. All rights reserved.
//

import XCTest

class ImagesColorTest: XCTestCase {

    override func setUp() {
        super.setUp()

        // Put setup code here. This method is called before the invocation of each test method in the class.

        // In UI tests it is usually best to stop immediately when a failure occurs.
        continueAfterFailure = false
        // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
        if #available(iOS 9.0, *) {
            XCUIApplication().launch()
        } else {
            // Fallback on earlier versions
        }

        // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // Use recording to get started writing UI tests.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

}

Remove code from color extension test class

//
//  ImagesColorTest.swift
//  MochaUtilities
//
//  Created by Gregory Sholl e Santos on 09/06/17.
//  Copyright © 2017 CocoaPods. All rights reserved.
//

import XCTest

class ImagesColorTest: XCTestCase {

    override func setUp() {
        super.setUp()
    }

    override func tearDown() {
        super.tearDown()
    }
}


//
//  FileKit.swift
//  FileKit
//
//  Created by Nikolai Vazquez on 9/1/15.
//  Copyright © 2015 Nikolai Vazquez. All rights reserved.
//

import Foundation

public class File: StringLiteralConvertible {

    // MARK: - File

    public var path: Path

    public init(path: Path) {
        self.path = path
    }

    func moveToPath(path: Path) throws {
        try NSFileManager.defaultManager().moveItemAtPath(path._path, toPath: path._path)
        self.path = path
    }

    // MARK: - StringLiteralConvertible

    public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType

    public typealias UnicodeScalarLiteralType = StringLiteralType

    public required init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
        path = Path(value)
    }

    public required init(stringLiteral value: StringLiteralType) {
        path = Path(value)
    }

    public required init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
        path = Path(value)
    }

}

Add delete() method to File

//
//  FileKit.swift
//  FileKit
//
//  Created by Nikolai Vazquez on 9/1/15.
//  Copyright © 2015 Nikolai Vazquez. All rights reserved.
//

import Foundation

public class File: StringLiteralConvertible {

    // MARK: - File

    public var path: Path

    public init(path: Path) {
        self.path = path
    }

    func delete() throws {
        try NSFileManager.defaultManager().removeItemAtPath(path._path)
    }

    func moveToPath(path: Path) throws {
        try NSFileManager.defaultManager().moveItemAtPath(path._path, toPath: path._path)
        self.path = path
    }

    // MARK: - StringLiteralConvertible

    public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType

    public typealias UnicodeScalarLiteralType = StringLiteralType

    public required init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
        path = Path(value)
    }

    public required init(stringLiteral value: StringLiteralType) {
        path = Path(value)
    }

    public required init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
        path = Path(value)
    }

}


import Nimble

expect(1 + 1).to(equal(3))

Implement basic Nimble assertion handler

import Nimble

class NimbleAssertionHandlerAdapter: AssertionHandler {
  func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) {
    if assertion { return }

    println(message.stringValue)
    println("  \(location.description)\n")
  }
}

NimbleAssertionHandler = NimbleAssertionHandlerAdapter()

expect(1 + 1).to(equal(3))


//
//  AKDevice.swift
//  AudioKit
//
//  Created by Stéphane Peter on 2/8/16.
//  Copyright © 2016 AudioKit. All rights reserved.
//

import Foundation
import AVFoundation

/// Wrapper for audio device selection
@objc public class AKDevice : NSObject {
    /// The human-readable name for the device.
    public var name: String

    #if os(OSX)

    /// The device identifier.
    public private(set) var deviceID: AudioDeviceID

    #else

    /// The device identifier.
    public private(set) var deviceID: String

    #endif

    #if os(OSX)

    /// Initialize the device
    ///
    /// - parameter name: The human-readable name for the device.
    /// - paramter deviceID: The device identifier.
    ///
    public init(name: String, deviceID: AudioDeviceID) {
        self.name = name
        self.deviceID = deviceID
        super.init()
    }

    #else

    /// Initialize the device
    ///
    /// - parameter name: The human-readable name for the device.
    /// - paramter deviceID: The device identifier.
    ///
    public init(name: String, deviceID: String) {
        self.name = name
        self.deviceID = deviceID
        super.init()
    }

    #endif

    /// Printable device description
    public override var description: String {
        return "<Device: \(name) (\(deviceID))>"
    }
}

Use typealias instead of making multiple inits for different OSes

//
//  AKDevice.swift
//  AudioKit
//
//  Created by Stéphane Peter on 2/8/16.
//  Copyright © 2016 AudioKit. All rights reserved.
//

import Foundation
import AVFoundation

#if os(OSX)
public typealias DeviceID = AudioDeviceID
#else
public typealias DeviceID = String
#endif

/// Wrapper for audio device selection
@objc public class AKDevice : NSObject {
    /// The human-readable name for the device.
    public var name: String

    /// The device identifier.
    public private(set) var deviceID: DeviceID

    /// Initialize the device
    ///
    /// - parameter name: The human-readable name for the device.
    /// - parameter deviceID: The device identifier.
    ///
    public init(name: String, deviceID: DeviceID) {
        self.name = name
        self.deviceID = deviceID
        super.init()
    }

    /// Printable device description
    public override var description: String {
        return "<Device: \(name) (\(deviceID))>"
    }
}


//
//  UIBarButtonItem.swift
//  ZamzamUI
//
//  Created by Basem Emara on 5/3/16.
//  Copyright © 2016 Zamzam Inc. All rights reserved.
//

#if os(iOS)
import UIKit

public extension UIBarButtonItem {

    /// Initializes a UIBarButtonItem with an image more conveniently.
    ///
    /// - Parameters:
    ///   - imageName: Image name.
    ///   - bundle: The bundle containing the image file or asset catalog. Specify nil to search the app's main bundle.
    ///   - target: Target of the context.
    ///   - action: Action to trigger.
    convenience init(imageName: String, inBundle bundle: Bundle? = nil, target: Any?, action: Selector) {
        self.init(
            image: UIImage(
                named: imageName,
                inBundle: bundle
            ),
            style: .plain,
            target: target,
            action: action
        )
    }
}
#endif

Add bacck bar button factory

//
//  UIBarButtonItem.swift
//  ZamzamUI
//
//  Created by Basem Emara on 5/3/16.
//  Copyright © 2016 Zamzam Inc. All rights reserved.
//

#if os(iOS)
import UIKit

public extension UIBarButtonItem {

    /// Initializes a `UIBarButtonItem` with an image more conveniently.
    ///
    /// - Parameters:
    ///   - imageName: Image name.
    ///   - bundle: The bundle containing the image file or asset catalog. Specify nil to search the app's main bundle.
    ///   - target: Target of the context.
    ///   - action: Action to trigger.
    convenience init(imageName: String, inBundle bundle: Bundle? = nil, target: Any?, action: Selector) {
        self.init(
            image: UIImage(
                named: imageName,
                inBundle: bundle
            ),
            style: .plain,
            target: target,
            action: action
        )
    }
}

public extension UIBarButtonItem {

    /// Initializes a blank back `UIBarButtonItem` conveniently.
    static func makeBackBarButtonItem() -> UIBarButtonItem {
        UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }
}
#endif


//
//  RACHelpers.swift
//  TodaysReactiveMenu
//
//  Created by Steffen Damtoft Sommer on 25/05/15.
//  Copyright (c) 2015 steffendsommer. All rights reserved.
//

import Foundation
import ReactiveCocoa

public func ignoreNil<T: AnyObject, E: Any>(signalProducer: SignalProducer<T?, E>) -> SignalProducer<T?, E> {
	return signalProducer
        |> filter { value in
            value != nil
        }
}

public func ignoreError<T: Any, E: ErrorType>(signalProducer: SignalProducer<T, E>) -> SignalProducer<T, NoError> {
    return signalProducer
        |> catch { _ in
            SignalProducer<T, NoError>.empty
        }
}

public func merge<T, E: ErrorType>(signals: [SignalProducer<T, E>]) -> SignalProducer<T, E> {
    return SignalProducer<SignalProducer<T, E>, E>(values: signals)
        |> flatten(FlattenStrategy.Merge)
}

Remove constraints to generic arguments

//
//  RACHelpers.swift
//  TodaysReactiveMenu
//
//  Created by Steffen Damtoft Sommer on 25/05/15.
//  Copyright (c) 2015 steffendsommer. All rights reserved.
//

import ReactiveCocoa

public func ignoreNil<T: AnyObject, E: Any>(signalProducer: SignalProducer<T?, E>) -> SignalProducer<T?, E> {
	return signalProducer
        |> filter { value in
            value != nil
        }
}

public func ignoreError<T: Any, E: ErrorType>(signalProducer: SignalProducer<T, E>) -> SignalProducer<T, NoError> {
public func ignoreError<T, E>(signalProducer: SignalProducer<T, E>) -> SignalProducer<T, NoError> {
    return signalProducer
        |> catch { _ in
            SignalProducer<T, NoError>.empty
        }
}

public func merge<T, E>(signals: [SignalProducer<T, E>]) -> SignalProducer<T, E> {
    return SignalProducer<SignalProducer<T, E>, E>(values: signals)
        |> flatten(.Merge)
}


//
//  LoginViewController.swift
//  MacAssistant
//
//  Created by Vansh on 4/27/17.
//  Copyright © 2017 vanshgandhi. All rights reserved.
//

import Cocoa
import WebKit

class LoginViewController: NSViewController, WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!
    private let authenticator = Authenticator()

    override func viewDidLoad() {
        super.viewDidLoad()
        loadLoginUrl()
        webView.navigationDelegate = self
        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let url = navigationAction.request.url?.absoluteString {
            if url.hasPrefix("http://localhost") { // TODO: Un-hardcode this
                decisionHandler(.cancel)
                if let index = url.characters.index(of: "=") {
                    let code = url.substring(from: url.index(index, offsetBy: 1))
                    authenticator.authenticate(code: code)
                }
                loadLoginUrl() // To reset the WebView if user later logs out

                // TODO: Completely dismiss this viewcontroller on authentication

                return
            }
        }
        decisionHandler(.allow)
    }

    func loadLoginUrl() {
        webView.load(URLRequest(url: URL(string: authenticator.loginUrl)!))
    }
}

Update string ops to Swift4

//
//  LoginViewController.swift
//  MacAssistant
//
//  Created by Vansh on 4/27/17.
//  Copyright © 2017 vanshgandhi. All rights reserved.
//

import Cocoa
import WebKit

class LoginViewController: NSViewController, WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!
    private let authenticator = Authenticator()

    override func viewDidLoad() {
        super.viewDidLoad()
        loadLoginUrl()
        webView.navigationDelegate = self
        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let url = navigationAction.request.url?.absoluteString {
            if url.hasPrefix("http://localhost") { // TODO: Un-hardcode this
                decisionHandler(.cancel)
                if let index = url.index(of: "=") {
                    let code = String(url[url.index(index, offsetBy: 1)...])
                    authenticator.authenticate(code: code)
                }
                loadLoginUrl() // To reset the WebView if user later logs out

                // TODO: Completely dismiss this viewcontroller on authentication

                return
            }
        }
        decisionHandler(.allow)
    }

    func loadLoginUrl() {
        webView.load(URLRequest(url: URL(string: authenticator.loginUrl)!))
    }
}


public protocol ObservablePropertyType {
    typealias ValueType
    var value: ValueType { get set }
}

public class ObservableProperty<ValueType> {
    public typealias CallbackType = (ValueType -> ())
    private var _value: ValueType
    private var subscriptions = [CallbackType]()

    public var value: ValueType {
        get {
            return self._value
        }
        set {
            self._value = newValue
            notifySubscriptions()
        }
    }

    public init(_ value: ValueType) {
        self._value = value
    }

    public func subscribe(callback: CallbackType) {
        subscriptions.append(callback)
    }

    private func notifySubscriptions() {
        for subscription in subscriptions {
            subscription(value)
        }
    }
}

extension ObservableProperty: ObservablePropertyType { }

Use didSet instead of a private var

public protocol ObservablePropertyType {
    typealias ValueType
    var value: ValueType { get set }
}

public class ObservableProperty<ValueType> {
    public typealias CallbackType = (ValueType -> ())

    private var subscriptions = [CallbackType]()

    public var value: ValueType {
        didSet {
            notifySubscriptions()
        }
    }

    public init(_ value: ValueType) {
        self.value = value
    }

    public func subscribe(callback: CallbackType) {
        subscriptions.append(callback)
    }

    private func notifySubscriptions() {
        for subscription in subscriptions {
            subscription(value)
        }
    }
}

extension ObservableProperty: ObservablePropertyType { }


import PackageDescription

let package = Package(
  name: "GPXKit"
)

Add the AEXML dependency to the package.

import PackageDescription

let package = Package(
  name: "GPXKit",
  dependencies: [
    .Package(url: "https://github.com/fousa/AEXML.git", majorVersion: 2, minor: 1)
  ]
)


//
//  Store.swift
//  ReactiveReSwift
//
//  Created by Charlotte Tortorella on 11/17/16.
//  Copyright © 2016 Benjamin Encz. All rights reserved.
//

import Foundation

open class Store<ObservableProperty: ObservablePropertyType> where ObservableProperty.ValueType: StateType {

    public typealias StoreMiddleware = Middleware<ObservableProperty.ValueType>
    public typealias StoreReducer = Reducer<ObservableProperty.ValueType>

    public private(set) var observable: ObservableProperty
    private let middleware: StoreMiddleware
    private let reducer: StoreReducer
    private let disposeBag = SubscriptionReferenceBag()

    public required init(reducer: StoreReducer, observable: ObservableProperty, middleware: StoreMiddleware = Middleware()) {
        self.reducer = reducer
        self.observable = observable
        self.middleware = middleware
    }

    public func dispatch(_ actions: Action...) {
        actions.flatMap { action in
            middleware.transform({ self.observable.value }, self.dispatch, action)
        }.forEach { action in
            observable.value = reducer.transform(action, observable.value)
        }
    }

    public func dispatch<S: StreamType>(_ stream: S) where S.ValueType: Action {
        disposeBag += stream.subscribe { [unowned self] action in
            self.dispatch(action)
        }
    }
}

Change dispatch from using flatMap + forEach to using two forEach statements instead

//
//  Store.swift
//  ReactiveReSwift
//
//  Created by Charlotte Tortorella on 11/17/16.
//  Copyright © 2016 Benjamin Encz. All rights reserved.
//

import Foundation

open class Store<ObservableProperty: ObservablePropertyType> where ObservableProperty.ValueType: StateType {

    public typealias StoreMiddleware = Middleware<ObservableProperty.ValueType>
    public typealias StoreReducer = Reducer<ObservableProperty.ValueType>

    public private(set) var observable: ObservableProperty
    private let middleware: StoreMiddleware
    private let reducer: StoreReducer
    private let disposeBag = SubscriptionReferenceBag()

    public required init(reducer: StoreReducer, observable: ObservableProperty, middleware: StoreMiddleware = Middleware()) {
        self.reducer = reducer
        self.observable = observable
        self.middleware = middleware
    }

    public func dispatch(_ actions: Action...) {
        actions.forEach { action in
            middleware.transform({ self.observable.value }, self.dispatch, action).forEach { action in
                observable.value = reducer.transform(action, observable.value)
            }
        }
    }

    public func dispatch<S: StreamType>(_ stream: S) where S.ValueType: Action {
        disposeBag += stream.subscribe { [unowned self] action in
            self.dispatch(action)
        }
    }
}


import XCTest
import Syft

class SequenceTests: XCTestCase {

    func test_bothElementsMatchInput_sequenceMatches() {

        let first = Syft.Match("abc")
        let second = Syft.Match("def")

        let actual = Syft.Sequence(first, second).parse("abcdefghi")

        let expected = MatchResult.Success(match: "abcdef", remainder: "ghi")
        XCTAssertEqual(expected, actual)
    }

    func test_firstElementDoesNotMatchInput_sequenceDoesNotMatch() {

        let first = Syft.Match("abc")
        let second = Syft.Match("def")

        let actual = Syft.Sequence(first, second).parse("zdef")

        let expected = MatchResult.Failure(remainder: "zdef")
        XCTAssertEqual(expected, actual)
    }

    func test_secondElementDoesNotMatchInput_sequenceDoesNotMatch() {

        let first = Syft.Match("abc")
        let second = Syft.Match("def")

        let actual = Syft.Sequence(first, second).parse("abcz")

        let expected = MatchResult.Failure(remainder: "abcz")
        XCTAssertEqual(expected, actual)
    }
}

Test for sequence exactly matching the input.

import XCTest
import Syft

class SequenceTests: XCTestCase {

    func test_bothElementsMatchPrefixOfInput_sequenceMatches() {

        let first = Syft.Match("abc")
        let second = Syft.Match("def")

        let actual = Syft.Sequence(first, second).parse("abcdefghi")

        let expected = MatchResult.Success(match: "abcdef", remainder: "ghi")
        XCTAssertEqual(expected, actual)
    }

    func test_bothElementsExactlyMatchInput_sequenceMatches() {

        let first = Syft.Match("abc")
        let second = Syft.Match("def")

        let actual = Syft.Sequence(first, second).parse("abcdef")

        let expected = MatchResult.Success(match: "abcdef", remainder: "")
        XCTAssertEqual(expected, actual)
    }

    func test_firstElementDoesNotMatchInput_sequenceDoesNotMatch() {

        let first = Syft.Match("abc")
        let second = Syft.Match("def")

        let actual = Syft.Sequence(first, second).parse("zdef")

        let expected = MatchResult.Failure(remainder: "zdef")
        XCTAssertEqual(expected, actual)
    }

    func test_secondElementDoesNotMatchInput_sequenceDoesNotMatch() {

        let first = Syft.Match("abc")
        let second = Syft.Match("def")

        let actual = Syft.Sequence(first, second).parse("abcz")

        let expected = MatchResult.Failure(remainder: "abcz")
        XCTAssertEqual(expected, actual)
    }
}


//  FightingFantasy
//  Created by Tony Smith on 29/10/2017.
//  Copyright © 2017 Tony Smith. All rights reserved.

import Cocoa

class FFIconButton: NSButton {

    var index: Int = 1

}

Add property for the icons image array; respond to icon setting notifications by specific button; send the index of the selected image to the app delegate

//  FightingFantasy
//  Created by Tony Smith on 29/10/2017.
//  Copyright © 2017 Tony Smith. All rights reserved.

import Cocoa

class FFIconButton: NSButton {

    // Class properties
    // 'index' is the index of the button's icon within the 'icons' array
    // 'icons' is an array of NSImages for the backpack item icons
    // NOTE We use NSMutableArray so we can set the value of 'icons' as a reference
    var index: Int = 1
    var icons: NSMutableArray = NSMutableArray.init()

    override func awakeFromNib() {

        // Set up notifications
        // 'select.image' is sent by the popover controller (FFViewController) when an icon is selected
        let nc = NotificationCenter.default
        nc.addObserver(self, selector: #selector(setButton), name: NSNotification.Name(rawValue: "select.image"), object: nil)
    }

    @objc func setButton(_ note: Notification) {

        // When we receive a notification from the popover controller that an icon has been selected,
        // we come here and set the button's image to that icon
        let obj = note.object
        if obj != nil {
            // Decode the notifiction object
            let array = obj as! NSMutableArray
            let sender = array.object(at: 1) as! FFIconButton

            // Only change the icon of the button that was actually clicked on
            if sender == self {
                let item = array.object(at: 0) as! FFCollectionViewItem
                if let image = icons.object(at: item.index) as? NSImage { self.image = image }
                self.index = item.index

                // Add the index of the image in 'icons' back to the array
                array.add(NSNumber.init(value: item.index))

                // Send the array on to the App Delegate so that the pack item's icon record can
                // also be changed (see AppDelegate.updatePack() )
                let nc = NotificationCenter.default
                nc.post(name: NSNotification.Name(rawValue: "set.pack.item.index") , object: array)
            }
        }
    }

}


//
//  StoreSpec.swift
//  HabitsTests
//
//  Created by Julian Grosshauser on 26/09/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import Quick
import Nimble
@testable import Habits

class StoreSpec: QuickSpec {}

Set up store before running tests

//
//  StoreSpec.swift
//  HabitsTests
//
//  Created by Julian Grosshauser on 26/09/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import Quick
import Nimble
import RealmSwift
@testable import Habits

class StoreSpec: QuickSpec {
    override func spec() {
        var store: Store!
        var realm: Realm!

        beforeSuite {
            do {
                realm = try Realm(configuration: Realm.Configuration(inMemoryIdentifier: "StoreSpec"))
                store = Store(realm: realm)
            } catch {
                XCTFail("Failed to initialize Realm: \(error)")
            }
        }

        describe("Store") {}
    }
}


//
//  UIApplication+SafeShared.swift
//  Pageboy
//
//  Created by Merrick Sapsford on 05/01/2018.
//  Copyright © 2018 Merrick Sapsford. All rights reserved.
//

import Foundation

internal extension UIApplication {

    static var safeShared: UIApplication? {
        guard #available(iOSApplicationExtension 8, *) else {
            return nil
        }

        guard UIApplication.responds(to: NSSelectorFromString("sharedApplication")),
            let unmanagedSharedApplication = UIApplication.perform(NSSelectorFromString("sharedApplication")) else {
            return nil
        }

        return unmanagedSharedApplication.takeRetainedValue() as? UIApplication
    }
}

Fix potential retain issue in UIApplication extension

//
//  UIApplication+SafeShared.swift
//  Pageboy
//
//  Created by Merrick Sapsford on 05/01/2018.
//  Copyright © 2018 Merrick Sapsford. All rights reserved.
//

import Foundation

internal extension UIApplication {

    static var safeShared: UIApplication? {
        guard #available(iOSApplicationExtension 8, *) else {
            return nil
        }

        guard UIApplication.responds(to: NSSelectorFromString("sharedApplication")),
            let unmanagedSharedApplication = UIApplication.perform(NSSelectorFromString("sharedApplication")) else {
            return nil
        }

        return unmanagedSharedApplication.takeUnretainedValue() as? UIApplication
    }
}


// Statically link a "hello world" program
// REQUIRES: OS=linux-gnu
// REQUIRES: static_stdlib
print("hello world!")
// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swiftc_driver -static-stdlib -o %t/static-stdlib %s
// RUN: %t/static-stdlib | %FileCheck %s
// RUN: ldd %t/static-stdlib | %FileCheck %s --check-prefix=LDD
// CHECK: hello world!
// LDD-NOT: libswiftCore.so

Disable Linux statically-linked stdlib test until it is fixed

// Statically link a "hello world" program
// REQUIRES: OS=linux-gnu
// REQUIRES: static_stdlib
// REQUIRES: rdar://30250347
print("hello world!")
// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swiftc_driver -static-stdlib -o %t/static-stdlib %s
// RUN: %t/static-stdlib | %FileCheck %s
// RUN: ldd %t/static-stdlib | %FileCheck %s --check-prefix=LDD
// CHECK: hello world!
// LDD-NOT: libswiftCore.so


// RUN: %target-swift-frontend -O -emit-sil %s | FileCheck %s

protocol DrawingElementDispatchType {}

extension DrawingElementDispatchType {
  final var boundingBox: Int32 {
    return 0
  }
}

protocol DrawingElementType : DrawingElementDispatchType {
  var boundingBox: Int32 {get}
}

struct D : DrawingElementType {
  var boundingBox: Int32 = 42
}

// Check that that boundingBox is devirtualized and inlined.
// CHECK: sil @{{.*}}test1111
// bb0:
// CHECK-NOT: class_method
// CHECK-NOT: witness_method
// CHECK: integer_literal $Builtin.Int32, 42
// CHECK-NOT: class_method
// CHECK-NOT: witness_method
// CHECK-NOT: bb1
// return
public func test1111() -> Int32 {
  return (D() as DrawingElementType).boundingBox
}

Make sure test case does not collide with private discriminators.

// RUN: %target-swift-frontend -O -emit-sil %s | FileCheck %s

protocol DrawingElementDispatchType {}

extension DrawingElementDispatchType {
  final var boundingBox: Int32 {
    return 0
  }
}

protocol DrawingElementType : DrawingElementDispatchType {
  var boundingBox: Int32 {get}
}

struct D : DrawingElementType {
  var boundingBox: Int32 = 42
}

// Check that that boundingBox is devirtualized and inlined.
// CHECK: sil @{{.*}}test1111
// bb0:
// CHECK-NOT: class_method
// CHECK-NOT: witness_method
// CHECK: integer_literal $Builtin.Int32, 42
// CHECK-NOT: class_method
// CHECK-NOT: witness_method
// CHECK-NOT: bb1:
// return
public func test1111() -> Int32 {
  return (D() as DrawingElementType).boundingBox
}


import PackageDescription

let package = Package(
    name: "VaporApp",
    dependencies: [
        .Package(url: "https://github.com/tannernelson/vapor.git", majorVersion: 0),
        .Package(url: "https://github.com/tannernelson/vapor-stencil.git", majorVersion: 0),
        .Package(url: "https://github.com/stepanhruda/PostgreSQL-Swift.git", majorVersion: 0)
    ]

)

Move to custom pgsql repo

import PackageDescription

let package = Package(
    name: "VaporApp",
    dependencies: [
        .Package(url: "https://github.com/tannernelson/vapor.git", majorVersion: 0),
        .Package(url: "https://github.com/tannernelson/vapor-stencil.git", majorVersion: 0),
        .Package(url: "https://github.com/kylebshr/PostgreSQL-Swift.git", majorVersion: 0)
    ]

)


//
//  ProtoBufHubProxy.swift
//  SignalR-Swift
//
//
//  Copyright © 2017 Jordan Camara. All rights reserved.
//

import Foundation

public class ProtoBufHubProxy: ProtoBufHubProxyProtocol {

    public var state = [String: Any]()

    private var connection: HubConnectionProtocol!
    private var hubName: String?
    private var subscriptions = [String: ProtoBufSubscription]()

    // MARK: - Init

    public init(connection: HubConnectionProtocol, hubName: String) {
        self.connection = connection
        self.hubName = hubName
    }

    // MARK: - Subscribe

    public func on(eventName: String?, handler: @escaping ((_ args: [String: Any]) -> ())) -> ProtoBufSubscription? {
        guard eventName != nil && !eventName!.isEmpty else {
            NSException.raise(.invalidArgumentException, format: NSLocalizedString("Argument eventName is null", comment: "null event name exception"), arguments: getVaList(["nil"]))
            return nil
        }

        var subscription = self.subscriptions[eventName!]
        if subscription == nil {
            subscription = ProtoBufSubscription()
            subscription?.handler = handler
            self.subscriptions[eventName!] = subscription
        }

        return subscription!
    }

    public func invokeEvent(eventName: String, withArgs args: [String: Any]) {
        if let subscription = self.subscriptions[eventName], let handler = subscription.handler {
            handler(args)
        }
    }
}

Fix retain cycle between Connection <-> Proxy

//
//  ProtoBufHubProxy.swift
//  SignalR-Swift
//
//
//  Copyright © 2017 Jordan Camara. All rights reserved.
//

import Foundation

public class ProtoBufHubProxy: ProtoBufHubProxyProtocol {

    public var state = [String: Any]()

    private weak var connection: HubConnectionProtocol?
    private var hubName: String?
    private var subscriptions = [String: ProtoBufSubscription]()

    // MARK: - Init

    public init(connection: HubConnectionProtocol, hubName: String) {
        self.connection = connection
        self.hubName = hubName
    }

    // MARK: - Subscribe

    public func on(eventName: String?, handler: @escaping ((_ args: [String: Any]) -> ())) -> ProtoBufSubscription? {
        guard eventName != nil && !eventName!.isEmpty else {
            NSException.raise(.invalidArgumentException, format: NSLocalizedString("Argument eventName is null", comment: "null event name exception"), arguments: getVaList(["nil"]))
            return nil
        }

        var subscription = self.subscriptions[eventName!]
        if subscription == nil {
            subscription = ProtoBufSubscription()
            subscription?.handler = handler
            self.subscriptions[eventName!] = subscription
        }

        return subscription!
    }

    public func invokeEvent(eventName: String, withArgs args: [String: Any]) {
        if let subscription = self.subscriptions[eventName], let handler = subscription.handler {
            handler(args)
        }
    }
}


struct MyStruct {
  func labelNameParamName(label param: (inout Int) throws -> MyStruct) rethrows {}
  func labelName(label: (@autoclosure () -> Int) -> Int) {}
  func sameName(label label: Int) {}
  func paramName(_ param: Int) {}
  subscript(param: Int) -> Int { 1 }
  subscript(label param: Int) -> Int { 1 }
}
func test(value: MyStruct) {
  value
}

// RUN: %sourcekitd-test -req=complete -pos=10:8 -req-opts=annotateddescription=1 %s -- %s > %t.result
// RUN: diff -u %s.result %t.result

Use --strip-trailing-cr for diff test

struct MyStruct {
  func labelNameParamName(label param: (inout Int) throws -> MyStruct) rethrows {}
  func labelName(label: (@autoclosure () -> Int) -> Int) {}
  func sameName(label label: Int) {}
  func paramName(_ param: Int) {}
  subscript(param: Int) -> Int { 1 }
  subscript(label param: Int) -> Int { 1 }
}
func test(value: MyStruct) {
  value
}

// RUN: %sourcekitd-test -req=complete -pos=10:8 -req-opts=annotateddescription=1 %s -- %s > %t.result
// RUN: diff --strip-trailing-cr -u %s.result %t.result


import UIKit
import CoreData
import DATAStack

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    lazy var dataStack: DATAStack = DATAStack()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        application.setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)

        let appearance = UINavigationBar.appearance()
        appearance.barTintColor = UIColor(red:0.83, green:0.43, blue:0.36, alpha:1)
        appearance.titleTextAttributes = [NSFontAttributeName : UIFont(name: "AvenirNext-DemiBold", size: 20)!,
            NSForegroundColorAttributeName : UIColor.whiteColor()]

        window = UIWindow(frame: UIScreen.mainScreen().bounds)

        let initialViewController = ViewController(dataStack: dataStack)

        window?.rootViewController = UINavigationController(rootViewController: initialViewController)
        window?.makeKeyAndVisible()

        return true
    }

    func applicationWillTerminate(application: UIApplication) {
        dataStack.persistWithCompletion(nil)
    }
}

Add additional method to persist data

import UIKit
import CoreData
import DATAStack

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    lazy var dataStack: DATAStack = DATAStack()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        application.setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)

        let appearance = UINavigationBar.appearance()
        appearance.barTintColor = UIColor(red:0.83, green:0.43, blue:0.36, alpha:1)
        appearance.titleTextAttributes = [NSFontAttributeName : UIFont(name: "AvenirNext-DemiBold", size: 20)!,
            NSForegroundColorAttributeName : UIColor.whiteColor()]

        window = UIWindow(frame: UIScreen.mainScreen().bounds)

        let initialViewController = ViewController(dataStack: dataStack)

        window?.rootViewController = UINavigationController(rootViewController: initialViewController)
        window?.makeKeyAndVisible()

        return true
    }

    func applicationDidEnterBackground(application: UIApplication) {
        self.dataStack.persistWithCompletion(nil)
    }

    func applicationWillTerminate(application: UIApplication) {
        self.dataStack.persistWithCompletion(nil)
    }
}


//
//  TripsFetchedModelAdapter.swift
//  SmartReceipts
//
//  Created by Jaanus Siim on 31/05/16.
//  Copyright © 2016 Will Baumann. All rights reserved.
//

import Foundation

class TripsFetchedModelAdapter: FetchedModelAdapter {
    func refreshPriceForTrip(trip: WBTrip, inDatabase database: FMDatabase) {
        Log.debug("Refresh price on \(trip.name)")
        timeMeasured("Price update") {
            //TODO jaanus: maybe lighter query - only price/currency/exchangeRate?
            let receipts = database.fetchAllReceiptsForTrip(trip)
            let distances: [Distance]
            if WBPreferences.isTheDistancePriceBeIncludedInReports() {
                //lighter query also here?
                distances = database.fetchAllDistancesForTrip(trip)
            } else {
                distances = []
            }

            let collection = PricesCollection()
            for receipt in receipts {
                collection.addPrice(receipt.targetPrice())
            }
            trip.price = collection
        }
    }
}

Add distances to trip price

//
//  TripsFetchedModelAdapter.swift
//  SmartReceipts
//
//  Created by Jaanus Siim on 31/05/16.
//  Copyright © 2016 Will Baumann. All rights reserved.
//

import Foundation

class TripsFetchedModelAdapter: FetchedModelAdapter {
    func refreshPriceForTrip(trip: WBTrip, inDatabase database: FMDatabase) {
        Log.debug("Refresh price on \(trip.name)")
        timeMeasured("Price update") {
            //TODO jaanus: maybe lighter query - only price/currency/exchangeRate?
            let receipts = database.fetchAllReceiptsForTrip(trip)
            let distances: [Distance]
            if WBPreferences.isTheDistancePriceBeIncludedInReports() {
                //lighter query also here?
                distances = database.fetchAllDistancesForTrip(trip)
            } else {
                distances = []
            }

            let collection = PricesCollection()
            // just so that when no receipts we would not end up with blank price
            collection.addPrice(Price(amount: .zero(), currency: trip.defaultCurrency))
            for receipt in receipts {
                collection.addPrice(receipt.targetPrice())
            }
            for distance in distances {
                collection.addPrice(distance.totalRate())
            }
            trip.price = collection
        }
    }
}


// THIS TEST IS LINE-COUNT DEPENDENT.  DO NOT RE-INDENT.
import FileCheck
import XCTest
import Foundation

class LineCountSpec : XCTestCase {
  func testLineCount() {
    let txt = [
      "9",
      "10 aaa",
      "11 bbb",
      "12 ccc",
      "13 CHECK-LINECOUNT: [[@LINE-3]] {{a}}aa",
      "14 CHECK-LINECOUNT: [[@LINE-3]] {{b}}bb",
      "15 CHECK-LINECOUNT: [[@LINE-3]] {{c}}cc",
      "16 foobar",
      "17 CHECK-LINECOUNT: [[@LINE-1]] {{foo}}bar",
      "18",
      "19 arst CHECK-LINECOUNT: [[@LINE]] {{a}}rst",
      "20",
      "21 BAD-CHECK-LINECOUNT: [[@LINE:cant-have-regex]]",
    ].joined(separator: "\n")

    XCTAssert(fileCheckOutput(of: .stdout, withPrefixes: ["CHECK-LINECOUNT"]) {
      print(txt)
    })

    XCTAssertFalse(fileCheckOutput(of: .stdout, withPrefixes: ["BAD-CHECK-LINECOUNT"]) {
      print(txt)
    })
  }
  #if !os(macOS)
  static var allTests = testCase([
    ("testLineCount", testLineCount),
  ])
  #endif
}

Add test for @LINE expressions

// THIS TEST IS LINE-COUNT DEPENDENT.  DO NOT RE-INDENT.
import FileCheck
import XCTest
import Foundation

class LineCountSpec : XCTestCase {
  func testLineCount() {
    let txt = ((1...8).map({ "\($0)" }) + [
        "9 aaa"
      , "10 bbb"
      , "11 ccc", "", "", ""
      // 12 CHECK-LINECOUNT: [[@LINE-3]] {{a}}aa
      // 13 CHECK-LINECOUNT: [[@LINE-3]] {{b}}bb
      // 14 CHECK-LINECOUNT: [[@LINE-3]] {{c}}cc
      , "15 foobar", ""
      // 16 CHECK-LINECOUNT: [[@LINE-1]] {{foo}}bar
      , "17", "18 arst"
      // CHECK-LINECOUNT: [[@LINE]] {{a}}rst
      , "19"
      // 20 BAD-CHECK-LINECOUNT: [[@LINE:cant-have-regex]]
    ]).joined(separator: "\n")

    XCTAssert(fileCheckOutput(of: .stdout, withPrefixes: ["CHECK-LINECOUNT"]) {
      print(txt)
    })

    XCTAssertFalse(fileCheckOutput(of: .stdout, withPrefixes: ["BAD-CHECK-LINECOUNT"]) {
      print(txt)
    })
  }
  #if !os(macOS)
  static var allTests = testCase([
    ("testLineCount", testLineCount),
  ])
  #endif
}


//
//  Utils.swift
//  IBAnimatableApp
//
//  Created by jason akakpo on 03/07/16.
//  Copyright © 2016 Jake Lin. All rights reserved.
//

import Foundation

internal extension Array {
  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  subscript(safe index: Int ) -> Element? {
    return indices.contains(index) ? self[index] : nil  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  }
}

internal extension String {
  func toDouble() -> Double? {
    return Double(self)
  }
  func toInt() -> Int? {
    return Int(self)
  }
}

internal extension RawRepresentable where RawValue == String {
  init?(raw: String?) {
    guard let string = raw else {
      return nil
    }
    self.init(rawValue: string)
  }
}
internal extension RawRepresentable {
  init(raw: RawValue?,  defaultValue: Self) {
    guard let value = raw  else {
      self = defaultValue
      return
    }
    self = Self.init(rawValue: value) ?? defaultValue
  }
}

Make a more generic extension, instead of the specialised one.

//
//  Utils.swift
//  IBAnimatableApp
//
//  Created by jason akakpo on 03/07/16.
//  Copyright © 2016 Jake Lin. All rights reserved.
//

import Foundation

extension Array {
  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  subscript(safe index: Int ) -> Element? {
    return indices.contains(index) ? self[index] : nil  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  }
}

extension String {
  func toDouble() -> Double? {
    return Double(self)
  }
  func toInt() -> Int? {
    return Int(self)
  }
}

internal extension RawRepresentable {

  init?(raw: RawValue?) {
    guard let raw = raw else {
      return nil
    }
    self.init(rawValue: raw)
  }

  init(raw: RawValue?,  defaultValue: Self) {
    guard let value = raw  else {
      self = defaultValue
      return
    }
    self = Self.init(rawValue: value) ?? defaultValue
  }
}


import UIKit

extension Container {

    var appDelegateAssembly: AppDelegateAssembly {
        if let stubClass = NSClassFromString("SharedShoppingAppTests.AppDelegateAssemblyStub") as? NSObject.Type,
            let stubInstance = stubClass.init() as? AppDelegateAssembly {
            return stubInstance
        }
        return Assembly()
    }

    private struct Assembly: AppDelegateAssembly {

        var window: UIWindow {
            let window = UIWindow(frame: UIScreen.main.bounds)
            window.rootViewController = ViewController()
            return window
        }

    }

}

Use ShoppingsViewController as a root for app window

import UIKit

extension Container {

    var appDelegateAssembly: AppDelegateAssembly {
        if let stubClass = NSClassFromString("SharedShoppingAppTests.AppDelegateAssemblyStub") as? NSObject.Type,
            let stubInstance = stubClass.init() as? AppDelegateAssembly {
            return stubInstance
        }
        return Assembly(container: self)
    }

    private struct Assembly: AppDelegateAssembly {

        let container: Container

        // MAKR: AppDelegateAssembly

        var window: UIWindow {
            let window = UIWindow(frame: UIScreen.main.bounds)
            window.rootViewController = container.shoppingsViewController
            return window
        }

    }

}


//
//  KnownFacets.swift
//  SoftU2F
//
//  Created by Benjamin P Toews on 1/27/17.
//

import Foundation

let KnownFacets: [Data: String] = [
    SHA256.digest("https://github.com/u2f/trusted_facets"): "https://github.com",
    SHA256.digest("https://demo.yubico.com"): "https://demo.yubico.com",
    SHA256.digest("https://www.dropbox.com/u2f-app-id.json"): "https://dropbox.com",
    SHA256.digest("https://www.gstatic.com/securitykey/origins.json"): "https://google.com",
    SHA256.digest("https://vault.bitwarden.com/app-id.json"): "https://vault.bitwarden.com",
    SHA256.digest("https://keepersecurity.com"): "https://keepersecurity.com",
    SHA256.digest("https://api-9dcf9b83.duosecurity.com"): "https://api-9dcf9b83.duosecurity.com",
    SHA256.digest("https://dashboard.stripe.com"): "https://dashboard.stripe.com"
]

Add Fedora U2F to known facets

//
//  KnownFacets.swift
//  SoftU2F
//
//  Created by Benjamin P Toews on 1/27/17.
//

import Foundation

let KnownFacets: [Data: String] = [
    SHA256.digest("https://github.com/u2f/trusted_facets"): "https://github.com",
    SHA256.digest("https://demo.yubico.com"): "https://demo.yubico.com",
    SHA256.digest("https://www.dropbox.com/u2f-app-id.json"): "https://dropbox.com",
    SHA256.digest("https://www.gstatic.com/securitykey/origins.json"): "https://google.com",
    SHA256.digest("https://vault.bitwarden.com/app-id.json"): "https://vault.bitwarden.com",
    SHA256.digest("https://keepersecurity.com"): "https://keepersecurity.com",
    SHA256.digest("https://api-9dcf9b83.duosecurity.com"): "https://api-9dcf9b83.duosecurity.com",
    SHA256.digest("https://dashboard.stripe.com"): "https://dashboard.stripe.com",
    SHA256.digest("https://id.fedoraproject.org/u2f-origins.json"): "https://id.fedoraproject.org"
]


//
//  AppleMusicAPIError.swift
//  Cider
//
//  Created by Scott Hoyt on 8/9/17.
//  Copyright © 2017 Scott Hoyt. All rights reserved.
//

import Foundation

struct AppleMusicAPIError: Error, Codable {
    let id: String
    let about: String
    let status: String
    let code: String
    let title: String
    let detail: String
    // let source: Source
    // let meta: Meta
}

Make about field in error object optional since it is not always present.

//
//  AppleMusicAPIError.swift
//  Cider
//
//  Created by Scott Hoyt on 8/9/17.
//  Copyright © 2017 Scott Hoyt. All rights reserved.
//

import Foundation

struct AppleMusicAPIError: Error, Codable {
    let id: String
    let about: String?
    let status: String
    let code: String
    let title: String
    let detail: String
    // let source: Source
    // let meta: Meta
}


//
//  Data+Representation.swift
//  JustLog
//
//  Created by Alberto De Bortoli on 15/12/2016.
//  Copyright © 2017 Just Eat. All rights reserved.
//

import Foundation

extension Data {

    func stringRepresentation() -> String {
        let retVal = NSString(data: self, encoding: String.Encoding.utf8.rawValue) as? String
        return retVal ?? ""
    }
}

Fix downcast to String warning

//
//  Data+Representation.swift
//  JustLog
//
//  Created by Alberto De Bortoli on 15/12/2016.
//  Copyright © 2017 Just Eat. All rights reserved.
//

import Foundation

extension Data {

    func stringRepresentation() -> String {
        let retVal = String(data: self, encoding: .utf8)
        return retVal ?? ""
    }
}


//
//  UITableView+Source.swift
//  Shoyu
//
//  Created by asai.yuki on 2015/12/12.
//  Copyright © 2015年 yukiasai. All rights reserved.
//

import UIKit
import ObjectiveC

struct UITableViewAssociatedObjectHandle {
    static var Source: UInt8 = 0
}

public extension UITableView {
    public var source: Source? {
        set {
            objc_setAssociatedObject(self, &UITableViewAssociatedObjectHandle.Source, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            dataSource = newValue
            delegate = newValue
        }
        get {
            return objc_getAssociatedObject(self, &UITableViewAssociatedObjectHandle.Source) as? Source
        }
    }
}

Fix variable name to camel case

//
//  UITableView+Source.swift
//  Shoyu
//
//  Created by asai.yuki on 2015/12/12.
//  Copyright © 2015年 yukiasai. All rights reserved.
//

import UIKit
import ObjectiveC

struct UITableViewAssociatedObjectHandle {
    static var source: UInt8 = 0
}

public extension UITableView {
    public var source: Source? {
        set {
            objc_setAssociatedObject(self, &UITableViewAssociatedObjectHandle.source, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            dataSource = newValue
            delegate = newValue
        }
        get {
            return objc_getAssociatedObject(self, &UITableViewAssociatedObjectHandle.source) as? Source
        }
    }
}


//
//  MediaItemTests.swift
//  TraktTopTen
//
//  Created by Paul Williamson on 05/04/2015.
//  Copyright (c) 2015 Paul Williamson. All rights reserved.
//

import UIKit
import XCTest

class MediaItemTests: XCTestCase {

    func testMovieCanBeInitialised() {
        let mediaItem = MediaItem(title: "Bacon", year: 1980, slug: "bacon", banner: "bacon-movie.jpg")
        XCTAssertNotNil(mediaItem, "Movie should not be nil")
        XCTAssert(mediaItem.title == "Bacon", "Movie title not set");
        XCTAssert(mediaItem.year == 1980, "Movie year not set");
        XCTAssert(mediaItem.slug == "bacon", "Movie slug not set");
        XCTAssert(mediaItem.banner == "bacon-movie.jpg", "Movie banner url not set");
    }

}

Rename movie -> media item

//
//  MediaItemTests.swift
//  TraktTopTen
//
//  Created by Paul Williamson on 05/04/2015.
//  Copyright (c) 2015 Paul Williamson. All rights reserved.
//

import UIKit
import XCTest

class MediaItemTests: XCTestCase {

    func testMovieCanBeInitialised() {
        let mediaItem = MediaItem(title: "Bacon", year: 1980, slug: "bacon", banner: "bacon-movie.jpg")
        XCTAssertNotNil(mediaItem, "MediaItem should not be nil")
        XCTAssert(mediaItem.title == "Bacon", "MediaItem title not set");
        XCTAssert(mediaItem.year == 1980, "MediaItem year not set");
        XCTAssert(mediaItem.slug == "bacon", "MediaItem slug not set");
        XCTAssert(mediaItem.banner == "bacon-movie.jpg", "Movie banner url not set");
    }

}


import UIKit

extension UIButton {

    /**
        Mimics a user tap on the button, firing any associated events
    */
    public func tap() -> FleetError? {
        guard isEnabled else {
            return FleetError(message: "Cannot tap UIButton: Control is not enabled")
        }
        guard !isHidden else {
            return FleetError(message: "Cannot tap UIButton: Control is not visible")
        }

        sendActions(for: .touchUpInside)
        return nil
    }
}

Update in-code documentation of `UIButton.tap()`

import UIKit

extension UIButton {

    /**
     Mimics a user tap on the button, firing the `.touchUpInside` control event.

     - returns:
     A `FleetError` if the button is hidden or disabled.
     */
    public func tap() -> FleetError? {
        guard isEnabled else {
            return FleetError(message: "Cannot tap UIButton: Control is not enabled")
        }
        guard !isHidden else {
            return FleetError(message: "Cannot tap UIButton: Control is not visible")
        }

        sendActions(for: .touchUpInside)
        return nil
    }
}


//
//  Person.swift
//  BNRSwiftJSONTests
//
//  Created by Matthew D. Mathias on 3/21/15.
//  Copyright © 2015 Big Nerd Ranch. Licensed under MIT.
//

import Foundation
import BNRSwiftJSON
import Result

public struct Person: CustomStringConvertible {
    public let name: String
    public var age: Int
    public let spouse: Bool

    public init(name: String, age: Int, spouse: Bool) {
        self.name = name
        self.age = age
        self.spouse = spouse
    }

    public var description: String {
        return "Name: \(name), age: \(age), married: \(spouse)"
    }
}

extension Person: JSONDecodable {
    public static func createWithJSON(value: JSON) -> Result<Person, NSError> {
        let name = value["name"].string
        let age = value["age"].int
        let isMarried = value["spouse"].bool

        return mapAll(name, age, isMarried, Person.create)
    }
}

extension Person {
    private static func create(name: String, age: Int, spouse: Bool) -> Person {
        return self.init(name: name, age: age, spouse: spouse)
    }
}

Remove person create function and pass the initialize to mapAll.

//
//  Person.swift
//  BNRSwiftJSONTests
//
//  Created by Matthew D. Mathias on 3/21/15.
//  Copyright © 2015 Big Nerd Ranch. Licensed under MIT.
//

import Foundation
import BNRSwiftJSON
import Result

public struct Person: CustomStringConvertible {
    public let name: String
    public var age: Int
    public let spouse: Bool

    public init(name: String, age: Int, spouse: Bool) {
        self.name = name
        self.age = age
        self.spouse = spouse
    }

    public var description: String {
        return "Name: \(name), age: \(age), married: \(spouse)"
    }
}

extension Person: JSONDecodable {
    public static func createWithJSON(value: JSON) -> Result<Person, NSError> {
        let name = value["name"].string
        let age = value["age"].int
        let isMarried = value["spouse"].bool

        return mapAll(name, age, isMarried, Person.init)
    }
}


//
//  NSPersistentStore.swift
//  CoreDataKit
//
//  Created by Mathijs Kadijk on 07-07-14.
//  Copyright (c) 2014 Mathijs Kadijk. All rights reserved.
//

import CoreData

extension NSPersistentStore
{
    public class func URLForStoreName(storeName: String) -> NSURL?
    {
        assert(countElements(storeName) > 0, "Store name must be longer then zero characters.")

        let supportDirectoryURLs = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .AllDomainsMask)

        if let supportDirectoryURL = supportDirectoryURLs.first as? NSURL {
            return supportDirectoryURL.URLByAppendingPathComponent(storeName + ".sqlite", isDirectory: false)
        }

        return nil
    }
}

Create directory for persistent store

//
//  NSPersistentStore.swift
//  CoreDataKit
//
//  Created by Mathijs Kadijk on 07-07-14.
//  Copyright (c) 2014 Mathijs Kadijk. All rights reserved.
//

import CoreData

extension NSPersistentStore
{
    public class func URLForStoreName(storeName: String) -> NSURL?
    {
        assert(countElements(storeName) > 0, "Store name must be longer then zero characters.")

        let optionalSupportDirectoryURL = NSFileManager.defaultManager().URLForDirectory(.ApplicationSupportDirectory, inDomain: .AllDomainsMask, appropriateForURL: nil, create: true, error: nil)

        if let supportDirectoryURL = optionalSupportDirectoryURL {
            return supportDirectoryURL.URLByAppendingPathComponent(storeName + ".sqlite", isDirectory: false)
        }

        return nil
    }
}


//
//  FormSection.swift
//  Bureaucracy
//
//  Created by Alexander Kolov on 20.10.14.
//  Copyright (c) 2014 Alexander Kolov. All rights reserved.
//

import Foundation
import SwiftHelpers

public class FormSection: SequenceType {

  public init(form: Form, name: String) {
    self.form = form
    self.name = name
  }

  public var name: String
  public var localizedTitle: String?
  public var form: Form
  public var items: [FormElement] = []

  public var count: Int {
    return items.count
  }

  public func append(item: FormElement) -> FormElement {
    items += [item]
    return item
  }

  public func serialize() -> [String: Any?] {
    return items
      .map { (var el) -> (String, Any?) in
        el.serialize()
      }
      .reduce([:]) { (var dict, tuple) -> [String: Any?] in
        var (key, value) = tuple
        dict[key] = value
        return dict
      }
  }

  // MARK: - SequenceType

  public func generate() -> GenericGenerator<FormElement> {
    return GenericGenerator(items: self.items)
  }

}

Append item, don't wrap in array

//
//  FormSection.swift
//  Bureaucracy
//
//  Created by Alexander Kolov on 20.10.14.
//  Copyright (c) 2014 Alexander Kolov. All rights reserved.
//

import Foundation
import SwiftHelpers

public class FormSection: SequenceType {

  public init(form: Form, name: String) {
    self.form = form
    self.name = name
  }

  public var name: String
  public var localizedTitle: String?
  public var form: Form
  public var items: [FormElement] = []

  public var count: Int {
    return items.count
  }

  public func append(item: FormElement) -> FormElement {
    items.append(item)
    return item
  }

  public func serialize() -> [String: Any?] {
    return items
      .map { (var el) -> (String, Any?) in
        el.serialize()
      }
      .reduce([:]) { (var dict, tuple) -> [String: Any?] in
        var (key, value) = tuple
        dict[key] = value
        return dict
      }
  }

  // MARK: - SequenceType

  public func generate() -> GenericGenerator<FormElement> {
    return GenericGenerator(items: self.items)
  }

}


// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency %import-libdispatch -parse-as-library) | %FileCheck %s --dump-input=always

// REQUIRES: executable_test
// REQUIRES: concurrency

// rdar://76038845
// UNSUPPORTED: use_os_stdlib

// This test is flaky on VS2017 (unknown reasons)
// UNSUPPORTED: MSVC_VER=15.0

@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@main struct Main {
  static func main() async {
    let handle = detach {
      while (!Task.isCancelled) { // no need for await here, yay
        print("waiting")
      }

      print("done")
    }

    handle.cancel()

    // CHECK: done
    await handle.get()
  }
}

Disable test that is failing on windows.

// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency %import-libdispatch -parse-as-library) | %FileCheck %s --dump-input=always

// REQUIRES: executable_test
// REQUIRES: concurrency

// rdar://76038845
// UNSUPPORTED: use_os_stdlib

// This test is flaky on VS2017 (unknown reasons)
// UNSUPPORTED: MSVC_VER=15.0

// This test is failing on windows. SR-14447.
//
// UNSUPPORTED: OS=windows-msvc

@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@main struct Main {
  static func main() async {
    let handle = detach {
      while (!Task.isCancelled) { // no need for await here, yay
        print("waiting")
      }

      print("done")
    }

    handle.cancel()

    // CHECK: done
    await handle.get()
  }
}


//
//  BackendConfiguration.swift
//  TOZ_iOS
//
//  Copyright © 2017 intive. All rights reserved.
//

import Foundation
/**
 Class storing backend URL so other system elements know where to send requests to.
 */
final class BackendConfiguration {

    let baseURL: URL

    init(baseURL: URL) {
        self.baseURL = baseURL
    }

    static var shared: BackendConfiguration = BackendConfiguration(baseURL: URL(string: "http://dev.patronage2017.intive-projects.com")!)
}

Set new URL to backend

//
//  BackendConfiguration.swift
//  TOZ_iOS
//
//  Copyright © 2017 intive. All rights reserved.
//

import Foundation
/**
 Class storing backend URL so other system elements know where to send requests to.
 */
final class BackendConfiguration {

    let baseURL: URL

    init(baseURL: URL) {
        self.baseURL = baseURL
    }

    static var shared: BackendConfiguration = BackendConfiguration(baseURL: URL(string: "http://dev.patronage2017.intive-projects.com/api")!)
}


/*
 Copyright 2016-present The Material Motion Authors. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import Foundation

extension MotionObservableConvertible {

  /**
   Emit a constant value each time this operator receives a value.
   */
  public func rewriteTo<U>(_ value: U) -> MotionObservable<U> {
    return _map(#function, args: [value]) { _ in value }
  }
}

Add rewrite operator that accepts an observable.

/*
 Copyright 2016-present The Material Motion Authors. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import Foundation

extension MotionObservableConvertible {

  /**
   Emit a constant value each time this operator receives a value.
   */
  public func rewriteTo<U>(_ value: U) -> MotionObservable<U> {
    return _map(#function, args: [value]) { _ in value }
  }

  /**
   Emit a constant value each time this operator receives a value.
   */
  public func rewriteTo<O: MotionObservableConvertible>(_ value: O) -> MotionObservable<O.T> {
    return _map(#function, args: [value]) { _ in value._read()! }
  }
}


// NOTE: This test does NOT run under Address Sanitizer because it triggers
// a heap use-after-free (SR-1070).

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not %target-swift-frontend %s -typecheck
// REQUIRES: no_asan
{
protocol A{
func<typealias e=b
typealias e typealias b

Remove "REQUIRES: no_asan" since crash case is marked fixed.

// NOTE: This test does NOT run under Address Sanitizer because it triggers
// a heap use-after-free (SR-1070).

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not %target-swift-frontend %s -typecheck
{
protocol A{
func<typealias e=b
typealias e typealias b