//
//  ArrayExtensions.swift
//  EZSwiftExtensions
//
//  Created by Goktug Yilmaz on 15/07/15.
//  Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit

extension Array {

    /// EZSwiftExtensions
    public func random() -> Element {
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }

    /// EZSwiftExtensions
    public func indexOfObject<T: Equatable>(object: T) -> Int? {
        for index in 0..<self.count {
            if let arrayObject = self[index] as? T {
                if arrayObject == object {
                    return index
                }
            }
        }

        return nil
    }

    /// EZSwiftExtensions
    public mutating func removeObject<U: Equatable>(object: U) {
        var index: Int?
        for (idx, objectToCompare) in self.enumerate() {
            if let to = objectToCompare as? U {
                if object == to {
                    index = idx
                }
            }
        }

        if index != nil {
            self.removeAtIndex(index!)
        }
    }
}

Update Array's removeObject to remove all occurences

//
//  ArrayExtensions.swift
//  EZSwiftExtensions
//
//  Created by Goktug Yilmaz on 15/07/15.
//  Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit

extension Array {

    /// EZSwiftExtensions
    public func random() -> Element {
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }

    /// EZSwiftExtensions
    public func indexOfObject<T: Equatable>(object: T) -> Int? {
        for index in 0..<self.count {
            if let arrayObject = self[index] as? T {
                if arrayObject == object {
                    return index
                }
            }
        }

        return nil
    }

    /// EZSwiftExtensions
    public mutating func removeObject<U: Equatable>(object: U) {
        for i in (0..<count).reverse() {
            if let obj = self[i] as? U where obj == object {
                self.removeAtIndex(i)
            }
        }
    }
}


//  Copyright (c) 2015 Steve Brambilla. All rights reserved.

import UIKit

/// Evaluates a distinct layout expression into a single constraint.
///
/// Returns an evaluated NSLayoutConstraint
public func evaluateLayoutExpression(_ expression: DistinctExpressionType) -> NSLayoutConstraint {
	return expression.evaluateDistinct()
}

/// Evaluates a layout expression into constraints.
///
/// Returns an array of layout constraints.
public func evaluateLayoutExpression(_ expression: ExpressionProtocol) -> [NSLayoutConstraint] {
	return expression.evaluateAll()
}

/// Evaluates multiple layout expressions into constraints.
///
/// Returns an array of layout constraints.
public func evaluateLayoutExpressions(_ expressions: [ExpressionProtocol]) -> [NSLayoutConstraint] {
	return expressions.reduce([]) { acc, expression in
		return acc + expression.evaluateAll()
	}
}

Add convenience funcs for activating constraints

//  Copyright (c) 2015 Steve Brambilla. All rights reserved.

import UIKit

/// Evaluates a distinct layout expression into a single constraint.
///
/// Returns an evaluated NSLayoutConstraint
public func evaluateLayoutExpression(_ expression: DistinctExpressionType) -> NSLayoutConstraint {
	return expression.evaluateDistinct()
}

/// Evaluates a layout expression into constraints.
///
/// Returns an array of layout constraints.
public func evaluateLayoutExpression(_ expression: ExpressionProtocol) -> [NSLayoutConstraint] {
	return expression.evaluateAll()
}

/// Evaluates multiple layout expressions into constraints.
///
/// Returns an array of layout constraints.
public func evaluateLayoutExpressions(_ expressions: [ExpressionProtocol]) -> [NSLayoutConstraint] {
	return expressions.reduce([]) { acc, expression in
		return acc + expression.evaluateAll()
	}
}

/// Evaluates a distinct layout expression and activates the constraint.
///
/// The effect of this function is the same as setting the `isActive` property of the constraint to
/// `true`.
public func activateLayoutExpression(_ expression: DistinctExpressionType) {
    evaluateLayoutExpression(expression).isActive = true
}

/// Evaluates a layout expression and activates its constraints.
///
/// The effect of this function is the same as setting the `isActive` property of the constraints to
/// `true`.
public func activateLayoutExpression(_ expression: ExpressionProtocol) {
    evaluateLayoutExpression(expression).activateConstraints()
}

/// Evaluates multiple layout expressions and activates their constraints.
///
/// The effect of this function is the same as setting the `isActive` property of each constraint
/// to `true`.
public func activateLayoutExpressions(_ expressions: [ExpressionProtocol]) {
    evaluateLayoutExpressions(expressions).activateConstraints()
}


//  Copyright © 2015 Rob Rix. All rights reserved.

final class TelescopeTests: XCTestCase {
	// MARK: Types

	func testEmptyDataConstructorHasUnitType() {
		assert(Telescope.End.type("A"), ==, .UnitType)
	}

	func testRecursiveDataConstructorHasFunctionType() {
		assert(Telescope.Recursive(.End).type("A"), ==, .lambda("A", const(.UnitType)))
	}

	func testMultiplyRecursiveDataConstructorHasFunctionType() {
		assert(Telescope.Recursive(.Recursive(.End)).type("A"), ==, .lambda("A", const(.lambda("A", const(.UnitType)))))
	}

	func testArgumentDataConstructorHasFunctionType() {
		assert(Telescope.Argument("B", const(.Recursive(.End))).type("A"), ==, .lambda("B", const(.lambda("A", const(.UnitType)))))
	}

	// MARK: Values

	func testEmptyDataConstructorHasUnitValue() {
		assert(Telescope.End.value("A"), ==, .Unit)
	}
}

import Assertions
@testable import Manifold
import Prelude
import XCTest

Test with a single recursive parameter.

//  Copyright © 2015 Rob Rix. All rights reserved.

final class TelescopeTests: XCTestCase {
	// MARK: Types

	func testEmptyDataConstructorHasUnitType() {
		assert(Telescope.End.type("A"), ==, .UnitType)
	}

	func testRecursiveDataConstructorHasFunctionType() {
		assert(Telescope.Recursive(.End).type("A"), ==, .lambda("A", const(.UnitType)))
	}

	func testMultiplyRecursiveDataConstructorHasFunctionType() {
		assert(Telescope.Recursive(.Recursive(.End)).type("A"), ==, .lambda("A", const(.lambda("A", const(.UnitType)))))
	}

	func testArgumentDataConstructorHasFunctionType() {
		assert(Telescope.Argument("B", const(.Recursive(.End))).type("A"), ==, .lambda("B", const(.lambda("A", const(.UnitType)))))
	}

	// MARK: Values

	func testEmptyDataConstructorHasUnitValue() {
		assert(Telescope.End.value("A"), ==, .Unit)
	}

	func testRecursiveDataConstructorHasLambdaValueReturningProductValue() {
		assert(Telescope.Recursive(.End).value("A"), ==, .lambda("A", { .Product($0, .Unit) }))
	}
}

import Assertions
@testable import Manifold
import Prelude
import XCTest


// RUN: %target-swift-frontend -parse-as-library -O -emit-ir  %s | %FileCheck %s
// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib,CPU=x86_64

// This is an end-to-end test to ensure that the optimizer generates
// a simple literal for character literals.

// CHECK-LABEL: define {{.*}}charArray
// CHECK:  store <2 x i64> <i64 97, i64 98>
// CHECK:  store <2 x i64> <i64 99, i64 100>
// CHECK:  ret
public func charArray(_ i: Int) -> [Character] {
  return [ "a", "b", "c", "d" ]
}

// CHECK-LABEL: define {{.*}}singleChar
// CHECK: ret {{.*}} 97
public func singleChar() -> Character {
  return "a"
}

// FIXME: The following part of this test is temporarily disabled.

// CHECK-LABEL: define {{.*}}singleNonAsciiChar
// CHECK: ret {{.*}} 26085
public func singleNonAsciiChar() -> Character {
  return "日"
}

Make assumption about SSE code gen explicit

// RUN: %target-swift-frontend -parse-as-library -O -target-cpu core2 -emit-ir  %s | %FileCheck %s
// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib,CPU=x86_64

// This is an end-to-end test to ensure that the optimizer generates
// a simple literal for character literals.

// Please note: this test targets "core2" to ensure consistent output
// on all x86 host processors.

// CHECK-LABEL: define {{.*}}charArray
// CHECK:  store <2 x i64> <i64 97, i64 98>
// CHECK:  store <2 x i64> <i64 99, i64 100>
// CHECK:  ret
public func charArray(_ i: Int) -> [Character] {
  return [ "a", "b", "c", "d" ]
}

// CHECK-LABEL: define {{.*}}singleChar
// CHECK: ret {{.*}} 97
public func singleChar() -> Character {
  return "a"
}

// FIXME: The following part of this test is temporarily disabled.

// CHECK-LABEL: define {{.*}}singleNonAsciiChar
// CHECK: ret {{.*}} 26085
public func singleNonAsciiChar() -> Character {
  return "日"
}


//
// SwiftyUserDefaults
//
// Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

import Quick

final class DefaultsStringSpec: QuickSpec, DefaultsSerializableSpec {

    typealias Serializable = String

    var customValue: String = "custom value"
    var defaultValue: String = "default value"

    override func spec() {
        given("String") {
            self.testValues()
            self.testOptionalValues()
            self.testOptionalValuesWithoutDefaultValue()
        }
    }
}

Add tests for String plist reading

//
// SwiftyUserDefaults
//
// Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

import Quick

final class DefaultsStringSpec: QuickSpec, DefaultsSerializableSpec {

    typealias Serializable = String

    var customValue: String = "custom value"
    var defaultValue: String = "default value"

    override func spec() {
        given("String") {
            self.testValues()
            self.testOptionalValues()
            self.testOptionalValuesWithoutDefaultValue()
            self.testPlistRegisteringValues(valueStrings: ["0.0": "0.0",
                                                           "test": "test"])
        }
    }
}


//
//  AppCoordinator
//  Cruciverber
//
//  Created by Cihat Gündüz on 12.03.16.
//  Copyright © 2016 Flinesoft. All rights reserved.
//

import UIKit

/// This class is a coordinator for screen flows starting on app start / using windows.
open class AppCoordinator: Coordinator {
    // MARK: - Stored Instance Properties

    public let window = UIWindow(frame: UIScreen.main.bounds)

    // MARK: - Initializers

    /// Initializes a new AppCoordinator object and creates a window.
    public init() {
        let pseudoViewController = UIViewController()
        super.init(presentingViewController: pseudoViewController)
    }

    override init(presentingViewController: UIViewController) {
        preconditionFailure("illegal init call – use init() instead")
    }
}

Add present initial view controller method on app coordinators

//
//  AppCoordinator
//  Cruciverber
//
//  Created by Cihat Gündüz on 12.03.16.
//  Copyright © 2016 Flinesoft. All rights reserved.
//

import UIKit

/// This class is a coordinator for screen flows starting on app start / using windows.
open class AppCoordinator: Coordinator {
    // MARK: - Stored Instance Properties

    public let window = UIWindow(frame: UIScreen.main.bounds)

    // MARK: - Initializers

    /// Initializes a new AppCoordinator object and creates a window.
    public init() {
        let pseudoViewController = UIViewController()
        super.init(presentingViewController: pseudoViewController)
    }

    override init(presentingViewController: UIViewController) {
        preconditionFailure("illegal init call – use init() instead")
    }

    // MARK: - Instance Methods

    /// Presents the initial view controllers as the windows root view.
    ///
    /// - Parameters:
    ///   - viewController: The view controller to be presented.
    public func presentInitialViewController(_ viewController: UIViewController) {
        window.rootViewController = viewController
        window.makeKeyAndVisible()
    }
}


//
//  NSObject.swift
//  DarkSwift
//
//  Created by Dark Dong on 2017/5/26.
//  Copyright © 2017年 Dark Dong. All rights reserved.
//

import Foundation

private var associatedObjectKey = 0

public extension NSObject {
    func trace(funcname: String = #function, _ items: Any...) {
        print(type(of: self), funcname, items)
    }

    func clone() -> AnyObject {
        return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as AnyObject
    }

    var associatedObject: Any? {
        get {
            return objc_getAssociatedObject(self, &associatedObjectKey)
        }
        set {
            objc_setAssociatedObject(self, &associatedObjectKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
}

Add date parameter to trace

//
//  NSObject.swift
//  DarkSwift
//
//  Created by Dark Dong on 2017/5/26.
//  Copyright © 2017年 Dark Dong. All rights reserved.
//

import Foundation

private var associatedObjectKey = 0

public extension NSObject {
    func trace(timestamp: Bool = false, funcname: String = #function, _ items: Any...) {
        if timestamp {
            print(Date(), type(of: self), funcname, items)
        } else {
            print(type(of: self), funcname, items)
        }
    }

    func clone() -> AnyObject {
        return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as AnyObject
    }

    var associatedObject: Any? {
        get {
            return objc_getAssociatedObject(self, &associatedObjectKey)
        }
        set {
            objc_setAssociatedObject(self, &associatedObjectKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
}


//
// Created by Viktor Belenyesi on 18/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
// Inspired by
// http://www.scala-lang.org/api/2.11.5/index.html#scala.util.DynamicVariable
// and
// https://searchcode.com/codesearch/view/18473763/
// and
// http://scalageek.blogspot.hu/2013/02/when-to-use-dynamic-variables.html?m=1

public class DynamicVariable<T> {

    private let threadLocal: ThreadLocal<T>

    public var value: T? {
        set {
            threadLocal.value = newValue
        }
        get {
            return threadLocal.value
        }
    }

    public init(_ value: T?) {
        self.threadLocal = ThreadLocal(value: value, key: "DynamicVariable")
        self.value = value
    }

    public func withValue<S>(newval: T, _ thunk: () -> S) -> S {
        let oldval = value

        // set the context
        self.value = newval

        let result = thunk()

        // restore the context
        self.value = oldval

        return result
    }

}

Remove unnecessary assignment and add noescape to thunk

//
// Created by Viktor Belenyesi on 18/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
// Inspired by
// http://www.scala-lang.org/api/2.11.5/index.html#scala.util.DynamicVariable
// and
// https://searchcode.com/codesearch/view/18473763/
// and
// http://scalageek.blogspot.hu/2013/02/when-to-use-dynamic-variables.html?m=1

public class DynamicVariable<T> {

    private let threadLocal: ThreadLocal<T>

    public var value: T? {
        set {
            threadLocal.value = newValue
        }
        get {
            return threadLocal.value
        }
    }

    public init(_ value: T?) {
        self.threadLocal = ThreadLocal(value: value, key: "DynamicVariable")
    }

    public func withValue<S>(newval: T, @noescape _ thunk: () -> S) -> S {
        let oldval = value

        // set the context
        self.value = newval

        let result = thunk()

        // restore the context
        self.value = oldval

        return result
    }

}


//
//  MapViewControllerUITests.swift
//  MapViewControllerUITests
//
//  Created by Peng Wang on 8/3/15.
//  Copyright © 2015 pengxwang. All rights reserved.
//

import XCTest

class MapViewControllerUITests: XCTestCase {

    override func setUp() {
        super.setUp()

        self.continueAfterFailure = false
        XCUIApplication().launch()
    }

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

    func testBasicUserFlow() {
        let app = XCUIApplication()

        app.buttons["Show Map"].tap()

        let searchField = app.navigationBars["Select Nearby Location"].searchFields["Search for place or address"]
        searchField.tap()
        searchField.typeText("Apple Inc., Cupertino")
        app.tables["Search results"].staticTexts["Apple Inc., 1 Infinite Loop, Cupertino, CA 95014-2083, United States"].tap()

        app.buttons["Select address in callout view"].tap()

        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

}

Add waiting assertions to basic-user-flow UI test

//
//  MapViewControllerUITests.swift
//  MapViewControllerUITests
//
//  Created by Peng Wang on 8/3/15.
//  Copyright © 2015 pengxwang. All rights reserved.
//

import XCTest

class MapViewControllerUITests: XCTestCase {

    let existsPredicate = NSPredicate(format: "exists == 1")

    override func setUp() {
        super.setUp()

        self.continueAfterFailure = false
        XCUIApplication().launch()
    }

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

    func testBasicUserFlow() {
        let app = XCUIApplication()
        let presentButton = app.buttons["Show Map"]

        presentButton.tap()

        let locationAnnotation = app.otherElements["Current Location"]

        self.expectationForPredicate(self.existsPredicate, evaluatedWithObject: locationAnnotation, handler: nil)
        self.waitForExpectationsWithTimeout(5.0, handler: nil)

        let searchField = app.navigationBars["Select Nearby Location"].searchFields["Search for place or address"]
        searchField.tap()
        searchField.typeText("Apple Inc., Cupertino")
        app.tables["Search results"].staticTexts["Apple Inc., 1 Infinite Loop, Cupertino, CA 95014-2083, United States"].tap()

        app.buttons["Select address in callout view"].tap()

        self.expectationForPredicate(self.existsPredicate, evaluatedWithObject: presentButton, handler: nil)
        self.waitForExpectationsWithTimeout(2.0, handler: nil)
    }

}


//
//  Request.swift
//  Slimane
//
//  Created by Yuki Takei on 4/16/16.
//  Copyright © 2016 MikeTOKYO. All rights reserved.
//

extension Response {

    public init(redirect location: String) {
        let headers: Headers = ["Location": location]
        self.init(status: .movedPermanently, headers: headers, body: [])
    }

    var bodyLength: Int {
        if case .buffer(let data) = body {
            return data.bytes.count
        }
        return 0
    }

    public var shouldKeepAlive: Bool {
        return connection?.lowercased() == "keep-alive"
    }
}

Add 'Cache-Control: max-age=0, no-cache, no-store' to redirect header

//
//  Request.swift
//  Slimane
//
//  Created by Yuki Takei on 4/16/16.
//  Copyright © 2016 MikeTOKYO. All rights reserved.
//

extension Response {

    public init(redirect location: String) {
        let headers: Headers = ["Location": location, "Cache-Control": "max-age=0, no-cache, no-store"]
        self.init(status: .movedPermanently, headers: headers, body: [])
    }

    var bodyLength: Int {
        if case .buffer(let data) = body {
            return data.bytes.count
        }
        return 0
    }

    public var shouldKeepAlive: Bool {
        return connection?.lowercased() == "keep-alive"
    }
}


import Foundation

public protocol DNSResolverProtocol: class {
    weak var delegate: DNSResolverDelegate? { get set }
    func resolve(session: DNSSession)
    func stop()
}

public protocol DNSResolverDelegate: class {
    func didReceive(rawResponse: Data)
}

public class UDPDNSResolver: DNSResolverProtocol, NWUDPSocketDelegate {
    let socket: NWUDPSocket
    public weak var delegate: DNSResolverDelegate?

    public init(address: IPAddress, port: Port) {
        socket = NWUDPSocket(host: address.presentation, port: Int(port.value))!
        socket.delegate = self
    }

    public func resolve(session: DNSSession) {
        socket.write(data: session.requestMessage.payload)
    }

    public func stop() {
        socket.disconnect()
    }

    public func didReceive(data: Data, from: NWUDPSocket) {
        delegate?.didReceive(rawResponse: data)
    }

    public func didCancel(socket: NWUDPSocket) {

    }
}

Allow overriding the DNS Resolver

import Foundation

public protocol DNSResolverProtocol: class {
    weak var delegate: DNSResolverDelegate? { get set }
    func resolve(session: DNSSession)
    func stop()
}

public protocol DNSResolverDelegate: class {
    func didReceive(rawResponse: Data)
}

open class UDPDNSResolver: DNSResolverProtocol, NWUDPSocketDelegate {
    let socket: NWUDPSocket
    public weak var delegate: DNSResolverDelegate?

    public init(address: IPAddress, port: Port) {
        socket = NWUDPSocket(host: address.presentation, port: Int(port.value))!
        socket.delegate = self
    }

    public func resolve(session: DNSSession) {
        socket.write(data: session.requestMessage.payload)
    }

    public func stop() {
        socket.disconnect()
    }

    public func didReceive(data: Data, from: NWUDPSocket) {
        delegate?.didReceive(rawResponse: data)
    }

    public func didCancel(socket: NWUDPSocket) {

    }
}


import SpriteKit

class BoidViewController: UIViewController {

    override func loadView() {
        let applicationFrame = UIScreen.mainScreen().bounds
        let skView = SKView(frame: applicationFrame)
        self.view = skView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if let skView = self.view as? SKView {
            skView.showsFPS = true
            skView.showsNodeCount = true
            skView.showsDrawCount = true
            skView.showsPhysics = true
            skView.showsFields = true
            skView.showsQuadCount = true

            skView.ignoresSiblingOrder = true

            let scene = BoidScene(size: CGSize(width: CGRectGetWidth(skView.bounds), height: CGRectGetHeight(skView.bounds)))
            skView.presentScene(scene)
        }
    }
}

Disable physics and fields debug informations

import SpriteKit

class BoidViewController: UIViewController {

    override func loadView() {
        let applicationFrame = UIScreen.mainScreen().bounds
        let skView = SKView(frame: applicationFrame)
        self.view = skView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if let skView = self.view as? SKView {
            skView.showsFPS = true
            skView.showsNodeCount = true
            skView.showsDrawCount = true
            //skView.showsPhysics = true
            //skView.showsFields = true
            skView.showsQuadCount = true

            skView.ignoresSiblingOrder = true

            let scene = BoidScene(size: CGSize(width: CGRectGetWidth(skView.bounds), height: CGRectGetHeight(skView.bounds)))
            skView.presentScene(scene)
        }
    }
}


//
//  FoundationExtensions.swift
//  Pargi
//
//  Created by Henri Normak on 29/04/2017.
//  Copyright © 2017 Henri Normak. All rights reserved.
//

import Foundation

extension String {
    func localized(withComment:String) -> String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment)
    }
}

Add an extension for arrays for shifting

//
//  FoundationExtensions.swift
//  Pargi
//
//  Created by Henri Normak on 29/04/2017.
//  Copyright © 2017 Henri Normak. All rights reserved.
//

import Foundation

extension String {
    func localized(withComment:String) -> String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment)
    }
}

extension Array {
    func shift(withDistance distance: Int = 1) -> Array<Element> {
        let offsetIndex = distance >= 0 ?
            self.index(startIndex, offsetBy: distance, limitedBy: endIndex) :
            self.index(endIndex, offsetBy: distance, limitedBy: startIndex)

        guard let index = offsetIndex else { return self }
        return Array(self[index ..< endIndex] + self[startIndex ..< index])
    }

    mutating func shiftInPlace(withDistance distance: Int = 1) {
        self = shift(withDistance: distance)
    }
}


//
//  Network.swift
//  SwinjectSimpleExample
//
//  Created by Yoichi Tagaya on 8/10/15.
//  Copyright © 2015 Swinject Contributors. All rights reserved.
//

import Foundation
import Alamofire

struct Network : Networking {
    func request(response: NSData? -> ()) {
        Alamofire.request(.GET, OpenWeatherMap.url, parameters: OpenWeatherMap.parameters)
            .response { _, _, data, error in
                response(data)
            }
    }
}

Replace an unused parameter with _.

//
//  Network.swift
//  SwinjectSimpleExample
//
//  Created by Yoichi Tagaya on 8/10/15.
//  Copyright © 2015 Swinject Contributors. All rights reserved.
//

import Foundation
import Alamofire

struct Network : Networking {
    func request(response: NSData? -> ()) {
        Alamofire.request(.GET, OpenWeatherMap.url, parameters: OpenWeatherMap.parameters)
            .response { _, _, data, _ in
                response(data)
            }
    }
}


import Foundation

struct MVitaPtpMessageOutRequestCommand:MVitaPtpMessageOutProtocol
{
    let data:Data

    init()
    {
        let builder:MVitaPtpMessageOutBuilder = MVitaPtpMessageOutBuilder()
        builder.append(value:MVitaPtpType.commandRequest)
        builder.append(value:MVitaPtpDataPhase.none)
        builder.appendTransactionId()

        data = builder.export()
    }
}

Send guid on command request

import Foundation

struct MVitaPtpMessageOutRequestCommand:MVitaPtpMessageOutProtocol
{
    let data:Data
    private let kGuidStart:UInt32 = 0
    private let kGuidEnd:UInt32 = 0

    init()
    {
        let builder:MVitaPtpMessageOutBuilder = MVitaPtpMessageOutBuilder()
        builder.append(value:MVitaPtpType.commandRequest)
        builder.append(value:MVitaPtpDataPhase.none)
        builder.appendTransactionId()
        builder.append(value:kGuidStart)
        builder.append(value:kGuidEnd)

        data = builder.export()
    }
}


//
//  NSDateComponentsFormatter+Postfix.swift
//  PartyUP
//
//  Created by Fritz Vander Heide on 2016-03-25.
//  Copyright © 2016 Sandcastle Application Development. All rights reserved.
//

import Foundation

extension NSDateComponentsFormatter {
    func stringFromDate(startDate: NSDate,
                        toDate endDate: NSDate,
                               classicThreshold classic: NSTimeInterval?,
                                                postfix: Bool = false,
                                                substituteZero zero: String? = nil) -> String? {
        var capped = false
        var interval = endDate.timeIntervalSinceDate(startDate)
        if let classic = classic where interval > classic {
            interval = classic
            capped = true
            if unitsStyle != .Abbreviated {
                return NSLocalizedString("Classic", comment: "Stale time display")
            }
        }

        var formatted = stringFromTimeInterval(interval) ?? "?"
        if capped {
            formatted += "+"
        }

        if let zero = zero where formatted.hasPrefix("0") {
            formatted = zero
        } else if postfix {
            formatted += NSLocalizedString(" ago", comment:"Samples more than a minute old")
        }
        return formatted
    }
}

Work around for the date formatter issue where being within an hour of a component transition will display more components than desired.

//
//  NSDateComponentsFormatter+Postfix.swift
//  PartyUP
//
//  Created by Fritz Vander Heide on 2016-03-25.
//  Copyright © 2016 Sandcastle Application Development. All rights reserved.
//

import Foundation

extension NSDateComponentsFormatter {
    func stringFromDate(startDate: NSDate,
                        toDate endDate: NSDate,
                               classicThreshold classic: NSTimeInterval?,
                                                postfix: Bool = false,
                                                substituteZero zero: String? = nil) -> String? {
        var capped = false
        var interval = endDate.timeIntervalSinceDate(startDate)
        if let classic = classic where interval > classic {
            interval = classic
            capped = true
            if unitsStyle != .Abbreviated {
                return NSLocalizedString("Classic", comment: "Stale time display")
            }
        }

        var formatted = stringFromTimeInterval(interval) ?? "?"
		formatted = formatted.characters.split(",").prefixUpTo(self.maximumUnitCount).map { String($0) }.joinWithSeparator(",")

        if capped {
            formatted += "+"
        }

        if let zero = zero where formatted.hasPrefix("0") {
            formatted = zero
        } else if postfix {
            formatted += NSLocalizedString(" ago", comment:"Samples more than a minute old")
        }
        return formatted
    }
}


//
//  FakeMessageReceiver.swift
//  MessageBroker
//
//  Created by Paul Young on 03/09/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Foundation
import MessageTransfer
import JSONLib

struct FakeMessageReceiver: MessageReceiverWithSender {

    typealias Verification = (channel: String, topic: String, payload: JSON) -> Void

    private let verify: Verification
    var messageSender: MessageSender?

    init(var _ messageSender: MessageSenderWithReceiver, _ verify: Verification = { (channel, topic, payload) in }) {
        self.messageSender = messageSender
        self.verify = verify
        messageSender.messageReceiver = self
    }

    func receive(channel: String, _ topic: String, _ payload: JSON) {
        self.verify(channel: channel, topic: topic, payload: payload)
    }
}

Update fake message receiver for optional payload.

//
//  FakeMessageReceiver.swift
//  MessageBroker
//
//  Created by Paul Young on 03/09/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Foundation
import MessageTransfer
import JSONLib

struct FakeMessageReceiver: MessageReceiverWithSender {

    typealias Verification = (channel: String, topic: String, payload: JSON?) -> Void

    private let verify: Verification
    var messageSender: MessageSender?

    init(var _ messageSender: MessageSenderWithReceiver, _ verify: Verification = { (channel, topic, payload) in }) {
        self.messageSender = messageSender
        self.verify = verify
        messageSender.messageReceiver = self
    }

    func receive(channel: String, _ topic: String, _ payload: JSON?) {
        self.verify(channel: channel, topic: topic, payload: payload)
    }
}


//
// Created by Alexey Korolev on 07/11/2018.
//

import Foundation

struct ProductType {
    private let value: String
    init(value: String) {
        self.value = value
    }

    var description: String {
        return self.value
    }

    var isApplication: Bool {
        switch self.value {
        case "\"com.apple.product-type.application\"":
            return true
        default:
            return false
        }
    }
}

Trim \" symbols in product type check

//
// Created by Alexey Korolev on 07/11/2018.
//

import Foundation

struct ProductType {
    private let value: String

    init(value: String) {
        self.value = value
    }

    var description: String {
        return value
    }

    var isApplication: Bool {
        return value.replacingOccurrences(of: "\"", with: "") == "com.apple.product-type.application"
    }
}


import Foundation

public final class Provider {
  var translations: [String: Data] = [:]

  // MARK: - Locale data

  public func dataForLocale(_ locale: String) -> Data? {
    var translation: Data?

    if let translationData = translations[locale] {
      translation = translationData
    } else {
      let bundle = Bundle(for: Provider.self)

      var path = bundle.path(forResource: locale,
                             ofType: Config.pathExtension,
                             inDirectory: Config.dirPath) ??
                 bundle.path(forResource: locale,
                             ofType: Config.pathExtension,
                             inDirectory: Config.dirFrameworkPath) ??
                 bundle.path(forResource: locale,
                             ofType: Config.pathExtension,
                             inDirectory: Config.dirResourcePath)

      if let resourcePath = Bundle(for: Provider.self).resourcePath {
        let bundlePath = resourcePath + "/Faker.bundle"

        if let bundle = Bundle(path: bundlePath) {
          path = bundle.path(forResource: locale, ofType: Config.pathExtension)
        }
      }

      if let path = path {
        let fileURL = URL(fileURLWithPath: path)

        if let data = try? Data(contentsOf: fileURL) {
          translation = data
          translations[locale] = data
        }
      }
    }

    return translation
  }
}

Rearrange to give precedence to the resource path

import Foundation

public final class Provider {
  var translations: [String: Data] = [:]

  // MARK: - Locale data

  public func dataForLocale(_ locale: String) -> Data? {
    var translation: Data?

    if let translationData = translations[locale] {
      translation = translationData
    } else {
      let bundle = Bundle(for: Provider.self)

      var path = bundle.path(forResource: locale,
                             ofType: Config.pathExtension,
                             inDirectory: Config.dirResourcePath) ??
                 bundle.path(forResource: locale,
                             ofType: Config.pathExtension,
                             inDirectory: Config.dirPath) ??
                 bundle.path(forResource: locale,
                             ofType: Config.pathExtension,
                             inDirectory: Config.dirFrameworkPath)

      if let resourcePath = Bundle(for: Provider.self).resourcePath {
        let bundlePath = resourcePath + "/Faker.bundle"

        if let bundle = Bundle(path: bundlePath) {
          path = bundle.path(forResource: locale, ofType: Config.pathExtension)
        }
      }

      if let path = path {
        let fileURL = URL(fileURLWithPath: path)

        if let data = try? Data(contentsOf: fileURL) {
          translation = data
          translations[locale] = data
        }
      }
    }

    return translation
  }
}


//  Copyright © 2015 Rob Rix. All rights reserved.

extension Module {
	public static var churchEither: Module {
		let Either = Declaration("Either",
			type: Recur.FunctionType(.Type, .Type, .Type),
			value: Recur.lambda(.Type, .Type, .Type) { L, R, Result in Recur.FunctionType(.FunctionType(L, Result), .FunctionType(R, Result), Result) })

		let left = Declaration("left",
			type: Recur.lambda(.Type, .Type) { L, R in .FunctionType(L, Either.ref[L, R]) },
			value: Recur.lambda(.Type, .Type) { L, R in Recur.lambda(L, .Type) { l, Result in Recur.lambda(.FunctionType(L, Result), .FunctionType(R, Result)) { ifL, _ in ifL[l] } } })

		let right = Declaration("right",
			type: Recur.lambda(.Type, .Type) { L, R in .FunctionType(R, Either.ref[L, R]) },
			value: Recur.lambda(.Type, .Type) { L, R in Recur.lambda(R, .Type) { r, Result in Recur.lambda(.FunctionType(L, Result), .FunctionType(R, Result)) { _, ifR in ifR[r] } } })

		return Module("ChurchEither", [ Either, left, right ])
	}
}

Use the --> and => operators to define ChurchEither.Either.

//  Copyright © 2015 Rob Rix. All rights reserved.

extension Module {
	public static var churchEither: Module {
		let Either = Declaration("Either",
			type: Recur.FunctionType(.Type, .Type, .Type),
			value: (.Type, .Type, .Type) => { L, R, Result in (L --> Result) --> (R --> Result) --> Result })

		let left = Declaration("left",
			type: Recur.lambda(.Type, .Type) { L, R in .FunctionType(L, Either.ref[L, R]) },
			value: Recur.lambda(.Type, .Type) { L, R in Recur.lambda(L, .Type) { l, Result in Recur.lambda(.FunctionType(L, Result), .FunctionType(R, Result)) { ifL, _ in ifL[l] } } })

		let right = Declaration("right",
			type: Recur.lambda(.Type, .Type) { L, R in .FunctionType(R, Either.ref[L, R]) },
			value: Recur.lambda(.Type, .Type) { L, R in Recur.lambda(R, .Type) { r, Result in Recur.lambda(.FunctionType(L, Result), .FunctionType(R, Result)) { _, ifR in ifR[r] } } })

		return Module("ChurchEither", [ Either, left, right ])
	}
}


import Foundation

internal protocol CurrentPathProvider {
    var currentPath: String { get }
}

internal final class DefaultCurrentPathProvider: CurrentPathProvider {
    var currentPath: String {
        return ShellExecutor().execute("pwd").trimmingCharacters(in: .newlines)
    }
}

Use FileManager to get the current directory path

import Foundation

internal protocol CurrentPathProvider {
    var currentPath: String { get }
}

internal final class DefaultCurrentPathProvider: CurrentPathProvider {
    var currentPath: String {
        return FileManager.default.currentDirectoryPath
    }
}


import Foundation

protocol FDatabaseProtocol
{
    var identifier:String? { get set }
    var parent:FDatabaseProtocol? { get set }
    var path:String { get }
    var json:Any? { get }

    init?(json:Any)
}

Add child with identifier method

import Foundation

protocol FDatabaseProtocol
{
    var identifier:String? { get set }
    var parent:FDatabaseProtocol? { get set }
    var path:String { get }
    var json:Any? { get }

    init?(json:Any)

    func child(identifier:String) -> String
}


//
//  ViewController.swift
//  TipCalculator
//
//  Created by Hesham Massoud on 11/12/15.
//  Copyright © 2015 Hesham Massoud. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Add view controller logic for tip calculator

//
//  ViewController.swift
//  TipCalculator
//
//  Created by Hesham Massoud on 11/12/15.
//  Copyright © 2015 Hesham Massoud. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    let tipCalc = TipCalculatorModel(total: 33.25, taxPercantage: 0.06)

    @IBOutlet weak var totalBillTextField: UITextField!
    @IBOutlet weak var taxPercentageSlider: UISlider!
    @IBOutlet weak var taxPercentageLabel: UILabel!
    @IBOutlet weak var resultsTextView: UITextView!

    @IBAction func calculateButtonTapped(sender: AnyObject) {
        tipCalc.total = Double((totalBillTextField.text! as NSString).doubleValue)
        let possibleTips = tipCalc.returnPossibleTips()
        var results = ""
        for (tipPercentage, tipValue) in possibleTips {
            results += "\(tipPercentage)%: \(tipValue)\n"
        }
        resultsTextView.text = results
    }

    @IBAction func taxPercentageChanged(sender: AnyObject) {
        tipCalc.taxPercantage = Double(taxPercentageSlider.value) / 100.0
        refreshUI()
    }

    @IBAction func viewTapped(sender: AnyObject) {
        totalBillTextField.resignFirstResponder()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        refreshUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func refreshUI() {
        totalBillTextField.text = String(tipCalc.total)
        taxPercentageSlider.value = Float(tipCalc.taxPercantage) * 100.0
        taxPercentageLabel.text = "Tax Percentage (\(Int(taxPercentageSlider.value))%)"
        resultsTextView.text = ""
    }

}


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

// We used to crash on this when trying to devirtualize a.doSomething(),
// because a is A<Int> and B is a subclass of A<String>, but not a
// subclass A<Int>. And we were not filtring the results of the
// ClassHierarchyAnalysis to handle such cases properly and
// as a result, we were trying to cast A<Int> into B, which is
// impossible.
//
// rdar://21188939

public class A<T> {
  @inline(never)
  func doSomething() -> Int32 {
    return 100
  }
}

final class B: A<String> {

}

final class C<T>: A<T> {

}

final class D<T>: A<String> {

}

@inline(never)
public func testDevirt(a: A<Int>) -> Int32 {
  return a.doSomething()
}

Fix typo: filtring → filtering

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

// We used to crash on this when trying to devirtualize a.doSomething(),
// because a is A<Int> and B is a subclass of A<String>, but not a
// subclass A<Int>. And we were not filtering the results of the
// ClassHierarchyAnalysis to handle such cases properly and
// as a result, we were trying to cast A<Int> into B, which is
// impossible.
//
// rdar://21188939

public class A<T> {
  @inline(never)
  func doSomething() -> Int32 {
    return 100
  }
}

final class B: A<String> {

}

final class C<T>: A<T> {

}

final class D<T>: A<String> {

}

@inline(never)
public func testDevirt(a: A<Int>) -> Int32 {
  return a.doSomething()
}


// Check that the apple-names section is emitted on Darwin.
// Adapted from llvm/test/DebugInfo/X86/debugger-tune.ll
// RUN: %target-swiftc_driver -emit-object -g %s -o %t
// RUN: llvm-readobj -sections %t | %FileCheck --check-prefix=CHECK-LLDB %s

// CHECK-LLDB-NOT: debug_pubnames
// CHECK-LLDB:     apple_names
// CHECK-LLDB-NOT: debug_pubnames

// REQUIRES: OS=macosx

Update test to use dwarfdump instead of readobj

// Check that the apple-names section is emitted on Darwin.
// Adapted from llvm/test/DebugInfo/X86/debugger-tune.ll
// RUN: %target-swiftc_driver -emit-object -g %s -o %t
// RUN: %llvm-dwarfdump -a %t | %FileCheck --check-prefix=CHECK-LLDB %s

// CHECK-LLDB-NOT: debug_pubnames
// CHECK-LLDB:     apple_names
// CHECK-LLDB-NOT: debug_pubnames

// REQUIRES: OS=macosx


//
//  RadioButton_exampleUITests.swift
//  RadioButton-exampleUITests
//
//  Created by Joe Amanse on 20/11/2015.
//  Copyright © 2015 Joe Christopher Paul Amanse. All rights reserved.
//

import XCTest

class RadioButton_exampleUITests: 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.
        XCUIApplication().launch()

        // 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.
    }

}

Add UI testing in example app

//
//  RadioButton_exampleUITests.swift
//  RadioButton-exampleUITests
//
//  Created by Joe Amanse on 20/11/2015.
//  Copyright © 2015 Joe Christopher Paul Amanse. All rights reserved.
//

import XCTest

class RadioButton_exampleUITests: 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.
        XCUIApplication().launch()

        // 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 testRadioButtonSelection() {
        XCUIDevice.sharedDevice().orientation = .FaceUp

        let button = XCUIApplication().childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Button).element

        let selected = button.selected

        button.tap()
        XCTAssert(button.selected == !selected)

        button.tap()
        XCTAssert(button.selected == selected)
    }
}


import Foundation

public final class Disposable {

    private let dispose: () -> ()

    init(_ dispose: @escaping () -> ()) {
        self.dispose = dispose
    }

    deinit {
        dispose()
    }
}

Add disposal for multiple observers.

import Foundation

public typealias Disposal = [Disposable]

public final class Disposable {

    private let dispose: () -> ()

    init(_ dispose: @escaping () -> ()) {
        self.dispose = dispose
    }

    deinit {
        dispose()
    }

    public func add(to disposal: inout Disposal) {
        disposal.append(self)
    }
}


//
//  AppDelegate.swift
//  Vandelay
//
//  Created by Daniel Saidi on 06/07/2016.
//  Copyright © 2016 Daniel Saidi. All rights reserved.
//

import UIKit
import SwiftyDropbox

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        DropboxClientsManager.setupWithAppKey("4j6q36uumkro49k")
        return true
    }

    func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        if let authResult = DropboxClientsManager.handleRedirectURL(url) {
            switch authResult {
            case .success:
                print("Success! User is logged into Dropbox.")
            case .cancel:
                print("Authorization flow was manually canceled by user!")
            case .error(_, let description):
                print("Error: \(description)")
            }
        }
        return true
    }
}

Move Dropbox key appo separate variable and add warning for missing value

//
//  AppDelegate.swift
//  Vandelay
//
//  Created by Daniel Saidi on 06/07/2016.
//  Copyright © 2016 Daniel Saidi. All rights reserved.
//

import UIKit
import SwiftyDropbox

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var dropboxAppKey = ""

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        if (dropboxAppKey.isEmpty) {
            print("*** IMPORTANT ***")
            print("In order to try Dropbox import/export, you must set the dropboxAppKey value in AppDelegate\n")
        }

        DropboxClientsManager.setupWithAppKey(dropboxAppKey)
        return true
    }

    func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        if let authResult = DropboxClientsManager.handleRedirectURL(url) {
            switch authResult {
            case .success:
                print("Success! User is logged into Dropbox.")
            case .cancel:
                print("Authorization flow was manually canceled by user!")
            case .error(_, let description):
                print("Error: \(description)")
            }
        }
        return true
    }
}


/*
   Copyright 2017 Ryuichi Saito, LLC and the Yanagiba project contributors

   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

import Source
import AST
import Metric

class NestedCodeBlockDepthRule : RuleBase, ASTVisitorRule {
  static let ThresholdKey = "NestedCodeBlockDepth"
  static let DefaultThreshold = 5

  let name = "Nested Code Block Depth"
  let description = ""
  let markdown = ""

  private var threshold: Int {
    if let config = configurations,
      let customThreshold = config[NestedCodeBlockDepthRule.ThresholdKey] as? Int
    {
      return customThreshold
    }
    return NestedCodeBlockDepthRule.DefaultThreshold
  }

  func visit(_ codeBlock: CodeBlock) throws -> Bool {
    let codeBlockDpeth = codeBlock.depth
    if codeBlockDpeth > threshold {
      let foundIssue = Issue(
        ruleIdentifier: identifier,
        description: "Code block depth of \(codeBlockDpeth) exceeds limit of \(threshold)",
        category: .badPractice,
        location: codeBlock.sourceRange,
        severity: .normal,
        correction: nil)
      emitIssue(foundIssue)
    }

    return true
  }
}

Update threshold key to follow consistent naming convension

/*
   Copyright 2017 Ryuichi Saito, LLC and the Yanagiba project contributors

   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

import Source
import AST
import Metric

class NestedCodeBlockDepthRule : RuleBase, ASTVisitorRule {
  static let ThresholdKey = "NESTED_CODE_BLOCK_DEPTH"
  static let DefaultThreshold = 5

  let name = "Nested Code Block Depth"
  let description = ""
  let markdown = ""

  private var threshold: Int {
    if let config = configurations,
      let customThreshold = config[NestedCodeBlockDepthRule.ThresholdKey] as? Int
    {
      return customThreshold
    }
    return NestedCodeBlockDepthRule.DefaultThreshold
  }

  func visit(_ codeBlock: CodeBlock) throws -> Bool {
    let codeBlockDpeth = codeBlock.depth
    if codeBlockDpeth > threshold {
      let foundIssue = Issue(
        ruleIdentifier: identifier,
        description: "Code block depth of \(codeBlockDpeth) exceeds limit of \(threshold)",
        category: .badPractice,
        location: codeBlock.sourceRange,
        severity: .normal,
        correction: nil)
      emitIssue(foundIssue)
    }

    return true
  }
}


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

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

	func testGraphsWithOneParameterAndNoReturnsHaveFunctionType() {
		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

Clarify a test case name.

//  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


// swift-tools-version:3.1

import PackageDescription

let package = Package(
    name: "Stripe",
    targets: [
        Target(name: "Errors"),
        Target(name: "Helpers", dependencies: ["Errors"]),
        Target(name: "Models", dependencies: ["Helpers"]),
        Target(name: "API", dependencies: ["Models", "Errors", "Helpers"]),
        Target(name: "Stripe", dependencies: ["API", "Models", "Errors", "Helpers"]),
    ],
    dependencies: [
        .Package(url: "https://github.com/vapor/vapor.git", Version(2,0,0, prereleaseIdentifiers: ["beta"])),
    ]
)

Update to Vapor 2 release

// swift-tools-version:3.1

import PackageDescription

let package = Package(
    name: "Stripe",
    targets: [
        Target(name: "Errors"),
        Target(name: "Helpers", dependencies: ["Errors"]),
        Target(name: "Models", dependencies: ["Helpers"]),
        Target(name: "API", dependencies: ["Models", "Errors", "Helpers"]),
        Target(name: "Stripe", dependencies: ["API", "Models", "Errors", "Helpers"]),
    ],
    dependencies: [
        .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 2),
    ]
)


// swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "Instructions",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "Instructions",
            targets: ["Instructions"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "Instructions",
            dependencies: []),
    ]
)

Add iOS 9 as minimum version

// swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "Instructions",
    platform: [
        .ios(.v9)
    ],
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "Instructions",
            targets: ["Instructions"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "Instructions",
            dependencies: []),
    ]
)


import Foundation
import FluentProvider

extension ProblemCase: Preparation {

    static func prepare(_ database: Database) throws {
        try database.create(self) { builder in
            builder.id()
            builder.parent(Problem.self, optional: false)
            builder.string("input")
            builder.string("output")
            builder.bool("visible")
        }
    }

    static func revert(_ database: Database) throws {
        try database.delete(self)
    }

}

Extend problem case input column to 2000 chars

import Foundation
import FluentProvider

extension ProblemCase: Preparation {

    static func prepare(_ database: Database) throws {
        try database.create(self) { builder in
            builder.id()
            builder.parent(Problem.self, optional: false)
            builder.string("input", length: 2000)
            builder.string("output")
            builder.bool("visible")
        }
    }

    static func revert(_ database: Database) throws {
        try database.delete(self)
    }

}


// swift-tools-version:5.1
import PackageDescription

let package = Package(
    name: "Differ",
    products: [
        .library(name: "Differ", targets: ["Differ"]),
    ],
    targets: [
        .target(name: "Differ"),
        .testTarget(name: "DifferTests", dependencies: ["Differ"]),
    ]
)

Update Swift tools version to Swift 5.2

// swift-tools-version:5.2
import PackageDescription

let package = Package(
    name: "Differ",
    products: [
        .library(name: "Differ", targets: ["Differ"]),
    ],
    targets: [
        .target(name: "Differ"),
        .testTarget(name: "DifferTests", dependencies: [
            .target(name: "Differ")
        ]),
    ]
)


import PackageDescription

let package = Package(
    name: "Quick",
    targets: [
        Target(name: "QuickTests", dependencies: [.Target(name: "Quick"), .Target(name: "QuickTestHelpers")]),
        Target(name: "QuickFocusedTests", dependencies: [.Target(name: "Quick"), .Target(name: "QuickTestHelpers")]),
        Target(name: "QuickTestHelpers", dependencies: [.Target(name: "Quick")]),
    ],
    // TODO: Once the `test` command has been implemented in the Swift Package Manager, this should be changed to
    // be `testDependencies:` instead. For now it has to be done like this for the library to get linked with the test targets.
    // See: https://github.com/apple/swift-evolution/blob/master/proposals/0019-package-manager-testing.md
    dependencies: [
        .Package(url: "https://github.com/briancroom/Nimble", majorVersion: 3)
    ]
)

Exclude afterSuite tests source in SPM

import PackageDescription

let package = Package(
    name: "Quick",
    exclude: ["Sources/QuickAfterSuiteTests"],
    targets: [
        Target(name: "QuickTests", dependencies: [.Target(name: "Quick"), .Target(name: "QuickTestHelpers")]),
        Target(name: "QuickFocusedTests", dependencies: [.Target(name: "Quick"), .Target(name: "QuickTestHelpers")]),
        Target(name: "QuickTestHelpers", dependencies: [.Target(name: "Quick")]),
    ],
    // TODO: Once the `test` command has been implemented in the Swift Package Manager, this should be changed to
    // be `testDependencies:` instead. For now it has to be done like this for the library to get linked with the test targets.
    // See: https://github.com/apple/swift-evolution/blob/master/proposals/0019-package-manager-testing.md
    dependencies: [
        .Package(url: "https://github.com/briancroom/Nimble", majorVersion: 3)
    ]
)


//
//  DateFormatter+InitWithFormat.swift
//  DayDatePicker
//
//  Created by Hugh Bellamy on 01/02/2018.
//

import Foundation

internal extension DateFormatter {
    convenience init(format: String) {
        self.init()
        self.dateFormat = format
    }
}

Make data formatter extensions public

//
//  DateFormatter+InitWithFormat.swift
//  DayDatePicker
//
//  Created by Hugh Bellamy on 01/02/2018.
//

import Foundation

public extension DateFormatter {
    convenience init(format: String) {
        self.init()
        self.dateFormat = format
    }
}


/**
 * Question Link: https://leetcode.com/problems/merge-two-sorted-lists/
 * Primary idea: Dummy Node to traverse two lists, compare two nodes and point to the right one
 * Time Complexity: O(n), Space Complexity: O(1)
 *
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */

class MergeTwoSortedLists {
    func mergeTwoLists(l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        let dummy = ListNode(0)
        var node = dummy

        var l1 = l1
        var l2 = l2

        while l1 != nil && l2 != nil {
            if l1!.val < l2!.val {
                node.next = l1
                l1 = l1!.next
            } else {
                node.next = l2
                l2 = l2!.next
            }
            node = node.next!
        }

        if l1 != nil {
            node.next = l1
        } else if l2 != nil {
            node.next = l2
        }

        return dummy.next
    }
}

Simplify code style for Merge Two Sorted Lists

/**
 * Question Link: https://leetcode.com/problems/merge-two-sorted-lists/
 * Primary idea: Dummy Node to traverse two lists, compare two nodes and point to the right one
 * Time Complexity: O(n), Space Complexity: O(1)
 *
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */

class MergeTwoSortedLists {
    func mergeTwoLists(l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        let dummy = ListNode(0)
        var node = dummy

        var l1 = l1
        var l2 = l2

        while l1 != nil && l2 != nil {
            if l1!.val < l2!.val {
                node.next = l1
                l1 = l1!.next
            } else {
                node.next = l2
                l2 = l2!.next
            }
            node = node.next!
        }

        node.next = l1 ?? l2

        return dummy.next
    }
}


//
//  PercentEncoding.swift
//  PercentEncoder
//
//  Created by Kazunobu Tasaka on 8/4/15.
//  Copyright (c) 2015 Kazunobu Tasaka. All rights reserved.
//

import Foundation
import JavaScriptCore

public enum PercentEncoding {
    case EncodeURI, EncodeURIComponent, DecodeURI, DecodeURIComponent

    /// return equivalent javascript function name
    private var functionName: String {
        switch self {
        case .EncodeURI:            return "encodeURI"
        case .EncodeURIComponent:   return "encodeURIComponent"
        case .DecodeURI:            return "decodeURI"
        case .DecodeURIComponent:   return "decodeURIComponent"
        }
    }

    public func evaluate(string string: String) -> String {
        // escape back slash, single quote and line terminators because it is not included in ECMAScript SingleStringCharacter
        var escaped = string
        let mapping = [
            "\\": "\\\\",
            "'":  "\\'",
            "\n": "\\n",
            "\r": "\\r",
            "\u{2028}": "\\u2028",
            "\u{2029}": "\\u2029"]
        for (src, dst) in mapping {
            escaped = escaped.stringByReplacingOccurrencesOfString(src, withString: dst)
        }

        let script = "var value = \(functionName)('\(escaped)');"
        let context = JSContext()
        context.evaluateScript(script)
        let value: JSValue = context.objectForKeyedSubscript("value")
        return value.toString()
    }
}

Fix the bug that escaping single quote fails

//
//  PercentEncoding.swift
//  PercentEncoder
//
//  Created by Kazunobu Tasaka on 8/4/15.
//  Copyright (c) 2015 Kazunobu Tasaka. All rights reserved.
//

import Foundation
import JavaScriptCore

public enum PercentEncoding {
    case EncodeURI, EncodeURIComponent, DecodeURI, DecodeURIComponent

    /// return equivalent javascript function name
    private var functionName: String {
        switch self {
        case .EncodeURI:            return "encodeURI"
        case .EncodeURIComponent:   return "encodeURIComponent"
        case .DecodeURI:            return "decodeURI"
        case .DecodeURIComponent:   return "decodeURIComponent"
        }
    }

    public func evaluate(string string: String) -> String {
        // escape back slash, single quote and line terminators because it is not included in ECMAScript SingleStringCharacter
        // * Must use an array to ensure the order to escape the characters.
        let mapping = [
            ("\\", "\\\\"),
            ("'", "\\'"),
            ("\n", "\\n"),
            ("\r", "\\r"),
            ("\u{2028}", "\\u2028"),
            ("\u{2029}", "\\u2029")
        ]

        var escaped = string

        for (src, dst) in mapping {
            escaped = escaped.stringByReplacingOccurrencesOfString(src, withString: dst)
        }

        let script = "var value = \(functionName)('\(escaped)');"
        let context = JSContext()
        context.evaluateScript(script)
        let value: JSValue = context.objectForKeyedSubscript("value")
        return value.toString()
    }
}


//  Copyright (c) 2015 Steve Brambilla. All rights reserved.

import UIKit

extension UIView {
	/// Evaluates the distinct expression and adds the layout constraint to the view.
	///
	/// Returns the layout constraint.
	public func addLayoutExpression(_ expression: DistinctExpressionType) -> NSLayoutConstraint {
		let constraint = evaluateLayoutExpression(expression)
		addConstraint(constraint)
		return constraint
	}

	/// Evaluates the expression and adds the constraints to the view.
	///
	/// Returns the layout constraints.
	public func addLayoutExpression(_ expression: ExpressionType) -> [NSLayoutConstraint] {
		let constraints = evaluateLayoutExpression(expression)
		addConstraints(constraints)
		return constraints
	}

	/// Evaluates the expressions and adds the constraints to the view.
	///
	/// Returns the layout constraints.
	public func addLayoutExpressions(_ expressions: ExpressionType...) -> [NSLayoutConstraint] {
		let constraints = evaluateLayoutExpressions(expressions)
		addConstraints(constraints)
		return constraints
	}
}

Allow unused results when adding constraints

//  Copyright (c) 2015 Steve Brambilla. All rights reserved.

import UIKit

extension UIView {
	/// Evaluates the distinct expression and adds the layout constraint to the view.
	///
	/// Returns the layout constraint.
	@discardableResult
	public func addLayoutExpression(_ expression: DistinctExpressionType) -> NSLayoutConstraint {
		let constraint = evaluateLayoutExpression(expression)
		addConstraint(constraint)
		return constraint
	}

	/// Evaluates the expression and adds the constraints to the view.
	///
	/// Returns the layout constraints.
	@discardableResult
	public func addLayoutExpression(_ expression: ExpressionType) -> [NSLayoutConstraint] {
		let constraints = evaluateLayoutExpression(expression)
		addConstraints(constraints)
		return constraints
	}

	/// Evaluates the expressions and adds the constraints to the view.
	///
	/// Returns the layout constraints.
	@discardableResult
	public func addLayoutExpressions(_ expressions: ExpressionType...) -> [NSLayoutConstraint] {
		let constraints = evaluateLayoutExpressions(expressions)
		addConstraints(constraints)
		return constraints
	}
}


//
//  DataModel10.swift
//  Checklists10
//
//  Created by Karsten Gresch on 11.04.17.
//  Copyright © 2017 Closure One. All rights reserved.
//

import Foundation

class DataModel10 {
  var checklist10s = [Checklist10]()

}

Put the persistence to DataModel which's name should be different e.g. PersistenceManager

//
//  DataModel10.swift
//  Checklists10
//
//  Created by Karsten Gresch on 11.04.17.
//  Copyright © 2017 Closure One. All rights reserved.
//

import Foundation

class DataModel10 {
  var checklist10s = [Checklist10]()

  // Utility methods
  func documentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
  }

  func dataFilePath() -> URL {
    return documentsDirectory().appendingPathComponent("Checklist10.plist")
  }

  func saveChecklist10s() {
    let data = NSMutableData()
    let archiver = NSKeyedArchiver(forWritingWith: data)
    archiver.encode(checklist10s, forKey: "Checklist10s")
    archiver.finishEncoding()
    data.write(to: dataFilePath(), atomically: true)
  }

  func loadChecklist10s() {
    let path = dataFilePath()
    if let data = try? Data(contentsOf: path) {
      let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
      checklist10s = unarchiver.decodeObject(forKey: "Checklist10s") as! [Checklist10]
      unarchiver.finishDecoding()
    }
  }

}


//
//  Path+PolygonProtocol.swift
//  PathTools
//
//  Created by James Bean on 6/17/17.
//
//

import GeometryTools

extension Path {

    /// Creates a `Path` with the given `polygon`.
    public init <P: PolygonProtocol> (_ polygon: P) {
        self.init(polygon.edges.map(BezierCurve.init))
    }
}

Add Path init with vertices

//
//  Path+PolygonProtocol.swift
//  PathTools
//
//  Created by James Bean on 6/17/17.
//
//

import GeometryTools

extension Path {

    /// Creates a `Path` with the given `polygon`.
    public init <P: PolygonProtocol> (_ polygon: P) {
        self.init(polygon.edges.map(BezierCurve.init))
    }
}

extension Path {

    init(vertices: [Point]) {
        switch vertices.count {
        case 0:
            self.init([])
        case 1:
            self.init([BezierCurve(start: vertices[0], end: vertices[0])])
        case 2:
            self.init([BezierCurve(start: vertices[0], end: vertices[1])])
        default:
            let polygon = Polygon(vertices: vertices)
            self.init(polygon)
        }
    }
}


//
//  GitSpec.swift
//  Carthage
//
//  Created by Alan Rogers on 3/11/2014.
//  Copyright (c) 2014 Carthage. All rights reserved.
//

import Foundation
import CarthageKit
import Quick
import Nimble

class GitSpec: CarthageSpec {
    override func spec() {
		var testRepoPath: String!

        beforeEach {
            testRepoPath = self.pathForFixtureRepositoryNamed("simple-repo")
        }

        it("repositoryRemote should send the remote URL") {
			let remote = repositoryRemote(testRepoPath).first().value()
			expect(remote).notTo(beNil())
			expect(remote).to(equal(""))
        }
    }
}

Update the test to check for the actual remote.

//
//  GitSpec.swift
//  Carthage
//
//  Created by Alan Rogers on 3/11/2014.
//  Copyright (c) 2014 Carthage. All rights reserved.
//

import Foundation
import CarthageKit
import Quick
import Nimble

class GitSpec: CarthageSpec {
    override func spec() {
		var testRepoPath: String!

        beforeEach {
            testRepoPath = self.pathForFixtureRepositoryNamed("simple-repo")
			expect(testRepoPath).notTo(beNil())
			println(testRepoPath)
			let exists = NSFileManager.defaultManager().fileExistsAtPath(testRepoPath)
			expect(exists).to(beTruthy())
        }

        it("repositoryRemote should send the remote URL") {
			let remote = repositoryRemote(testRepoPath).first().value()
			expect(remote).notTo(beNil())
			expect(remote).to(equal("https://github.com/carthage/simple-repo.git"))
        }
    }
}


//  Copyright © 2015 Rob Rix. All rights reserved.

final class DeclarationTests: XCTestCase {
	func testDatatypeDeclarationsAddTypesToContext() {
		let expected: Term = .Type
		XCTAssertEqual(booleanModule.context["Boolean"].map(Term.init), expected)
	}

	func testDatatypeDeclarationsAddDataConstructorsToContext() {
		XCTAssertEqual(booleanModule.context["true"].map(Term.init), Term.Variable("Boolean"))
		XCTAssertEqual(booleanModule.context["false"].map(Term.init), Term.Variable("Boolean"))
	}

	func testDatatypeDeclarationsAddDataConstructorsToEnvironment() {
		XCTAssertEqual(booleanModule.environment["true"].map(Term.init), Term.lambda(.BooleanType, const(.Unit)))
		XCTAssertEqual(booleanModule.environment["false"].map(Term.init), Term.lambda(.BooleanType, const(.Unit)))
	}
}

private let booleanModule = Module<Term>([], [
	Declaration.Datatype("Boolean", [
		"true": .End,
		"false": .End,
	])
])

@testable import Manifold
import Prelude
import XCTest

Correct the tests of data constructors.

//  Copyright © 2015 Rob Rix. All rights reserved.

final class DeclarationTests: XCTestCase {
	func testDatatypeDeclarationsAddTypesToContext() {
		let expected: Term = .Type
		XCTAssertEqual(booleanModule.context["Boolean"].map(Term.init), expected)
	}

	func testDatatypeDeclarationsAddDataConstructorsToContext() {
		XCTAssertEqual(booleanModule.context["true"].map(Term.init), Term.Variable("Boolean"))
		XCTAssertEqual(booleanModule.context["false"].map(Term.init), Term.Variable("Boolean"))
	}

	func testDatatypeDeclarationsAddDataConstructorsToEnvironment() {
		XCTAssertEqual(booleanModule.environment["true"].map(Term.init), Term.Product(.Boolean(true), .Unit))
		XCTAssertEqual(booleanModule.environment["false"].map(Term.init), Term.Product(.Boolean(false), .Unit))
	}
}

private let booleanModule = Module<Term>([], [
	Declaration.Datatype("Boolean", [
		"true": .End,
		"false": .End,
	])
])

@testable import Manifold
import Prelude
import XCTest


//
//  NibResource.swift
//  R.swift Library
//
//  Created by Mathijs Kadijk on 06-12-15.
//  Copyright © 2015 Mathijs Kadijk. All rights reserved.
//

import Foundation

/// Represents a nib file on disk
public protocol NibResource {

  /// Bundle this nib is in or nil for main bundle
  var bundle: NSBundle? { get }

  /// Name of the nib file on disk
  var name: String { get }

  /**
   Create a new instance of this nib file

   - returns: A new instance of this nib
  */
  func initialize() -> UINib
}

Implement initialize and instantiate nib methods

//
//  NibResource.swift
//  R.swift Library
//
//  Created by Mathijs Kadijk on 06-12-15.
//  Copyright © 2015 Mathijs Kadijk. All rights reserved.
//

import Foundation

/// Represents a nib file on disk
public protocol NibResource {

  /// Bundle this nib is in or nil for main bundle
  var bundle: NSBundle? { get }

  /// Name of the nib file on disk
  var name: String { get }
}

public extension NibResource {
  /**
   Create a new instance of this nib file

   - returns: A new instance of this nib
   */
  public func initialize() -> UINib {
    return UINib.init(nibName: name, bundle: bundle)
  }

  /**
   Instantiate the nib to get the top-level object from this nib

   - parameter ownerOrNil: The owner, if the owner parameter is nil, connections to File's Owner are not permitted.
   - parameter options: Options are identical to the options specified with -[NSBundle loadNibNamed:owner:options:]

   - returns: An array containing the top-level objects from the NIB
   */
  public func instantiateWithOwner(ownerOrNil: AnyObject?, options optionsOrNil: [NSObject : AnyObject]?) -> [AnyObject] {
    return initialize().instantiateWithOwner(ownerOrNil, options: optionsOrNil)
  }
}


/**
 * Copyright IBM Corporation 2016
 *
 * 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 KituraNet

import Foundation
import XCTest

class ClientTests: XCTestCase {
    var allTests : [(String, () throws -> Void)] {
        return [
            ("testSimpleHttpClient", testSimpleHttpClient)
        ]
    }

    func testSimpleHttpClient() {
        _ = Http.get("http://www.ibm.com") {response in
            XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil")
            XCTAssertEqual(response!.statusCode, HttpStatusCode.OK, "HTTP Status code was \(response!.statusCode)")
            let contentType = response!.headers["Content-Type"]
            XCTAssertNotNil(contentType, "No ContentType header in response")
            XCTAssertEqual(contentType!, "text/html", "Content-Type header wasn't `text/html`")
        }
    }
}

Use XCTestCaseProvider only if on Linux

/**
 * Copyright IBM Corporation 2016
 *
 * 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

import XCTest

@testable import KituraNet

#if os(Linux)
    extension ClientTests : XCTestCaseProvider {
        var allTests : [(String, () throws -> Void)] {
            return [
                ("testSimpleHttpClient", testSimpleHttpClient)
            ]
        }
    }
    #endif

class ClientTests: XCTestCase {

    func testSimpleHttpClient() {
        _ = Http.get("http://www.ibm.com") {response in
            XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil")
            XCTAssertEqual(response!.statusCode, HttpStatusCode.OK, "HTTP Status code was \(response!.statusCode)")
            let contentType = response!.headers["Content-Type"]
            XCTAssertNotNil(contentType, "No ContentType header in response")
            XCTAssertEqual(contentType!, "text/html", "Content-Type header wasn't `text/html`")
        }
    }
}


//
//  ServiceProvider.swift
//  Zero
//
//  Created by Jairo Eli de Leon on 5/8/17.
//  Copyright © 2017 Jairo Eli de León. All rights reserved.
//

protocol ServiceProviderType: class {}

final class ServiceProvider: ServiceProviderType {}

Add Task and UserDefaults to Service Provider

//
//  ServiceProvider.swift
//  Zero
//
//  Created by Jairo Eli de Leon on 5/8/17.
//  Copyright © 2017 Jairo Eli de León. All rights reserved.
//

protocol ServiceProviderType: class {
  var userDefaultsService: UserDefaultsServiceType { get }
  var taskService: TaskServiceType { get }
}

final class ServiceProvider: ServiceProviderType {
  lazy var userDefaultsService: UserDefaultsServiceType = UserDefaultsService(provider: self)
  lazy var taskService: TaskServiceType = TaskService(provider: self)
}


//
//  PolyglotTests.swift
//  PolyglotTests
//
//  Created by Ayaka Nonaka on 7/27/14.
//  Copyright (c) 2014 Ayaka Nonaka. All rights reserved.
//

import UIKit
import XCTest

class PolyglotTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    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() {
        // This is an example of a functional test case.
        XCTAssert(true, "Pass")
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measureBlock() {
            // Put the code you want to measure the time of here.
        }
    }

}

Add blurb in test class

//
//  PolyglotTests.swift
//  PolyglotTests
//
//  Created by Ayaka Nonaka on 7/27/14.
//  Copyright (c) 2014 Ayaka Nonaka. All rights reserved.
//

import UIKit
import XCTest
import Polyglot

class PolyglotTests: XCTestCase {

    // Uhm. I'm pretty sure modules are broken in Xcode 6 Beta 4... Halp.

}


import UIKit

class View<V:ViewMain, M:Model<V>, C:Controller<V, M>>:UIView
{
    private(set) weak var controller:C!

    required init(controller:C)
    {
        super.init(frame:CGRect.zero)
        clipsToBounds = true
        backgroundColor = UIColor.clear
        translatesAutoresizingMaskIntoConstraints = false
        self.controller = controller
    }

    required init?(coder:NSCoder)
    {
        return nil
    }
}

Update generics to swift 4

import UIKit

class View<V, M, C:Controller<V, M>>:UIView
{
    private(set) weak var controller:C!

    required init(controller:C)
    {
        super.init(frame:CGRect.zero)
        clipsToBounds = true
        backgroundColor = UIColor.clear
        translatesAutoresizingMaskIntoConstraints = false
        self.controller = controller
    }

    required init?(coder:NSCoder)
    {
        return nil
    }
}


public struct Template<State> {
  let initial: Node
  let process: (State, Node) -> Node?

  public func step<S>(_ path: KeyPath<State, S>, fn: @escaping (S, Node) -> Node?) -> Template<State> {
    return Template<State>(initial: initial) { state, node in
      guard let update = self.process(state, node) else { return nil }
      return fn(state[keyPath: path], update)
    }
  }

  public func step(fn: @escaping (State, Node) -> Node?) -> Template<State> {
    return Template<State>(initial: initial) { state, node in
      guard let update = self.process(state, node) else { return nil }
      return fn(state, update)
    }
  }

  public func render(state: State) throws -> String {
    guard let node = process(state, initial) else { throw EmptyTemplateError() }
    let renderer = Renderer(.HTML5)
    return try renderer.render(node)
  }
}

extension Template {
  init(_ initial: Node) {
    self.initial = initial
    self.process = { _, node in return node }
  }
}

Allow template steps to be single arity

public struct Template<State> {
  let initial: Node
  let process: (State, Node) -> Node?

  public func step<S>(_ path: KeyPath<State, S>, _ fn: @escaping (S, Node) -> Node?) -> Template<State> {
    return Template<State>(initial: initial) { state, node in
      guard let update = self.process(state, node) else { return nil }
      return fn(state[keyPath: path], update)
    }
  }

  public func step(_ fn: @escaping (State, Node) -> Node?) -> Template<State> {
    return Template<State>(initial: initial) { state, node in
      guard let update = self.process(state, node) else { return nil }
      return fn(state, update)
    }
  }

  public func step(_ fn: @escaping (Node) -> Node?) -> Template<State> {
    return Template<State>(initial: initial) { state, node in
      guard let update = self.process(state, node) else { return nil }
      return fn(update)
    }
  }

  public func render(state: State) throws -> String {
    guard let node = process(state, initial) else { throw EmptyTemplateError() }
    let renderer = Renderer(.HTML5)
    return try renderer.render(node)
  }
}

extension Template {
  init(_ initial: Node) {
    self.initial = initial
    self.process = { _, node in return node }
  }
}


//
//  TestCase.swift
//  Drrrible
//
//  Created by Suyeol Jeon on 19/04/2017.
//  Copyright © 2017 Suyeol Jeon. All rights reserved.
//

import XCTest

import RxSwift

@testable import Drrrible

class TestCase: XCTestCase {
  override func setUp() {
    UIApplication.shared.delegate = MockAppDelegate()
    self.registerDependencies()
  }

  func registerDependencies() {
    DI.autoregister(AuthServiceType.self, initializer: MockAuthService.init)
    DI.autoregister(UserServiceType.self, initializer: MockUserService.init)
    DI.autoregister(ShotServiceType.self, initializer: MockShotService.init).inObjectScope(.container)
    DI.autoregister(AppStoreServiceType.self, initializer: MockAppStoreService.init).inObjectScope(.container)
  }
}

Clear mocks in setUp() and tearDown()

//
//  TestCase.swift
//  Drrrible
//
//  Created by Suyeol Jeon on 19/04/2017.
//  Copyright © 2017 Suyeol Jeon. All rights reserved.
//

import XCTest

import RxSwift

@testable import Drrrible

class TestCase: XCTestCase {
  override func setUp() {
    UIApplication.shared.delegate = MockAppDelegate()
    clearMocks()
  }

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


//
//  Mappings.swift
//  Ashton
//
//  Created by Michael Schwarz on 19.12.17.
//  Copyright © 2017 Michael Schwarz. All rights reserved.
//

#if os(iOS)
    import UIKit
#elseif os(macOS)
    import AppKit
#endif
import Foundation

// Defines mappings between HTML attributes and AttributedString keys
struct Mappings {

    struct UnderlineStyle {
        static let encode: [NSUnderlineStyle.RawValue: String] = [
            NSUnderlineStyle.styleSingle.rawValue: "single",
            NSUnderlineStyle.styleDouble.rawValue: "double",
            NSUnderlineStyle.styleThick.rawValue: "thick"
        ]
        static let decode: [String: NSUnderlineStyle] = [
            "single": .styleSingle,
            "double": .styleDouble,
            "thick": .styleThick
        ]
    }

    struct TextAlignment {
        static let encode: [NSTextAlignment: String] = [
            .left: "left",
            .center: "center",
            .right: "right",
            .justified: "justify",
            .natural: "left"
        ]
        static let decode: [String: NSTextAlignment] = [
            "left": .left,
            "center": .center,
            "right": .right,
            "justify": .justified
        ]
    }

    struct TextDecoration {
        static let decode: [String: NSAttributedStringKey] = [
            "underline": .underlineStyle,
            "line-through": .strikethroughStyle
        ]
    }
}

Remove textAlignment mapping from natural to left

//
//  Mappings.swift
//  Ashton
//
//  Created by Michael Schwarz on 19.12.17.
//  Copyright © 2017 Michael Schwarz. All rights reserved.
//

#if os(iOS)
    import UIKit
#elseif os(macOS)
    import AppKit
#endif
import Foundation

// Defines mappings between HTML attributes and AttributedString keys
struct Mappings {

    struct UnderlineStyle {
        static let encode: [NSUnderlineStyle.RawValue: String] = [
            NSUnderlineStyle.styleSingle.rawValue: "single",
            NSUnderlineStyle.styleDouble.rawValue: "double",
            NSUnderlineStyle.styleThick.rawValue: "thick"
        ]
        static let decode: [String: NSUnderlineStyle] = [
            "single": .styleSingle,
            "double": .styleDouble,
            "thick": .styleThick
        ]
    }

    struct TextAlignment {
        static let encode: [NSTextAlignment: String] = [
            .left: "left",
            .center: "center",
            .right: "right",
            .justified: "justify"
        ]
        static let decode: [String: NSTextAlignment] = [
            "left": .left,
            "center": .center,
            "right": .right,
            "justify": .justified
        ]
    }

    struct TextDecoration {
        static let decode: [String: NSAttributedStringKey] = [
            "underline": .underlineStyle,
            "line-through": .strikethroughStyle
        ]
    }
}


//
//  StoryboardResource.swift
//  R.swift.Library
//
//  Created by Mathijs Kadijk on 07-01-16.
//  Copyright © 2016 Mathijs Kadijk. All rights reserved.
//

import Foundation
import UIKit

public protocol StoryboardResourceType {

  /// Bundle this storyboard is in or nil for main bundle
  var bundle: NSBundle? { get }

  /// Name of the storyboard file on disk
  var name: String { get }
}

public protocol StoryboardResourceWithInitialControllerType: StoryboardResourceType {

  /// Type of the inital controller
  typealias InitialController
}

Remove unused UIKit import from Core

//
//  StoryboardResource.swift
//  R.swift.Library
//
//  Created by Mathijs Kadijk on 07-01-16.
//  Copyright © 2016 Mathijs Kadijk. All rights reserved.
//

import Foundation

public protocol StoryboardResourceType {

  /// Bundle this storyboard is in or nil for main bundle
  var bundle: NSBundle? { get }

  /// Name of the storyboard file on disk
  var name: String { get }
}

public protocol StoryboardResourceWithInitialControllerType: StoryboardResourceType {

  /// Type of the inital controller
  typealias InitialController
}


//
//  dispatchqos.swift
//  deferred
//
//  Created by Guillaume Lessard on 31/08/2016.
//  Copyright © 2016 Guillaume Lessard. All rights reserved.
//

import Dispatch

extension DispatchQoS
{
  public static func current(fallback: DispatchQoS.QoSClass = .utility) -> DispatchQoS
  {
    let qos = DispatchQoS.QoSClass(rawValue: qos_class_self()) ?? fallback
    return DispatchQoS(qosClass: qos, relativePriority: 0)
  }
}

Make the DispatchQoS extension internal when building from Xcode

//
//  dispatchqos.swift
//  deferred
//
//  Created by Guillaume Lessard on 31/08/2016.
//  Copyright © 2016 Guillaume Lessard. All rights reserved.
//

import Dispatch

extension DispatchQoS
{
#if SWIFT_PACKAGE
  public static func current(fallback: DispatchQoS.QoSClass = .utility) -> DispatchQoS
  {
    let qos = DispatchQoS.QoSClass(rawValue: qos_class_self()) ?? fallback
    return DispatchQoS(qosClass: qos, relativePriority: 0)
  }
#else
  static func current(fallback: DispatchQoS.QoSClass = .utility) -> DispatchQoS
  {
    let qos = DispatchQoS.QoSClass(rawValue: qos_class_self()) ?? fallback
    return DispatchQoS(qosClass: qos, relativePriority: 0)
  }
#endif
}


//
//  JSONTypes.swift
//  SwiftyJSONModel
//
//  Created by Oleksii on 18/09/16.
//  Copyright © 2016 Oleksii Dykan. All rights reserved.
//

import Foundation
import SwiftyJSON

public protocol JSONInitializable {
    init(json: JSON) throws
}

public protocol JSONRepresantable {
    var jsonValue: JSON { get }
}

Extend basic types with JSON representable

//
//  JSONTypes.swift
//  SwiftyJSONModel
//
//  Created by Oleksii on 18/09/16.
//  Copyright © 2016 Oleksii Dykan. All rights reserved.
//

import Foundation
import SwiftyJSON

public protocol JSONInitializable {
    init(json: JSON) throws
}

public protocol JSONRepresantable {
    var jsonValue: JSON { get }
}

extension String: JSONRepresantable {
    public var jsonValue: JSON { return JSON(self) }
}

extension Bool: JSONRepresantable {
    public var jsonValue: JSON { return JSON(self) }
}

extension Int: JSONRepresantable {
    public var jsonValue: JSON { return JSON(self) }
}

extension Double: JSONRepresantable {
    public var jsonValue: JSON { return JSON(self) }
}


//
// This playground must be opened using the enclosed workspace in order for the
// ObjectiveGit module to be available.
//
import ObjectiveGit

let url = NSURL(string: "https://github.com/phatblat/objective-git.git") as NSURL?
let workdirURL = NSURL(string: "/tmp/objective-git") as NSURL?
var error: NSError? = nil

let repo = GTRepository.cloneFromURL(url!, toWorkingDirectory: workdirURL!, options: [:], error: &error,
    transferProgressBlock: { (gt_progress, stop) -> Void in
        // transferProgressBlock:^(const git_transfer_progress *gt_progress, BOOL *stop) {
        println()
    }, checkoutProgressBlock: { (path, completedSteps, totalSteps) -> Void in
        // checkoutProgressBlock:^(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps) {
        println()
    }
)

if let myError = error {
    println("\(myError)")
}

Add forced downcast to GTRepository

//
// This playground must be opened using the enclosed workspace in order for the
// ObjectiveGit module to be available.
//
import ObjectiveGit

let url = NSURL(string: "https://github.com/phatblat/objective-git.git") as NSURL?
let workdirURL = NSURL(string: "/tmp/objective-git") as NSURL?
var error: NSError? = nil

let repo = GTRepository.cloneFromURL(url!, toWorkingDirectory: workdirURL!, options: [:], error: &error,
    transferProgressBlock: { (gt_progress, stop) -> Void in
        // transferProgressBlock:^(const git_transfer_progress *gt_progress, BOOL *stop) {
        println()
    }, checkoutProgressBlock: { (path, completedSteps, totalSteps) -> Void in
        // checkoutProgressBlock:^(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps) {
        println()
    }
) as! GTRepository

if let myError = error {
    println("\(myError)")
}


//
//  VersionNumberService.swift
//  LaunchCount
//
//  Created by Ben Norris on 3/8/16.
//  Copyright © 2016 BSN Design. All rights reserved.
//

import Foundation

public struct VersionNumberService {

    // MARK: - Public properties

    public var currentVersionShort: String? {
        return NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String
    }

    public var currentVersionFull: String? {
        return NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String
    }

}

Add public initializer for version number service

//
//  VersionNumberService.swift
//  LaunchCount
//
//  Created by Ben Norris on 3/8/16.
//  Copyright © 2016 BSN Design. All rights reserved.
//

import Foundation

public struct VersionNumberService {

    // MARK: - Public properties

    public var currentVersionShort: String? {
        return NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String
    }

    public var currentVersionFull: String? {
        return NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String
    }

    // MARK: - Initializers

    public init() { }

}


//
//  Error.swift
//  mas-cli
//
//  Created by Andrew Naylor on 21/08/2015.
//  Copyright (c) 2015 Andrew Naylor. All rights reserved.
//

public let MASErrorDomain: String = "MASErrorDomain"

private let MASErrorSource: String = "MASErrorSource"

public enum MASErrorCode: Int {
    case noError
    case notSignedIn
    case purchaseError
    case noDownloads
    case cancelled
    case downloadFailed
    case signInError
    case alreadySignedIn
    case searchError
    case noSearchResultsFound
    case noUpdatesFound

    var exitCode: Int32 {
        return Int32(self.rawValue)
    }
}

public struct MASError: Error {
    let code: MASErrorCode

    let sourceError: NSError?

    init(code: MASErrorCode, sourceError: NSError? = nil) {
        self.code = code
        self.sourceError = sourceError
    }
}

public func == (lhs: MASError, rhs: MASError) -> Bool {
    return false
}

Fix weird Swift compiler error

//
//  Error.swift
//  mas-cli
//
//  Created by Andrew Naylor on 21/08/2015.
//  Copyright (c) 2015 Andrew Naylor. All rights reserved.
//

public let MASErrorDomain: String = "MASErrorDomain"

private let MASErrorSource: String = "MASErrorSource"

public enum MASErrorCode: Int {
    case noError
    case notSignedIn
    case purchaseError
    case noDownloads
    case cancelled
    case downloadFailed
    case signInError
    case alreadySignedIn
    case searchError
    case noSearchResultsFound
    case noUpdatesFound

    var exitCode: Int32 {
        return Int32(self.rawValue)
    }
}

open class MASError: Error {
    let code: MASErrorCode

    let sourceError: NSError?

    init(code: MASErrorCode, sourceError: NSError? = nil) {
        self.code = code
        self.sourceError = sourceError
    }
}

public func == (lhs: MASError, rhs: MASError) -> Bool {
    return false
}


//  Copyright © 2015 Rob Rix. All rights reserved.

final class ChurchBooleanTests: XCTestCase {
	func testModuleTypechecks() {
		module.typecheck().forEach { XCTFail($0.description) }
	}

	func testTrueReturnsItsFirstTermArgument() {
		assert(`true`[.Type, .Boolean(true), .Boolean(false)].evaluate(module.environment), ==, true)
	}
}

private let module = Module<Term>.churchBoolean
private let `true`: Term = "true"

import Assertions
import Manifold
import XCTest

Test the evaluation of `false`.

//  Copyright © 2015 Rob Rix. All rights reserved.

final class ChurchBooleanTests: XCTestCase {
	func testModuleTypechecks() {
		module.typecheck().forEach { XCTFail($0.description) }
	}

	func testTrueReturnsItsFirstTermArgument() {
		assert(`true`[.Type, .Boolean(true), .Boolean(false)].evaluate(module.environment), ==, true)
	}

	func testFalseReturnsItsSecondTermArgument() {
		assert(`false`[.Type, .Boolean(true), .Boolean(false)].evaluate(module.environment), ==, false)
	}
}

private let module = Module<Term>.churchBoolean
private let `true`: Term = "true"
private let `false`: Term = "false"

import Assertions
import Manifold
import XCTest