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

import PackageDescription

let package = Package(
    name: "pega-texto",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "pega-texto",
            targets: ["pega-texto"]),
    ],
    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: "pega-texto",
            dependencies: [],
            path: "./src",
            publicHeadersPath: "./include/**.h",
            cSettings: [CSetting.headerSearchPath("../include")])
    ]
)

Change path to include public headers, exclude some directories

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

import PackageDescription

let package = Package(
    name: "pega-texto",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "pega-texto",
            targets: ["pega-texto"]),
    ],
    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: "pega-texto",
            dependencies: [],
            path: "./",
            exclude: ["benchmark", "cmake", "doc", "examples", "test"],
            publicHeadersPath: "./include",
            cSettings: [CSetting.headerSearchPath("./include")])
    ]
)


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

import PackageDescription

let package = Package(
    name: "DKPhotoGallery",
    products: [
        .library(
            name: "DKPhotoGallery",
            targets: ["DKPhotoGallery"]),
    ],
    dependencies: [
        .package(url: "https://github.com/kirualex/SwiftyGif.git", from: "5.3.0"),
    ],
    targets: [
        .target(
            name: "DKPhotoGallery",
            dependencies: [],
            path: "DKPhotoGallery"),
    ]
)

Fix header search path setting

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

import PackageDescription

let package = Package(
    name: "DKPhotoGallery",
    products: [
        .library(
            name: "DKPhotoGallery",
            targets: ["DKPhotoGallery"]),
    ],
    dependencies: [
        .package(url: "https://github.com/kirualex/SwiftyGif.git", from: "5.3.0"),
    ],
    targets: [
        .target(
            name: "DKPhotoGallery",
            dependencies: ["SwiftyGif"],
            path: "DKPhotoGallery",
            cSettings: [
                .headerSearchPath(".")
            ]),
    ]
)


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

import PackageDescription

let package = Package(
    name: "CountryCode",
    platforms: [
        .iOS(.v8)
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "CountryCode",
            targets: ["CountryCode"]),
    ],
    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 this package depends on.
        .target(
            name: "CountryCode",
            dependencies: [],
            path: "CountryPicker",
            resources: [
                .copy("Assets")]
        ),
        .testTarget(
            name: "CountryCodeTests",
            dependencies: ["CountryCode"]),
    ]
)

Fix SPM support to explicitly include `CountryPicker.bundle` as a resource, otherwise `countryCodes.json` may not be included. Because of the `guard let` on line 188 of `CountryPicker.swift`, failure to load the JSON silently fails and returns an empty set.

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

import PackageDescription

let package = Package(
    name: "CountryCode",
    platforms: [
        .iOS(.v8)
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "CountryCode",
            targets: ["CountryCode"]),
    ],
    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 this package depends on.
        .target(
            name: "CountryCode",
            dependencies: [],
            path: "CountryPicker",
            resources: [
                .copy("Assets/CountryPicker.bundle")]
        ),
        .testTarget(
            name: "CountryCodeTests",
            dependencies: ["CountryCode"]),
    ]
)


// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "FuntastyKit",
    platforms: [.iOS(.v9)],
    products: [
        .library(
            name: "FuntastyKit",
            targets: ["FuntastyKit"])
    ],
    dependencies: [
        .package(url: "https://github.com/realm/SwiftLint.git", from: "0.33.0")
    ],
    targets: [
        .target(
            name: "FuntastyKit",
            dependencies: []),
        .testTarget(
            name: "FuntastyKitTests",
            dependencies: ["FuntastyKit"])
    ]
)

Remove SwiftLint from package dependencies

// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "FuntastyKit",
    platforms: [.iOS(.v9)],
    products: [
        .library(
            name: "FuntastyKit",
            targets: ["FuntastyKit"])
    ],
    targets: [
        .target(
            name: "FuntastyKit",
            dependencies: []),
        .testTarget(
            name: "FuntastyKitTests",
            dependencies: ["FuntastyKit"])
    ]
)


import CoreData

@objc(DealerCategory)
public class DealerCategory: NSManagedObject {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<DealerCategory> {
        return NSFetchRequest<DealerCategory>(entityName: "DealerCategory")
    }

    @NSManaged public var name: String
    @NSManaged public var dealers: Set<Dealer>

}

// MARK: - Fetching

extension DealerCategory {

    static func named(name: String, in managedObjectContext: NSManagedObjectContext) -> DealerCategory {
        let fetchRequest = Self.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "name == %@", name)
        let results = try? managedObjectContext.fetch(fetchRequest)

        if let existingCategory = results?.first {
            return existingCategory
        } else {
            let category = DealerCategory(context: managedObjectContext)
            category.name = name
            return category
        }
    }

}

// MARK: Generated accessors for dealers
extension DealerCategory {

    @objc(addDealersObject:)
    @NSManaged func addToDealers(_ value: Dealer)

    @objc(removeDealersObject:)
    @NSManaged func removeFromDealers(_ value: Dealer)

    @objc(addDealers:)
    @NSManaged func addToDealers(_ values: Set<Dealer>)

    @objc(removeDealers:)
    @NSManaged func removeFromDealers(_ values: Set<Dealer>)

}

Enable dealer categories to be used in ForEach

import CoreData

@objc(DealerCategory)
public class DealerCategory: NSManagedObject {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<DealerCategory> {
        return NSFetchRequest<DealerCategory>(entityName: "DealerCategory")
    }

    @NSManaged public var name: String
    @NSManaged public var dealers: Set<Dealer>

}

// MARK - DealerCategory + Identifiable

extension DealerCategory: Identifiable {

    public var id: some Hashable {
        objectID
    }

}

// MARK: - Fetching

extension DealerCategory {

    static func named(name: String, in managedObjectContext: NSManagedObjectContext) -> DealerCategory {
        let fetchRequest = Self.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "name == %@", name)
        let results = try? managedObjectContext.fetch(fetchRequest)

        if let existingCategory = results?.first {
            return existingCategory
        } else {
            let category = DealerCategory(context: managedObjectContext)
            category.name = name
            return category
        }
    }

}

// MARK: Generated accessors for dealers
extension DealerCategory {

    @objc(addDealersObject:)
    @NSManaged func addToDealers(_ value: Dealer)

    @objc(removeDealersObject:)
    @NSManaged func removeFromDealers(_ value: Dealer)

    @objc(addDealers:)
    @NSManaged func addToDealers(_ values: Set<Dealer>)

    @objc(removeDealers:)
    @NSManaged func removeFromDealers(_ values: Set<Dealer>)

}


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)
    ]
)

Change Nimble to my fork for test

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/norio-nomura/Nimble", majorVersion: 3)
    ]
)


//
//  NSBundle+Applivery.swift
//  AppliverySDK
//
//  Created by Alejandro Jiménez on 18/1/16.
//  Copyright © 2016 Applivery S.L. All rights reserved.
//

import Foundation

extension Bundle {

	class func applivery() -> Bundle {
		return Bundle(for: Applivery.self)
	}

}

Load bundle for static framework, if fails, load for Dynamic framework

//
//  NSBundle+Applivery.swift
//  AppliverySDK
//
//  Created by Alejandro Jiménez on 18/1/16.
//  Copyright © 2016 Applivery S.L. All rights reserved.
//

import Foundation

extension Bundle {

	class func applivery() -> Bundle {
		Bundle(for: Applivery.self)
			.url(forResource: "Applivery", withExtension: "bundle")
			.flatMap(Bundle.init(url:))
			?? Bundle(for: Applivery.self)
	}

}


//
//  ViewController.swift
//  FilbertSteps
//
//  Created by Mike Lazer-Walker on 12/28/15.
//  Copyright © 2015 Mike Lazer-Walker. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate {
    let synthesizer = AVSpeechSynthesizer()

    var game:Game?
    var activePassageId:String?

    override func viewDidLoad() {
        super.viewDidLoad()

        let game = Game()

        game.addOutputs([
            "textToSpeech": TextToSpeechOutput(),
            "mp3": AudioOutput()
        ])

        game.addInputs([
            "proximity": ProximitySensor(threshold: 2),
            "headphones": HeadphoneSensor(),
            "altimeter": AltimeterSensor(),
            "device": DeviceSensor()
        ])

        self.game = game
        game.start()
    }
}

Rename text to speech output

//
//  ViewController.swift
//  FilbertSteps
//
//  Created by Mike Lazer-Walker on 12/28/15.
//  Copyright © 2015 Mike Lazer-Walker. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate {
    let synthesizer = AVSpeechSynthesizer()

    var game:Game?
    var activePassageId:String?

    override func viewDidLoad() {
        super.viewDidLoad()

        let game = Game()

        game.addOutputs([
            "speech": TextToSpeechOutput(),
            "mp3": AudioOutput()
        ])

        game.addInputs([
            "proximity": ProximitySensor(threshold: 2),
            "headphones": HeadphoneSensor(),
            "altimeter": AltimeterSensor(),
            "device": DeviceSensor()
        ])

        self.game = game
        game.start()
    }
}


//
//  RHCTodayCell.swift
//  VindsidenApp
//
//  Created by Ragnar Henriksen on 10.07.14.
//  Copyright (c) 2014 RHC. All rights reserved.
//

import UIKit

extension UITableViewCell {

    func configureSelectedBackgroundView() -> Void
    {
        let vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect.notificationCenterVibrancyEffect())
        vibrancyView.frame = self.contentView.bounds

        let view = UIView(frame: vibrancyView.bounds)
        view.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
        vibrancyView.contentView.addSubview(view)
        self.selectedBackgroundView = vibrancyView
    }
}

class RHCTodayCell: UITableViewCell
{
    @IBOutlet weak var arrowImageView: UIImageView!
    @IBOutlet weak var speedLabel: UILabel!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var updatedLabel: UILabel!
    @IBOutlet weak var unitLabel: UILabel!
}

Clear today cell before use

//
//  RHCTodayCell.swift
//  VindsidenApp
//
//  Created by Ragnar Henriksen on 10.07.14.
//  Copyright (c) 2014 RHC. All rights reserved.
//

import UIKit

extension UITableViewCell {

    func configureSelectedBackgroundView() -> Void
    {
        let vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect.notificationCenterVibrancyEffect())
        vibrancyView.frame = self.contentView.bounds

        let view = UIView(frame: vibrancyView.bounds)
        view.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
        vibrancyView.contentView.addSubview(view)
        self.selectedBackgroundView = vibrancyView
    }
}

class RHCTodayCell: UITableViewCell
{
    @IBOutlet weak var arrowImageView: UIImageView!
    @IBOutlet weak var speedLabel: UILabel!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var updatedLabel: UILabel!
    @IBOutlet weak var unitLabel: UILabel!

    func clearCell() {
        self.arrowImageView.image = nil
        self.speedLabel.text = " "
        self.nameLabel.text = " "
        self.updatedLabel.text = " "
        self.unitLabel.text = " "
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        clearCell()
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        clearCell()
    }
}


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

final class ErrorTests: XCTestCase {
	func testLiftedParsersDoNotReportErrorsWhenTheyMatch() {
		let parser = %"x"
		let input = "x"
		assert(parser(input, input.startIndex).right, !=, nil)
		assert(parser(input, input.startIndex).left, ==, nil)
	}

	func testLiftedParsersReportErrorsWhenTheyDoNotMatch() {
		let parser = %"x"
		let input = "y"
		assert(parser(input, input.startIndex).right, ==, nil)
		assert(parser(input, input.startIndex).left, !=, nil)
	}

	func testParseError() {
		assert(parse(lambda, "λx.").left?.depth, ==, 5)
	}
}

// MARK: - Imports

import Assertions
import Madness
import XCTest

Test that errors get the correct name.

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

final class ErrorTests: XCTestCase {
	func testLiftedParsersDoNotReportErrorsWhenTheyMatch() {
		let parser = %"x"
		let input = "x"
		assert(parser(input, input.startIndex).right, !=, nil)
		assert(parser(input, input.startIndex).left, ==, nil)
	}

	func testLiftedParsersReportErrorsWhenTheyDoNotMatch() {
		let parser = %"x"
		let input = "y"
		assert(parser(input, input.startIndex).right, ==, nil)
		assert(parser(input, input.startIndex).left, !=, nil)
	}

	func testParseError() {
		assert(parse(lambda, "λx.").left?.depth, ==, 5)
	}

	func testParseNaming() {
		assert(parse(lambda |> describeAs("lambda"), "λx.").left, !=, nil)
	}
}

// MARK: - Imports

import Assertions
import Madness
import Prelude
import XCTest


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

extension CollectionType {
	public var uncons: (first: SubSequence._Element, rest: SubSequence)? {
		if !isEmpty {
			let some = self[startIndex..<startIndex.advancedBy(1)]
			return (first: some[some.startIndex], rest: dropFirst())
		}
		return nil
	}

	public var rest: SubSequence {
		return isEmpty
			? self[startIndex..<endIndex]
			: dropFirst()
	}
}

extension CollectionType where SubSequence: CollectionType, SubSequence.SubSequence == SubSequence {
	public var conses: AnyGenerator<(first: SubSequence._Element, rest: SubSequence)> {
		var current = uncons
		return anyGenerator {
			let next = current
			current = current?.rest.uncons
			return next
		}
	}

	public func fold<Out>(initial: Out, @noescape combine: (SubSequence._Element, Out) -> Out) -> Out {
		return self[indices].fold(initial, combine: combine)
	}
}

extension CollectionType where SubSequence == Self {
	public func fold<Out>(initial: Out, @noescape combine: (Generator.Element, Out) -> Out) -> Out {
		return first.map {
			combine($0, dropFirst().fold(initial, combine: combine))
		} ?? initial
	}
}

Revert "Add a fold overload that will work on Array."

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

extension CollectionType {
	public var uncons: (first: SubSequence._Element, rest: SubSequence)? {
		if !isEmpty {
			let some = self[startIndex..<startIndex.advancedBy(1)]
			return (first: some[some.startIndex], rest: dropFirst())
		}
		return nil
	}

	public var rest: SubSequence {
		return isEmpty
			? self[startIndex..<endIndex]
			: dropFirst()
	}
}

extension CollectionType where SubSequence: CollectionType, SubSequence.SubSequence == SubSequence {
	public var conses: AnyGenerator<(first: SubSequence._Element, rest: SubSequence)> {
		var current = uncons
		return anyGenerator {
			let next = current
			current = current?.rest.uncons
			return next
		}
	}
}

extension CollectionType where SubSequence == Self {
	public func fold<Out>(initial: Out, @noescape combine: (Generator.Element, Out) -> Out) -> Out {
		return first.map {
			combine($0, dropFirst().fold(initial, combine: combine))
		} ?? initial
	}
}


//
//  main.swift
//  AudioKit
//
//  Auto-generated on 12/28/14.
//  Customized by Aurelius Prochazka on 12/28/14.
//
//  Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//

import Foundation

class Instrument : AKInstrument {

    override init() {
        super.init()

        let filename = "CsoundLib64.framework/Sounds/808loop.wav"

        let soundFile = AKSoundFile(filename: filename)
        connect(soundFile)

        let speed = AKLine(firstPoint: 3.ak, secondPoint: 0.5.ak, durationBetweenPoints: 10.ak)
        connect(speed)

        let operation = AKFunctionTableLooper(functionTable: soundFile)
        operation.endTime = 9.6.ak
        operation.transpositionRatio = speed
        operation.loopMode = AKFunctionTableLooperMode.ForwardAndBack
        connect(operation)

        connect(AKAudioOutput(audioSource:operation))
    }
}

// Set Up
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
AKManager.sharedManager().isLogging = true
AKOrchestra.testForDuration(10)

instrument.play()

while(AKManager.sharedManager().isRunning) {} //do nothing
println("Test complete!")

Use mono file in AKFunctionTableLooper test

//
//  main.swift
//  AudioKit
//
//  Auto-generated on 12/28/14.
//  Customized by Aurelius Prochazka on 12/28/14.
//
//  Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//

import Foundation

class Instrument : AKInstrument {

    override init() {
        super.init()

        let filename = "CsoundLib64.framework/Sounds/mandpluk.aif"

        let soundFile = AKSoundFile(filename: filename)
        connect(soundFile)

        let speed = AKLine(firstPoint: 3.ak, secondPoint: 0.5.ak, durationBetweenPoints: 10.ak)
        connect(speed)

        let operation = AKFunctionTableLooper(functionTable: soundFile)
        operation.endTime = 9.6.ak
        operation.transpositionRatio = speed
        operation.loopMode = AKFunctionTableLooperMode.ForwardAndBack
        connect(operation)

        connect(AKAudioOutput(audioSource:operation))
    }
}

// Set Up
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
AKManager.sharedManager().isLogging = true
AKOrchestra.testForDuration(10)

instrument.play()

while(AKManager.sharedManager().isRunning) {} //do nothing
println("Test complete!")


//
//  SearchPerformanceTests.swift
//  SwiftGraphTests
//
//  Copyright (c) 2018 Ferran Pujol Camins
//
//  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 XCTest
@testable import SwiftGraph

class SearchPerformanceTests: XCTestCase {
    func testDfsInStarGraph() {
        let g = StarGraph.build(withCenter: 0, andLeafs: Array(1...999999))
        self.measure {
            _ = g.dfs(from: 0, goalTest: { _ in false })
        }
    }

    static var allTests = [
        ("testDfsInStarGraph", testDfsInStarGraph),
    ]
}

Add more performance tests for Dfs

//
//  SearchPerformanceTests.swift
//  SwiftGraphTests
//
//  Copyright (c) 2018 Ferran Pujol Camins
//
//  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 XCTest
@testable import SwiftGraph

class SearchPerformanceTests: XCTestCase {
    func testDfsInStarGraph() {
        let g = StarGraph.build(withCenter: 0, andLeafs: Array(1...999999))
        self.measure {
            _ = g.dfs(from: 0, goalTest: { _ in false })
        }
    }

    func testDfsInPath() {
        let g = UnweightedGraph(withPath: Array(0...999999))
        self.measure {
            _ = g.dfs(from: 0, goalTest: { _ in false })
        }
    }

    func testDfsInCompleteGraph() {
        let g = CompleteGraph.build(withVertices: Array(0...249))
        self.measure {
            _ = g.dfs(from: 0, goalTest: { _ in false })
        }
    }

    static var allTests = [
        ("testDfsInStarGraph", testDfsInStarGraph),
        ("testDfsInPath", testDfsInPath),
        ("testDfsInCompleteGraph", testDfsInCompleteGraph)
    ]
}


import XCTest
import OHHTTPStubs
import APIKit

class RequestTests: XCTestCase {
    override func tearDown() {
        OHHTTPStubs.removeAllStubs()
        super.tearDown()
    }

    func testURLQueryParameterEncoding() {
        struct SearchRequest: MockAPIRequest {
            let query: String

            // MARK: Request
            typealias Response = [String: AnyObject]

            var method: HTTPMethod {
                return .GET
            }

            var path: String {
                return "/"
            }

            var parameters: [String: AnyObject] {
                return [
                    "q": query,
                ]
            }

            func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) -> Response? {
                return object as? [String: AnyObject]
            }
        }

        OHHTTPStubs.stubRequestsPassingTest({ request in
            XCTAssert(request.URL?.query == "q=%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF")
            return true
        }, withStubResponse: { request in
            return OHHTTPStubsResponse(data: NSData(), statusCode: 200, headers: nil)
        })

        let request = SearchRequest(query: "こんにちは")
        let expectation = expectationWithDescription("waiting for the response.")

        API.sendRequest(request) { result in
            expectation.fulfill()
        }

        waitForExpectationsWithTimeout(1.0, handler: nil)
    }
}

Move dummy type for testing

import XCTest
import OHHTTPStubs
import APIKit

class RequestTests: XCTestCase {
    struct SearchRequest: MockAPIRequest {
        let query: String

        // MARK: Request
        typealias Response = [String: AnyObject]

        var method: HTTPMethod {
            return .GET
        }

        var path: String {
            return "/"
        }

        var parameters: [String: AnyObject] {
            return [
                "q": query,
            ]
        }

        func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) -> Response? {
            return object as? [String: AnyObject]
        }
    }

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

    func testURLQueryParameterEncoding() {
        OHHTTPStubs.stubRequestsPassingTest({ request in
            XCTAssert(request.URL?.query == "q=%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF")
            return true
        }, withStubResponse: { request in
            return OHHTTPStubsResponse(data: NSData(), statusCode: 200, headers: nil)
        })

        let request = SearchRequest(query: "こんにちは")
        let expectation = expectationWithDescription("waiting for the response.")

        API.sendRequest(request) { result in
            expectation.fulfill()
        }

        waitForExpectationsWithTimeout(1.0, handler: nil)
    }
}


import Foundation
import Argo
import Result

public struct APIClient {
  fileprivate let requestPerformer: RequestPerformer
  fileprivate let deserializer: Deserializer
  fileprivate let scheduler: Scheduler

  public init(requestPerformer: RequestPerformer = NetworkRequestPerformer(), deserializer: Deserializer = JSONDeserializer(), scheduler: @escaping Scheduler = mainQueueScheduler) {
    self.requestPerformer = requestPerformer
    self.deserializer = deserializer
    self.scheduler = scheduler
  }
}

extension APIClient: Client {
  @discardableResult
  public func perform<T: Request>(_ request: T, completionHandler: @escaping (Result<T.ResponseObject, SwishError>) -> Void) -> URLSessionDataTask {
    return requestPerformer.perform(request.build()) { [schedule = scheduler] result in
      let object = result
        >>- self.validate
        >>- self.deserializer.deserialize
        >>- T.ResponseParser.parse
        >>- request.parse

      schedule { completionHandler(object) }
    }
  }
}

private extension APIClient {
  func validate(_ httpResponse: HTTPResponse) -> Result<Data?, SwishError> {
    switch httpResponse.code {
    case (200...299):
      return .success(httpResponse.data)
    default:
      return .failure(.serverError(code: httpResponse.code, data: httpResponse.data))
    }
  }
}

Use Result.flatMap instead of >>-

import Foundation
import Argo
import Result

public struct APIClient {
  fileprivate let requestPerformer: RequestPerformer
  fileprivate let deserializer: Deserializer
  fileprivate let scheduler: Scheduler

  public init(requestPerformer: RequestPerformer = NetworkRequestPerformer(), deserializer: Deserializer = JSONDeserializer(), scheduler: @escaping Scheduler = mainQueueScheduler) {
    self.requestPerformer = requestPerformer
    self.deserializer = deserializer
    self.scheduler = scheduler
  }
}

extension APIClient: Client {
  @discardableResult
  public func perform<T: Request>(_ request: T, completionHandler: @escaping (Result<T.ResponseObject, SwishError>) -> Void) -> URLSessionDataTask {
    return requestPerformer.perform(request.build()) { [schedule = scheduler] result in
      let object = result
        .flatMap(self.validate)
        .flatMap(self.deserializer.deserialize)
        .flatMap(T.ResponseParser.parse)
        .flatMap(request.parse)

      schedule { completionHandler(object) }
    }
  }
}

private extension APIClient {
  func validate(_ httpResponse: HTTPResponse) -> Result<Data?, SwishError> {
    switch httpResponse.code {
    case (200...299):
      return .success(httpResponse.data)
    default:
      return .failure(.serverError(code: httpResponse.code, data: httpResponse.data))
    }
  }
}


//
//  XMLFeedTransformable.swift
//  SimpleRSSReader
//
//  Created by Kyosuke Takayama on 2016/03/07.
//  Copyright © 2016年 aill inc. All rights reserved.
//

import Foundation

protocol XMLFeedTransformable {
    typealias TransformType = Self

    static func mapping(feedInfo: XMLFeedInfo, feedItems: [ XMLFeedItem ]) -> TransformType
}

Fix warning: `use of 'typealias' to declare associated types is deprecated; use 'associatedtype' instead`

//
//  XMLFeedTransformable.swift
//  SimpleRSSReader
//
//  Created by Kyosuke Takayama on 2016/03/07.
//  Copyright © 2016年 aill inc. All rights reserved.
//

import Foundation

protocol XMLFeedTransformable {
    associatedtype TransformType = Self

    static func mapping(feedInfo: XMLFeedInfo, feedItems: [ XMLFeedItem ]) -> TransformType
}


#if SQLITE_SWIFT_SQLCIPHER
import SQLCipher

extension Connection {
    public func key(_ key: String) throws {
        try check(sqlite3_key(handle, key, Int32(key.utf8.count)))
        try execute(
            "CREATE TABLE \"__SQLCipher.swift__\" (\"cipher key check\");\n" +
            "DROP TABLE \"__SQLCipher.swift__\";"
        )
    }

    public func rekey(_ key: String) throws {
        try check(sqlite3_rekey(handle, key, Int32(key.utf8.count)))
    }

    public func key(_ key: Blob) throws {
        try check(sqlite3_key(handle, key.bytes, Int32(key.bytes.count)))
        try execute(
            "CREATE TABLE \"__SQLCipher.swift__\" (\"cipher key check\");\n" +
            "DROP TABLE \"__SQLCipher.swift__\";"
        )
    }

    public func rekey(_ key: Blob) throws {
        try check(sqlite3_rekey(handle, key.bytes, Int32(key.bytes.count)))
    }
}
#endif

Remove some duplication in key/rekey

#if SQLITE_SWIFT_SQLCIPHER
import SQLCipher

extension Connection {
    public func key(_ key: String) throws {
        try _key(keyPointer: key, keySize: key.utf8.count)
    }

    public func key(_ key: Blob) throws {
        try _key(keyPointer: key.bytes, keySize: key.bytes.count)
    }

    public func rekey(_ key: String) throws {
        try _rekey(keyPointer: key, keySize: key.utf8.count)
    }

    public func rekey(_ key: Blob) throws {
        try _rekey(keyPointer: key.bytes, keySize: key.bytes.count)
    }

    // MARK: - private
    private func _key(keyPointer: UnsafePointer<UInt8>, keySize: Int) throws {
        try check(sqlite3_key(handle, keyPointer, Int32(keySize)))
        try execute(
            "CREATE TABLE \"__SQLCipher.swift__\" (\"cipher key check\");\n" +
            "DROP TABLE \"__SQLCipher.swift__\";"
        )
    }

    private func _rekey(keyPointer: UnsafePointer<UInt8>, keySize: Int) throws {
        try check(sqlite3_rekey(handle, keyPointer, Int32(keySize)))
    }
}
#endif


import Foundation
import Surge
import XCPlayground

// MARK: - Arithmetic

let n = [-1.0, 2.0, 3.0, 4.0, 5.0]
let sum = Surge.sum(n)

let a = [1.0, 3.0, 5.0, 7.0]
let b = [2.0, 4.0, 6.0, 8.0]
let product = Surge.mul(a, b)

// MARK: - Matrix

// ⎛ 1  1 ⎞       ⎛ 3 ⎞
// ⎢      ⎟ * B = ⎢   ⎟         C = ?
// ⎝ 1 -1 ⎠       ⎝ 1 ⎠

let A = Matrix([[1, 1], [1, -1]])
let C = Matrix([[3], [1]])
let B = inv(A) * C

// MARK: - FFT

func plot<T>(values: [T], title: String) {
    for value in values {
        XCPCaptureValue(title, value)
    }
}

let count = 64
let frequency = 4.0
let amplitude = 3.0

let x = map(0..<count){ 2.0 * M_PI / Double(count) * Double($0) * frequency }

plot(sin(x), "Sine Wave")
plot(fft(sin(x)), "FFT")

Fix for Xcode 7.2 and Swift 2.1.1

import Foundation
import Surge
import XCPlayground

// MARK: - Arithmetic

let n = [-1.0, 2.0, 3.0, 4.0, 5.0]
let sum = Surge.sum(n)

let a = [1.0, 3.0, 5.0, 7.0]
let b = [2.0, 4.0, 6.0, 8.0]
let product = Surge.mul(a, y: b)

// MARK: - Matrix

// ⎛ 1  1 ⎞       ⎛ 3 ⎞
// ⎢      ⎟ * B = ⎢   ⎟         C = ?
// ⎝ 1 -1 ⎠       ⎝ 1 ⎠

let A = Matrix([[1, 1], [1, -1]])
let C = Matrix([[3], [1]])
let B = inv(A) * C

// MARK: - FFT

func plot<T>(values: [T], title: String) {
    for value in values {
        XCPlaygroundPage.currentPage.captureValue(value, withIdentifier: title)
    }
}

let count = 64
let frequency = 4.0
let amplitude = 3.0

let x = (0..<count).map{ 2.0 * M_PI / Double(count) * Double($0) * frequency }

plot(sin(x), title:"Sine Wave")
plot(fft(sin(x)), title:"FFT")


//
//  TestRoute.swift
//  SweetRouter
//
//  Created by Oleksii on 17/03/2017.
//  Copyright © 2017 ViolentOctopus. All rights reserved.
//

import XCTest
import SweetRouter

class TestRoute: XCTestCase {

    func testUrlRouteEquatable() {
        XCTAssertEqual(URL.Route(path: ["myPath"], query: ("user", nil), ("date", "12.04.02")), URL.Route(path: ["myPath"], query: ("user", "some"), ("date", "12.04.02")))
        XCTAssertNotEqual(URL.Route(path: ["myPath"]), URL.Route(path: ["myPath"], query: ("user", nil)))
    }

}

Make sure Route tests succeed

//
//  TestRoute.swift
//  SweetRouter
//
//  Created by Oleksii on 17/03/2017.
//  Copyright © 2017 ViolentOctopus. All rights reserved.
//

import XCTest
import SweetRouter

class TestRoute: XCTestCase {

    func testUrlRouteEquatable() {
        XCTAssertEqual(URL.Route(path: ["myPath"], query: ("user", nil), ("date", "12.04.02")), URL.Route(path: ["myPath"], query: ("user", nil), ("date", "12.04.02")))
        XCTAssertNotEqual(URL.Route(path: ["myPath"]), URL.Route(path: ["myPath"], query: ("user", nil)))
    }

}


//
// NSRunLoop+Utils.swift
//
// This source file is part of the Telegram Bot SDK for Swift (unofficial).
//
// Copyright (c) 2015 - 2016 Andrey Fidrya and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See AUTHORS.txt for the list of the project authors
//

import Foundation
import Dispatch

public extension RunLoop {
	public func waitForSemaphore(_ sem: DispatchSemaphore) {
        #if os(Linux)
		while true {
            // Bug workaround:
            // RunLoop.run() on Linux waits in a busy loop producing high CPU usage. Also, it freezes if
            // time interval is too small or negative. So, pick a minimal time interval when it still
            // doesn't freeze and add usleep(). This will minimize CPU usage when idling.
            let _ = run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.002))
		    if .success == sem.wait(timeout: DispatchTime.now()) {
                break
            }
            usleep(100000)
        }
        #else
		repeat {
            run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.01))
		} while .success != sem.wait(timeout: DispatchTime.now())
        #endif
	}
}

Remove Linux high CPU usage workaround (fixed in Swift 4)

//
// NSRunLoop+Utils.swift
//
// This source file is part of the Telegram Bot SDK for Swift (unofficial).
//
// Copyright (c) 2015 - 2016 Andrey Fidrya and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See AUTHORS.txt for the list of the project authors
//

import Foundation
import Dispatch

public extension RunLoop {
	public func waitForSemaphore(_ sem: DispatchSemaphore) {
		repeat {
            run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.01))
		} while .success != sem.wait(timeout: DispatchTime.now())
	}
}


//
//  CasperSplashWebView.swift
//  SplashBuddy
//
//  Created by ftiff on 04/08/16.
//  Copyright © 2016 François Levaux-Tiffreau. All rights reserved.
//

import Cocoa
import WebKit

class MainWebView: WebView {

    override func viewWillDraw() {
        self.layer?.borderWidth = 1.0
        self.layer?.borderWidth = 1.0
        self.layer?.borderColor = NSColor.lightGray.cgColor
        self.layer?.isOpaque = true

        // An attempt at returning a localized version, if exists.
        // presentation.html -> presentation_fr.html

        let full_url = URL(fileURLWithPath: Preferences.sharedInstance.htmlAbsolutePath)
        let extension_path = full_url.pathExtension
        let base_path = full_url.deletingPathExtension().path
        let languageCode = NSLocale.current.languageCode ?? "en"

        let localized_path = "\(base_path)_\(languageCode).\(extension_path)"

        if FileManager().fileExists(atPath: localized_path) {
            self.mainFrame.load(URLRequest(url: URL(fileURLWithPath: localized_path)))
        } else {
            self.mainFrame.load(URLRequest(url: URL(fileURLWithPath: Preferences.sharedInstance.htmlAbsolutePath)))
        }
    }
}

Set the webkit class to match IB.

//
//  CasperSplashWebView.swift
//  SplashBuddy
//
//  Created by ftiff on 04/08/16.
//  Copyright © 2016 François Levaux-Tiffreau. All rights reserved.
//

import Cocoa
import WebKit

class MainWebView: WebView {

    override func viewWillDraw() {
        self.layer?.borderWidth = 1.0
        self.layer?.borderWidth = 1.0
        self.layer?.borderColor = NSColor.lightGray.cgColor
        self.layer?.isOpaque = true

        //  Sets preferences to match IB
        //  NOTE: Possible issue with the IBOutlet connection
        self.preferences.isJavaEnabled = false
        self.preferences.isJavaScriptEnabled = false
        self.preferences.javaScriptCanOpenWindowsAutomatically = false
        self.preferences.loadsImagesAutomatically = true
        self.preferences.allowsAnimatedImages = false
        self.preferences.allowsAnimatedImageLooping = false

        // An attempt at returning a localized version, if exists.
        // presentation.html -> presentation_fr.html

        let full_url = URL(fileURLWithPath: Preferences.sharedInstance.htmlAbsolutePath)
        let extension_path = full_url.pathExtension
        let base_path = full_url.deletingPathExtension().path
        let languageCode = NSLocale.current.languageCode ?? "en"

        let localized_path = "\(base_path)_\(languageCode).\(extension_path)"

        if FileManager().fileExists(atPath: localized_path) {
            self.mainFrame.load(URLRequest(url: URL(fileURLWithPath: localized_path)))
        } else {
            self.mainFrame.load(URLRequest(url: URL(fileURLWithPath: Preferences.sharedInstance.htmlAbsolutePath)))
        }
    }
}


import UIKit
import AvitoDesignKit

class PhotoCollectionViewCell: UICollectionViewCell {

    var image: ImageSource? {
        didSet {
            updateImage()
        }
    }

    var selectedBorderColor: UIColor? = .blueColor() {
        didSet {
            adjustBorderColor()
        }
    }

    class var imageViewContentMode: UIViewContentMode {
        return .ScaleAspectFill
    }

    private let imageView = UIImageView()

    override init(frame: CGRect) {
        super.init(frame: frame)

        adjustBorderColor()

        imageView.contentMode = self.dynamicType.imageViewContentMode
        imageView.clipsToBounds = true

        contentView.addSubview(imageView)
    }

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

    override func layoutSubviews() {
        super.layoutSubviews()

        imageView.frame = contentView.bounds

        updateImage()
    }

    override var selected: Bool {
        didSet {
            layer.borderWidth = selected ? 4 : 0
        }
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        image = nil
        imageView.image = nil
    }

    // MARK: - Private

    private func updateImage() {

        let requestedImage = image

        requestedImage?.imageFittingSize(imageView.bounds.size) { [weak self] (uiImage: UIImage?) in
            if self?.image === requestedImage {
                self?.imageView.image = uiImage
//                debugPrint("set cell image")
            } else {
//                debugPrint("image setting cancelled (expected \(unsafeAddressOf(requestedImage!)), actual \(unsafeAddressOf(self!.image!)))")
            }
        }
    }

    private func adjustBorderColor() {
        layer.borderColor = selectedBorderColor?.CGColor
    }
}

Fix pixelization issue caused by previous commit

import UIKit
import AvitoDesignKit

class PhotoCollectionViewCell: UICollectionViewCell {

    var image: ImageSource? {
        didSet {
            updateImage()
        }
    }

    var selectedBorderColor: UIColor? = .blueColor() {
        didSet {
            adjustBorderColor()
        }
    }

    class var imageViewContentMode: UIViewContentMode {
        return .ScaleAspectFill
    }

    private let imageView = UIImageView()

    override init(frame: CGRect) {
        super.init(frame: frame)

        adjustBorderColor()

        imageView.contentMode = self.dynamicType.imageViewContentMode
        imageView.clipsToBounds = true

        contentView.addSubview(imageView)
    }

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

    override func layoutSubviews() {
        super.layoutSubviews()

        imageView.frame = contentView.bounds

        updateImage()
    }

    override var selected: Bool {
        didSet {
            layer.borderWidth = selected ? 4 : 0
        }
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        image = nil
        imageView.image = nil
    }

    // MARK: - Private

    private func updateImage() {
        imageView.setImage(image) { [weak self, requestedImage = image, previousImage = imageView.image] in
            if self?.image !== requestedImage {
                self?.imageView.image = previousImage
            }
        }
    }

    private func adjustBorderColor() {
        layer.borderColor = selectedBorderColor?.CGColor
    }
}


import Foundation

extension MSettings
{
    //MARK: private

    private class func factoryItemTypes() -> [MSettingsProtocol.Type]
    {
        let types:[MSettingsProtocol.Type] = [
            MSettingsTravelMode.self,
            MSettingsDetailLevel.self,
            MSettingsDistance.self,
            MSettingsStorage.self]

        return types
    }

    //MARK: internal

    class func factoryItems(
        settings:DSettings,
        database:Database) -> [MSettingsProtocol]
    {
        let itemTypes:[MSettingsProtocol.Type] = factoryItemTypes()
        var items:[MSettingsProtocol] = []

        for itemType:MSettingsProtocol.Type in itemTypes
        {
            let item:MSettingsProtocol = itemType.init(
                settings:settings,
                database:database)

            items.append(item)
        }

        return items
    }
}

Reorder factory, set memory first

import Foundation

extension MSettings
{
    //MARK: private

    private class func factoryItemTypes() -> [MSettingsProtocol.Type]
    {
        let types:[MSettingsProtocol.Type] = [
            MSettingsStorage.self,
            MSettingsTravelMode.self,
            MSettingsDetailLevel.self,
            MSettingsDistance.self]

        return types
    }

    //MARK: internal

    class func factoryItems(
        settings:DSettings,
        database:Database) -> [MSettingsProtocol]
    {
        let itemTypes:[MSettingsProtocol.Type] = factoryItemTypes()
        var items:[MSettingsProtocol] = []

        for itemType:MSettingsProtocol.Type in itemTypes
        {
            let item:MSettingsProtocol = itemType.init(
                settings:settings,
                database:database)

            items.append(item)
        }

        return items
    }
}


import XCTest
#if GRDBCIPHER
    @testable import GRDBCipher
#elseif GRDBCUSTOMSQLITE
    @testable import GRDBCustomSQLite
#else
    @testable import GRDB
#endif

class DatabaseLogErrorTests: GRDBTestCase {

    func testErrorLog() throws {
        let dbQueue = try makeDatabaseQueue()
        dbQueue.inDatabase { db in
            _ = try? db.execute("That's not SQL.")
        }
        XCTAssertEqual(lastResultCode!, ResultCode.SQLITE_ERROR)
        XCTAssertEqual(lastMessage!, "near \"That\": syntax error")
    }
}

Fix a test for syntax error that fails with SQLite 3.25.2

import XCTest
#if GRDBCIPHER
    @testable import GRDBCipher
#elseif GRDBCUSTOMSQLITE
    @testable import GRDBCustomSQLite
#else
    @testable import GRDB
#endif

class DatabaseLogErrorTests: GRDBTestCase {

    func testErrorLog() throws {
        let dbQueue = try makeDatabaseQueue()
        dbQueue.inDatabase { db in
            _ = try? db.execute("Abracadabra")
        }
        XCTAssertEqual(lastResultCode!, ResultCode.SQLITE_ERROR)
        // Don't check for exact error message because it depends on SQLite version
        XCTAssert(lastMessage!.contains("syntax error"))
        XCTAssert(lastMessage!.contains("Abracadabra"))
    }
}


// Sources/SwiftProtobuf/Google_Protobuf_NullValue+Extensions.swift - NullValue extensions
//
// Copyright (c) 2014 - 2020 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// NullValue is a well-known message type that can be used to parse or encode
/// JSON Null values.
///
// -----------------------------------------------------------------------------

extension Google_Protobuf_NullValue: _CustomJSONCodable {
  internal func encodedJSONString(options: JSONEncodingOptions) throws -> String {
    return "null"
  }
  internal mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
    if decoder.scanner.skipOptionalNull() {
      return
    }
  }
  static func decodedFromJSONNull() -> Google_Protobuf_NullValue? {
    print("Decoding Google_Protobuf_NullValue from null")
    return .nullValue
  }
}

Remove a debug print statement

// Sources/SwiftProtobuf/Google_Protobuf_NullValue+Extensions.swift - NullValue extensions
//
// Copyright (c) 2014 - 2020 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// NullValue is a well-known message type that can be used to parse or encode
/// JSON Null values.
///
// -----------------------------------------------------------------------------

extension Google_Protobuf_NullValue: _CustomJSONCodable {
  internal func encodedJSONString(options: JSONEncodingOptions) throws -> String {
    return "null"
  }
  internal mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
    if decoder.scanner.skipOptionalNull() {
      return
    }
  }
  static func decodedFromJSONNull() -> Google_Protobuf_NullValue? {
    return .nullValue
  }
}


//
//  __DoNotUse.swift
//  Cuckoo
//
//  Created by Tadeas Kriz on 13/01/16.
//  Copyright © 2016 Brightify. All rights reserved.
//

/// Marker struct for use as a return type in verification.
public struct __DoNotUse<IN, OUT> { }

Allow verify to specify return type for generic functions

//
//  __DoNotUse.swift
//  Cuckoo
//
//  Created by Tadeas Kriz on 13/01/16.
//  Copyright © 2016 Brightify. All rights reserved.
//

/// Marker struct for use as a return type in verification.
public struct __DoNotUse<IN, OUT> { }

public extension __DoNotUse {

    /// Hint at the return type when verifying a function where the function is generic
    /// and the type is inferred from the return value
    func with(returnType: OUT.Type) { }
}


// Copyright 2015 Tony Allevato
//
// 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 SwiftCGI

print("Hello, world!")

Update the demo to start the server and respond with "Hello, world!"

// Copyright 2015 Tony Allevato
//
// 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 SwiftCGI

let server = Server()
server.listen { request, response in
  do {
    try response.contentStream.write("Hello, world!\n")
  } catch {
    fatalError("Failed to write output to the response stream.")
  }
}


//
//  BPETrackUsersViewController.swift
//  BPApp
//
//  Created by Chris Blackstone on 4/24/17.
//  Copyright © 2017 BlackstoneBuilds. All rights reserved.
//

import UIKit

class BPETrackUsersViewControler: UITableViewController {

    @IBAction func back() {
        dismiss(animated: true, completion: nil)
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Users", for: indexPath)
        let titleLabel = cell.viewWithTag(10) as! UILabel
        titleLabel.text = "Chris Blackstone"
        return cell
    }

}

Fix patients view controller to actually display patients in the list.

//
//  BPETrackUsersViewController.swift
//  BPApp
//
//  Created by Chris Blackstone on 4/24/17.
//  Copyright © 2017 BlackstoneBuilds. All rights reserved.
//

import UIKit

class BPETrackUsersViewControler: UITableViewController {

    @IBAction func back() {
        dismiss(animated: true, completion: nil)
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Config.patients.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Users", for: indexPath)
        let titleLabel = cell.viewWithTag(10) as! UILabel
        titleLabel.text = "\(Config.patients[indexPath.row].lastName), \(Config.patients[indexPath.row].firstName)"
        return cell
    }

}


import Foundation

public protocol CSSAttributeMatcher {
    func check(_ cssAttribute: CSSAttribute) -> Bool
}

Add an empty CSS Attribute matcher.

import Foundation

public protocol CSSAttributeMatcher {
    func check(_ cssAttribute: CSSAttribute) -> Bool
}

open class NeverCSSAttributeMatcher: CSSAttributeMatcher {
    public func check(_ cssAttribute: CSSAttribute) -> Bool {
        return false
    }
}


//
//  TeleprompterTextView.swift
//  Dictater
//
//  Created by Kyle Carson on 9/15/15.
//  Copyright © 2015 Kyle Carson. All rights reserved.
//

import Foundation
import Cocoa

class TeleprompterTextView : NSTextView
{
	static let skipChars = [ " " ]
	override func keyDown(theEvent: NSEvent) {
		for char in TeleprompterTextView.skipChars
		{
			if char == theEvent.characters
			{
				return
			}
		}
		super.keyDown(theEvent)
	}

	var scrollDate : NSDate?

	override func scrollWheel(theEvent: NSEvent)
	{
		super.scrollWheel(theEvent)
		self.scrollDate = NSDate()
	}
}

Fix play/pause button via space in the text window

//
//  TeleprompterTextView.swift
//  Dictater
//
//  Created by Kyle Carson on 9/15/15.
//  Copyright © 2015 Kyle Carson. All rights reserved.
//

import Foundation
import Cocoa

class TeleprompterTextView : NSTextView
{
	static let skipChars = [ " " ]
	override func keyDown(theEvent: NSEvent) {
		for char in TeleprompterTextView.skipChars
		{
			if char == theEvent.characters
			{
				self.nextKeyView?.keyDown(theEvent)
				return
			}
		}
		super.keyDown(theEvent)
	}

	var scrollDate : NSDate?

	override func scrollWheel(theEvent: NSEvent)
	{
		super.scrollWheel(theEvent)
		self.scrollDate = NSDate()
	}
}


// UNSUPPORTED: OS=windows-msvc
// static library is not well supported yet on Windows

// REQUIRES: lld_lto
// REQUIRES: rdar75301449

// RUN: %empty-directory(%t)
// RUN: %target-swiftc_driver -emit-library -static -lto=llvm-full -emit-module %S/Inputs/lto/module1.swift -working-directory %t
// RUN: %target-swiftc_driver -lto=llvm-full %s -I%t -L%t -lmodule1 -module-name main -o %t/main
// RUN: %llvm-nm --defined-only %t/main | %FileCheck %s

// CHECK-NOT: _$s7module120unusedPublicFunctionyyF

import module1

Revert "Disable test that's failing in CI"

// UNSUPPORTED: OS=windows-msvc
// static library is not well supported yet on Windows

// REQUIRES: lld_lto

// RUN: %empty-directory(%t)
// RUN: %target-swiftc_driver -emit-library -static -lto=llvm-full -emit-module %S/Inputs/lto/module1.swift -working-directory %t
// RUN: %target-swiftc_driver -lto=llvm-full %s -I%t -L%t -lmodule1 -module-name main -o %t/main
// RUN: %llvm-nm --defined-only %t/main | %FileCheck %s

// CHECK-NOT: _$s7module120unusedPublicFunctionyyF

import module1


//
//  TGCardController+ShowError.swift
//  TripGoAppKit
//
//  Created by Adrian Schönig on 05.11.19.
//  Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//

import UIKit

import TGCardViewController

extension UIViewController {
  public func showErrorAsAlert(_ error: Error) {
    let alertController = UIAlertController(title: Loc.Error, message: error.localizedDescription, preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: Loc.OK, style: .cancel, handler: nil))
    present(alertController, animated: true)
  }
}

extension TGCardViewController {
  public func show(_ error: Error) {
    self.showErrorAsAlert(error)
  }
}

Allow setting title on errors

//
//  TGCardController+ShowError.swift
//  TripGoAppKit
//
//  Created by Adrian Schönig on 05.11.19.
//  Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//

import UIKit

import TGCardViewController

extension UIViewController {
  public func showErrorAsAlert(_ error: Error, title: String? = nil) {
    let alertController = UIAlertController(title: title ?? Loc.Error, message: error.localizedDescription, preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: Loc.OK, style: .cancel, handler: nil))
    present(alertController, animated: true)
  }
}

extension TGCardViewController {
  public func show(_ error: Error, title: String? = nil) {
    self.showErrorAsAlert(error, title: title)
  }
}


// Copyright (c) 2018 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information

import Foundation

/**
 Represents an error, which happened during processing 7-Zip container.
 It may indicate that either container is damaged or it might not be 7-Zip container at all.
 */
public enum SevenZipError: Error {
    /// Wrong container's signature.
    case wrongSignature
    /// Unsupported version of container's format.
    case wrongFormatVersion
    /**
     CRC either of one of the files from the container
     or one of the container's strucutures is incorrect.
     */
    case wrongCRC
    /**
     Size either of one of the files from the container
     or one of the container's strucutures is incorrect.
     */
    case wrongSize
    /// Files have StartPos property. This feature isn't supported.
    case startPosNotSupported
    /// External feature isn't supported.
    case externalNotSupported
    /// Coders with multiple in and/or out streams aren't supported.
    case multiStreamNotSupported
    /// Additional streams feature isn't supported.
    case additionalStreamsNotSupported
    /// Entry is compressed using unsupported compression method.
    case compressionNotSupported
    /// Entry or container's header is encrypted. This feature isn't supported.
    case encryptionNotSupported
    /**
     Unknown/incorrect internal 7-Zip structure was encountered or
     no internal structure was found where it must be.
     */
    case internalStructureError
}

Simplify documentation for SevenZipError cases

// Copyright (c) 2018 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information

import Foundation

/**
 Represents an error, which happened during processing 7-Zip container.
 It may indicate that either container is damaged or it might not be 7-Zip container at all.
 */
public enum SevenZipError: Error {
    /// Wrong container's signature.
    case wrongSignature
    /// Unsupported version of container's format.
    case wrongFormatVersion
    /// CRC either of one of the files from the container or one of the container's strucutures is incorrect.
    case wrongCRC
    /// Size either of one of the files from the container or one of the container's strucutures is incorrect.
    case wrongSize
    /// Files have StartPos property. This feature isn't supported.
    case startPosNotSupported
    /// External feature isn't supported.
    case externalNotSupported
    /// Coders with multiple in and/or out streams aren't supported.
    case multiStreamNotSupported
    /// Additional streams feature isn't supported.
    case additionalStreamsNotSupported
    /// Entry is compressed using unsupported compression method.
    case compressionNotSupported
    /// Entry or container's header is encrypted. This feature isn't supported.
    case encryptionNotSupported
    /// Unknown/incorrect internal 7-Zip structure was encountered or a required internal structure is missing.
    case internalStructureError
}


//
//  materialized+elements.swift
//  RxSwiftExt
//
//  Created by Andy Chou on 1/5/17.
//  Copyright © 2017 RxSwift Community. All rights reserved.
//

import Foundation
import RxSwift

extension ObservableType where Element: EventConvertible {

	/**
	 Returns an observable sequence containing only next elements from its input
	 - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html)
	 */
	public func elements() -> Observable<Element.Element> {
		return filter { $0.event.element != nil }
				.map { $0.event.element! }
	}

	/**
	 Returns an observable sequence containing only error elements from its input
	 - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html)
	 */
	public func errors() -> Observable<Swift.Error> {
		return filter { $0.event.error != nil }
				.map { $0.event.error! }
	}
}

Refactor elements & errors implementation

//
//  materialized+elements.swift
//  RxSwiftExt
//
//  Created by Andy Chou on 1/5/17.
//  Copyright © 2017 RxSwift Community. All rights reserved.
//

import Foundation
import RxSwift

extension ObservableType where Element: EventConvertible {

	/**
	 Returns an observable sequence containing only next elements from its input
	 - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html)
	 */
	public func elements() -> Observable<Element.Element> {
		return compactMap { $0.event.element }
	}

	/**
	 Returns an observable sequence containing only error elements from its input
	 - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html)
	 */
	public func errors() -> Observable<Swift.Error> {
		return compactMap { $0.event.error }
	}
}


//
//  UIViewController+Extensions.swift
//  Utilities
//
//  Created by Caio Mello on 8/21/19.
//  Copyright © 2019 Caio Mello. All rights reserved.
//

import UIKit

extension UIViewController {
    public class func instantiate<T: UIViewController>(_ viewController: @escaping (NSCoder) -> T?) -> T {
        let storyboard = UIStoryboard(name: "\(T.self)", bundle: nil)

        return storyboard.instantiateInitialViewController(creator: viewController)!
    }

    public func show<T: UIViewController>(_ viewController: @escaping (NSCoder) -> T?) {
        let viewController = T.instantiate(viewController)
        show(viewController, sender: nil)
    }

    public func showDetail<T: UIViewController>(_ viewController: @escaping (NSCoder) -> T?) {
        let viewController = T.instantiate(viewController)

        let navigationController = UINavigationController(rootViewController: viewController)
        navigationController.navigationBar.barStyle = .black

        showDetailViewController(navigationController, sender: nil)
    }

    public func present<T: UIViewController>(_ viewController: @escaping (NSCoder) -> T?) {
        let viewController = T.instantiate(viewController)

        let navigationController = UINavigationController(rootViewController: viewController)
        navigationController.navigationBar.barStyle = .black

        present(navigationController, animated: true)
    }
}

Change modal presentation to form sheet

//
//  UIViewController+Extensions.swift
//  Utilities
//
//  Created by Caio Mello on 8/21/19.
//  Copyright © 2019 Caio Mello. All rights reserved.
//

import UIKit

extension UIViewController {
    public class func instantiate<T: UIViewController>(_ viewController: @escaping (NSCoder) -> T?) -> T {
        let storyboard = UIStoryboard(name: "\(T.self)", bundle: nil)

        return storyboard.instantiateInitialViewController(creator: viewController)!
    }

    public func show<T: UIViewController>(_ viewController: @escaping (NSCoder) -> T?) {
        let viewController = T.instantiate(viewController)
        show(viewController, sender: nil)
    }

    public func showDetail<T: UIViewController>(_ viewController: @escaping (NSCoder) -> T?) {
        let viewController = T.instantiate(viewController)

        let navigationController = UINavigationController(rootViewController: viewController)
        navigationController.navigationBar.barStyle = .black

        showDetailViewController(navigationController, sender: nil)
    }

    public func present<T: UIViewController>(_ viewController: @escaping (NSCoder) -> T?) {
        let viewController = T.instantiate(viewController)

        let navigationController = UINavigationController(rootViewController: viewController)
        navigationController.navigationBar.barStyle = .black
        navigationController.modalPresentationStyle = .formSheet

        present(navigationController, animated: true)
    }
}


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

extension Int {
	public func digits(base: Int) -> [Int] {
		return Repeat(count: self <= 0 ? 0 : Int(log(Double(self)) / log(Double(base))), repeatedValue: 0)
			.reduce(([self % base], self)) { into, _ -> ([Int], Int) in ([ (into.1 / base) % base ] + into.0, into.1 / base) }.0
	}
}

import Darwin

Move the negative handling outside of the Repeat.

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

extension Int {
	public func digits(base: Int) -> [Int] {
		return self <= 0 ? [self % base] : Repeat(count: Int(log(Double(self)) / log(Double(base))), repeatedValue: 0)
			.reduce(([self % base], self)) { into, _ -> ([Int], Int) in ([ (into.1 / base) % base ] + into.0, into.1 / base) }.0
	}
}

import Darwin


/**
    If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
    multiples is 23.

    Find the sum of all the multiples of 3 or 5 below 1000.
*/

let MAX = 1000                              // Upperbound
let factors:Array<Int> = [3,5]              // Factors to check for multiples

/*
    Iterates through the given Natural numbers collection.
    If an element of the Natural numbers collections is a multiple
    of the given factors, add it to the current sum.
*/

func findSum() {
    var sumOfMultiples:Int = 0              // Initialize and set sum to 0

    for i in factors.minElement()!..<MAX {  // Iterate from lowerbound to upperbound.
        for j in factors {                  // Iterate over given factors.
            if i % j == 0 {                 // If current factor is a multiple of current element of the collection N,
                sumOfMultiples += i         // add the current element to the current sum.
                break
            }
        }
    }

    print(sumOfMultiples)                   // Return summated result of found factor multiples.
}

Correct comment on, is multiple condition checking

/**
    If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
    multiples is 23.

    Find the sum of all the multiples of 3 or 5 below 1000.
*/

let MAX = 1000                              // Upperbound
let factors:Array<Int> = [3,5]              // Factors to check for multiples

/*
    Iterates through the given Natural numbers collection.
    If an element of the Natural numbers collections is a multiple
    of the given factors, add it to the current sum.
*/

func findSum() {
    var sumOfMultiples:Int = 0              // Initialize and set sum to 0

    for i in factors.minElement()!..<MAX {  // Iterate from lowerbound to upperbound.
        for j in factors {                  // Iterate over given factors.
            if i % j == 0 {                 // If current element of the collection N is a multiple of current factor element,
                sumOfMultiples += i         // add the current element to the current sum.
                break
            }
        }
    }

    print(sumOfMultiples)                   // Return summated result of found factor multiples.
}


func demo() {
    var x: Int
    if (x == 2) {
        return (x < 2)
    }
    else if (y == 2) {

    }

    while(true) {

    }
}

Add test for guard statement

func demo() {
    var x: Int
    if (x == 2) {
        return (x < 2)
    }
    else if (y == 2) {

    }

    while(true) {

    }

    guard (true) else { }
}


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

import SwiftSyntax

extension VariableDecl {
  public init(
    _ letOrVarKeyword: TokenSyntax,
    name: ExpressibleAsIdentifierPattern,
    type: ExpressibleAsTypeAnnotation? = nil,
    initializer: ExpressibleAsInitializerClause? = nil
  ) {
    self.init(letOrVarKeyword: letOrVarKeyword) {
      PatternBinding(
        pattern: name,
        typeAnnotation: type,
        initializer: initializer
      )
    }
  }
}

Add leadingTrivia parameter to VariableDecl initializer

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

import SwiftSyntax

extension VariableDecl {
  public init(
    leadingTrivia: Trivia = [],
    _ letOrVarKeyword: TokenSyntax,
    name: ExpressibleAsIdentifierPattern,
    type: ExpressibleAsTypeAnnotation? = nil,
    initializer: ExpressibleAsInitializerClause? = nil
  ) {
    self.init(leadingTrivia: leadingTrivia, letOrVarKeyword: letOrVarKeyword) {
      PatternBinding(
        pattern: name,
        typeAnnotation: type,
        initializer: initializer
      )
    }
  }
}


//
//  DateFormatterExtensions.swift
//  Pods
//
//  Created by Phillipe Casorla Sagot on 3/7/17.
//
//

import Foundation

extension DateFormatter {

    class internal func makespace() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        return dateFormatter
    }

    class internal func makespaceDateFormatterWithMicroSeconds() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
        return dateFormatter
    }

    class internal func makespaceHourMinute() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "h:mm a"
        return dateFormatter
    }

    class internal func makespaceYearMonthDay() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter
    }

    class internal func string(fromMSDate msDate: Date) -> String {
        return self.makespace().string(from: msDate)
    }

    class internal func date(fromMSString dateString: String) -> Date? {
        return self.makespace().date(from: dateString)
    }
}

Make date exstensions public again

//
//  DateFormatterExtensions.swift
//  Pods
//
//  Created by Phillipe Casorla Sagot on 3/7/17.
//
//

import Foundation

extension DateFormatter {

    class public func makespace() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        return dateFormatter
    }

    class public func makespaceDateFormatterWithMicroSeconds() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
        return dateFormatter
    }

    class public func makespaceHourMinute() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "h:mm a"
        return dateFormatter
    }

    class public func makespaceYearMonthDay() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter
    }

    class public func string(fromMSDate msDate: Date) -> String {
        return self.makespace().string(from: msDate)
    }

    class public func date(fromMSString dateString: String) -> Date? {
        return self.makespace().date(from: dateString)
    }
}


//
//  PreferenceTableView.swift
//  kawa
//
//  Created by noraesae on 27/07/2015.
//  Copyright (c) 2015 noraesae. All rights reserved.
//

import Cocoa

class PreferenceTableView: NSTableView, NSTableViewDataSource, NSTableViewDelegate {
    func numberOfRowsInTableView(tableView: NSTableView) -> Int {
        return InputSourceManager.inputSources.count
    }

    func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
        var cell: NSTableCellView?

        if tableColumn?.identifier == "Keyboard" {
            cell = tableView.makeViewWithIdentifier("KeyboardCellView", owner: self) as? NSTableCellView

            let inputSource = InputSourceManager.inputSources[row]
            cell!.textField?.stringValue = inputSource.name
            cell!.imageView?.image = inputSource.icon
        }

        return cell
    }
}

Add some test code to try changing the input method.

//
//  PreferenceTableView.swift
//  kawa
//
//  Created by noraesae on 27/07/2015.
//  Copyright (c) 2015 noraesae. All rights reserved.
//

import Cocoa

class PreferenceTableView: NSTableView, NSTableViewDataSource, NSTableViewDelegate {
    func numberOfRowsInTableView(tableView: NSTableView) -> Int {
        return InputSourceManager.inputSources.count
    }

    func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
        var cell: NSTableCellView?

        if tableColumn?.identifier == "Keyboard" {
            cell = tableView.makeViewWithIdentifier("KeyboardCellView", owner: self) as? NSTableCellView

            let inputSource = InputSourceManager.inputSources[row]
            cell!.textField?.stringValue = inputSource.name
            cell!.imageView?.image = inputSource.icon
        }

        return cell
    }

    func tableViewSelectionDidChange(notification: NSNotification) {
        // FIXME: test purpose
        let tableView = notification.object as! NSTableView
        InputSourceManager.inputSources[tableView.selectedRowIndexes.firstIndex].select()
    }
}


/**
 * Tae Won Ha - http://taewon.de - @hataewon
 * See LICENSE
 */

import Foundation

class PrefMiddleware: MiddlewareType {

  typealias StateType = AppState
  typealias ActionType = AnyAction

  static let compatibleVersion = "168"
  static let lastCompatibleVersion = "128"

  let mainWindow = MainWindowMiddleware()

  // The following should only be used when Cmd-Q'ing
  func applyPref(from appState: AppState) {
    defaults.setValue(appState.dict(), forKey: PrefMiddleware.compatibleVersion)
  }

  func typedApply(_ reduce: @escaping TypedActionReduceFunction) -> TypedActionReduceFunction {
    return { tuple in
      let result = reduce(tuple)

      guard tuple.modified else {
        return result
      }

      defaults.setValue(result.state.dict(), forKey: PrefMiddleware.compatibleVersion)

      return result
    }
  }

  class MainWindowMiddleware: MiddlewareType {

    typealias StateType = AppState
    typealias ActionType = UuidAction<MainWindow.Action>

    func typedApply(_ reduce: @escaping TypedActionReduceFunction) -> TypedActionReduceFunction {
      return { tuple in
        let result = reduce(tuple)

        guard tuple.modified else {
          return result
        }

        let uuidAction = tuple.action
        guard case .close = uuidAction.payload else {
          return result
        }

        defaults.setValue(result.state.dict(), forKey: PrefMiddleware.compatibleVersion)
        return result
      }
    }
  }
}

private let defaults = UserDefaults.standard

Use set(_, forKey:) instead of setValue(_, forKey:)

/**
 * Tae Won Ha - http://taewon.de - @hataewon
 * See LICENSE
 */

import Foundation

class PrefMiddleware: MiddlewareType {

  typealias StateType = AppState
  typealias ActionType = AnyAction

  static let compatibleVersion = "168"
  static let lastCompatibleVersion = "128"

  let mainWindow = MainWindowMiddleware()

  // The following should only be used when Cmd-Q'ing
  func applyPref(from appState: AppState) {
    defaults.set(appState.dict(), forKey: PrefMiddleware.compatibleVersion)
  }

  func typedApply(_ reduce: @escaping TypedActionReduceFunction) -> TypedActionReduceFunction {
    return { tuple in
      let result = reduce(tuple)

      guard tuple.modified else {
        return result
      }

      defaults.set(result.state.dict(), forKey: PrefMiddleware.compatibleVersion)

      return result
    }
  }

  class MainWindowMiddleware: MiddlewareType {

    typealias StateType = AppState
    typealias ActionType = UuidAction<MainWindow.Action>

    func typedApply(_ reduce: @escaping TypedActionReduceFunction) -> TypedActionReduceFunction {
      return { tuple in
        let result = reduce(tuple)

        guard tuple.modified else {
          return result
        }

        let uuidAction = tuple.action
        guard case .close = uuidAction.payload else {
          return result
        }

        defaults.set(result.state.dict(), forKey: PrefMiddleware.compatibleVersion)
        return result
      }
    }
  }
}

private let defaults = UserDefaults.standard


import Foundation

/// A Nimble matcher that succeeds when the actual value is the same instance
/// as the expected instance.
public func beIdenticalTo<T: AnyObject>(expected: T?) -> NonNilMatcherFunc<T> {
    return NonNilMatcherFunc { actualExpression, failureMessage in
        let actual = try actualExpression.evaluate()
        failureMessage.actualValue = "\(identityAsString(actual))"
        failureMessage.postfixMessage = "be identical to \(identityAsString(expected))"
        return actual === expected && actual !== nil
    }
}

public func ===<T: AnyObject>(lhs: Expectation<T>, rhs: T?) {
    lhs.to(beIdenticalTo(rhs))
}
public func !==<T: AnyObject>(lhs: Expectation<T>, rhs: T?) {
    lhs.toNot(beIdenticalTo(rhs))
}

/// Alias for "beIdenticalTo"
public func be<T: AnyObject>(expected: T?) -> NonNilMatcherFunc<T> {
    return beIdenticalTo(expected)
}

#if _runtime(_ObjC)
extension NMBObjCMatcher {
    public class func beIdenticalToMatcher(expected: NSObject?) -> NMBObjCMatcher {
        return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
            return try! beIdenticalTo(expected).matches(actualExpression, failureMessage: failureMessage)
        }
    }
}
#endif

Add same documentation to be() matcher

import Foundation

/// A Nimble matcher that succeeds when the actual value is the same instance
/// as the expected instance.
public func beIdenticalTo<T: AnyObject>(expected: T?) -> NonNilMatcherFunc<T> {
    return NonNilMatcherFunc { actualExpression, failureMessage in
        let actual = try actualExpression.evaluate()
        failureMessage.actualValue = "\(identityAsString(actual))"
        failureMessage.postfixMessage = "be identical to \(identityAsString(expected))"
        return actual === expected && actual !== nil
    }
}

public func ===<T: AnyObject>(lhs: Expectation<T>, rhs: T?) {
    lhs.to(beIdenticalTo(rhs))
}
public func !==<T: AnyObject>(lhs: Expectation<T>, rhs: T?) {
    lhs.toNot(beIdenticalTo(rhs))
}

/// A Nimble matcher that succeeds when the actual value is the same instance
/// as the expected instance.
///
/// Alias for "beIdenticalTo".
public func be<T: AnyObject>(expected: T?) -> NonNilMatcherFunc<T> {
    return beIdenticalTo(expected)
}

#if _runtime(_ObjC)
extension NMBObjCMatcher {
    public class func beIdenticalToMatcher(expected: NSObject?) -> NMBObjCMatcher {
        return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
            return try! beIdenticalTo(expected).matches(actualExpression, failureMessage: failureMessage)
        }
    }
}
#endif


import MapKit

extension Array { // seems you can no longer do extension [CLLocationCoordinate2D] ?
    func wmf_boundingRegion(with boundingMetersPerPoint: Double) -> MKCoordinateRegion {
        var rect: MKMapRect?
        for element in self {
            guard let coordinate = element as? CLLocationCoordinate2D else {
                continue
            }
            let point = MKMapPoint(coordinate)
            let mapPointsPerMeter = MKMapPointsPerMeterAtLatitude(coordinate.latitude)
            let dimension = mapPointsPerMeter * boundingMetersPerPoint
            let size = MKMapSize(width: dimension, height: dimension)
            let coordinateRect = MKMapRect(origin: MKMapPoint(x: point.x - 0.5*dimension, y: point.y - 0.5*dimension), size: size)
            guard let currentRect = rect else {
                rect = coordinateRect
                continue
            }
            rect = currentRect.union(coordinateRect)
        }

        guard let finalRect = rect else {
            return MKCoordinateRegion()
        }

        var region = MKCoordinateRegion(finalRect)
        if region.span.latitudeDelta < 0.01 {
            region.span.latitudeDelta = 0.01
        }
        if region.span.longitudeDelta < 0.01 {
            region.span.longitudeDelta = 0.01
        }
        return region
    }
}

Update array extension to be constrainted to non-class/protocol type CLLocationCoordinate2D

import MapKit

extension Array where Element == CLLocationCoordinate2D {
    func wmf_boundingRegion(with boundingMetersPerPoint: Double) -> MKCoordinateRegion {
        var rect: MKMapRect?
        for coordinate in self {
            let point = MKMapPoint(coordinate)
            let mapPointsPerMeter = MKMapPointsPerMeterAtLatitude(coordinate.latitude)
            let dimension = mapPointsPerMeter * boundingMetersPerPoint
            let size = MKMapSize(width: dimension, height: dimension)
            let coordinateRect = MKMapRect(origin: MKMapPoint(x: point.x - 0.5*dimension, y: point.y - 0.5*dimension), size: size)
            guard let currentRect = rect else {
                rect = coordinateRect
                continue
            }
            rect = currentRect.union(coordinateRect)
        }

        guard let finalRect = rect else {
            return MKCoordinateRegion()
        }

        var region = MKCoordinateRegion(finalRect)
        if region.span.latitudeDelta < 0.01 {
            region.span.latitudeDelta = 0.01
        }
        if region.span.longitudeDelta < 0.01 {
            region.span.longitudeDelta = 0.01
        }
        return region
    }
}


//
//  SafariExtensionHandler.swift
//  extension
//
//  Created by Simon on 2018-07-13.
//  Copyright © 2018 vimari. All rights reserved.
//

import SafariServices

class SafariExtensionHandler: SFSafariExtensionHandler {

    enum MessageType: String {
        case openLinkInTab
        case openNewTab
    }

    override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) {
        switch messageName {
        case MessageType.openLinkInTab.rawValue:
            let url = URL(string: userInfo?["url"] as! String)
            openInNewTab(url: url!)
            break
        case MessageType.openNewTab.rawValue:
            openNewTab()
            break
        default:
            NSLog("Received message with unsupported type: \(messageName)")
        }
    }

    func openInNewTab(url: URL) {
        SFSafariApplication.getActiveWindow { (activeWindow) in
            activeWindow?.openTab(with: url, makeActiveIfPossible: false, completionHandler: {_ in
                // Perform some action here after the page loads
            })
        }
    }

    func openNewTab() {
        // Ideally this URL would be something that represents an empty tab better than localhost
        let url = URL(string: "http://localhost")!
        SFSafariApplication.getActiveWindow { (activeWindow) in
            activeWindow?.openTab(with: url, makeActiveIfPossible: true, completionHandler: {_ in
                // Perform some action here after the page loads
            })
        }
    }

}

Move enum out of class

//
//  SafariExtensionHandler.swift
//  extension
//
//  Created by Simon on 2018-07-13.
//  Copyright © 2018 vimari. All rights reserved.
//

import SafariServices

enum ActionType: String {
    case openLinkInTab
    case openNewTab
}

class SafariExtensionHandler: SFSafariExtensionHandler {

    override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) {
        switch messageName {
        case ActionType.openLinkInTab.rawValue:
            let url = URL(string: userInfo?["url"] as! String)
            openInNewTab(url: url!)
            break
        case ActionType.openNewTab.rawValue:
            openNewTab()
            break
        default:
            NSLog("Received message with unsupported type: \(messageName)")
        }
    }

    func openInNewTab(url: URL) {
        SFSafariApplication.getActiveWindow { (activeWindow) in
            activeWindow?.openTab(with: url, makeActiveIfPossible: false, completionHandler: {_ in
                // Perform some action here after the page loads
            })
        }
    }

    func openNewTab() {
        // Ideally this URL would be something that represents an empty tab better than localhost
        let url = URL(string: "http://localhost")!
        SFSafariApplication.getActiveWindow { (activeWindow) in
            activeWindow?.openTab(with: url, makeActiveIfPossible: true, completionHandler: {_ in
                // Perform some action here after the page loads
            })
        }
    }

}


//
//  CardSet.swift
//  HSTracker
//
//  Created by Benjamin Michotte on 8/06/16.
//  Copyright © 2016 Benjamin Michotte. All rights reserved.
//

import Foundation

// swiftlint:disable type_name
enum CardSet: String {
    case all // fake one
    case fp1, pe1
    case core, expert1, naxx, gvg, brm,
    tgt, loe, promo, reward, hero_skins,
    og, kara, gangs, ungoro, hof

    static func allValues() -> [CardSet] {
        return [.core, .expert1, .naxx, .gvg, .brm,
                .tgt, .loe, .promo, .reward, .hero_skins,
                .og, .kara, .gangs, .ungoro]
    }

    static func deckManagerValidCardSets() -> [CardSet] {
        return [.all, .expert1, .naxx, .gvg, .brm, .tgt, .loe, .og, .kara, .gangs, .ungoro]
    }

    static func wildSets() -> [CardSet] {
        return [.all, .expert1, .naxx, .gvg, .brm, .tgt, .loe, .og, .kara, .gangs, .ungoro]
    }
}

Add Hall Of Fame cards

//
//  CardSet.swift
//  HSTracker
//
//  Created by Benjamin Michotte on 8/06/16.
//  Copyright © 2016 Benjamin Michotte. All rights reserved.
//

import Foundation

// swiftlint:disable type_name
enum CardSet: String {
    case all // fake one
    case core, expert1, naxx, gvg, brm,
    tgt, loe, promo, reward, hero_skins,
    og, kara, gangs, ungoro, hof

    static func allValues() -> [CardSet] {
        return [.core, .expert1, .naxx, .gvg, .brm,
                .tgt, .loe, .promo, .reward, .hero_skins,
                .og, .kara, .gangs, .ungoro, .hof]
    }

    static func deckManagerValidCardSets() -> [CardSet] {
        return [.all, .expert1, .naxx, .gvg, .brm, .tgt, .loe, .og, .kara, .gangs, .ungoro]
    }

    static func wildSets() -> [CardSet] {
        return [.naxx, .gvg, .brm, .tgt, .loe, .hof, .promo]
    }
}


// RUN: %target-run-simple-swift | FileCheck %s
// <rdar://problem/17014037>
// REQUIRES: OS=macosx

import QuartzCore

class Canary: NSObject {
  deinit {
    print("died")
  }
}

var CanaryAssocObjectHandle: UInt8 = 0

// Hack to build with both older and newer SDKs.
// rdar://problem/19494514
extension UInt {
  static let OBJC_ASSOCIATION_RETAIN_NONATOMIC: UInt = 1
}

// Attach an associated object with a loud deinit so we can see that the
// error died.
func hangCanary(o: AnyObject) {
  objc_setAssociatedObject(o, &CanaryAssocObjectHandle, Canary(),
                           .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}

class FooLayer: CALayer {
  var black: CGColor
  var white: CGColor = CGColorGetConstantColor(kCGColorWhite)

  override init() {
    black = CGColorGetConstantColor(kCGColorBlack)
    super.init()
    hangCanary(self)
  }

  required init?(coder: NSCoder) {
    black = coder.decodeObjectForKey("black") as! CGColor
    super.init(coder: coder)
  }

  override var description: String {
    return "FooLayer"
  }
}

if true {
  let layer = FooLayer()
  print("\(layer)")
}

// CHECK: FooLayer
// CHECK: died

Update test for newer SDK (on behalf of Jordan Rose).

// RUN: %target-run-simple-swift | FileCheck %s
// <rdar://problem/17014037>
// REQUIRES: OS=macosx

import QuartzCore

class Canary: NSObject {
  deinit {
    print("died")
  }
}

var CanaryAssocObjectHandle: UInt8 = 0

// Hack to build with both older and newer SDKs.
// rdar://problem/19494514
extension UInt {
  static let OBJC_ASSOCIATION_RETAIN_NONATOMIC: UInt = 1
}

// Attach an associated object with a loud deinit so we can see that the
// error died.
func hangCanary(o: AnyObject) {
  objc_setAssociatedObject(o, &CanaryAssocObjectHandle, Canary(),
                           .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}

class FooLayer: CALayer {
  var black: CGColor
  var white: CGColor = CGColorGetConstantColor(kCGColorWhite)!

  override init() {
    black = CGColorGetConstantColor(kCGColorBlack)!
    super.init()
    hangCanary(self)
  }

  required init?(coder: NSCoder) {
    black = coder.decodeObjectForKey("black") as! CGColor
    super.init(coder: coder)
  }

  override var description: String {
    return "FooLayer"
  }
}

if true {
  let layer = FooLayer()
  print("\(layer)")
}

// CHECK: FooLayer
// CHECK: died


//
//  UIImage.swift
//  Core
//
//  Created by Nahuel Gladstein on 6/8/17.
//  Copyright © 2017 Wolox. All rights reserved.
//

import UIKit

public extension UIImage {

    func resizedImage(_ wantedSize: CGSize, cornerRadius: CGFloat = 0.0) -> UIImage {
        let newSize = size.resizedMaintainingRatio(wantedSize: wantedSize)

        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        if cornerRadius > 0 {
            let path = UIBezierPath(
                        roundedRect:CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height),
                        cornerRadius: cornerRadius)
            path.addClip()
        }
        draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return newImage
    }

}

private extension CGSize {

    func resizedMaintainingRatio(wantedSize: CGSize) -> CGSize {
        let widthFactor = width / wantedSize.width
        let heightFactor = height / wantedSize.height
        let resizeFactor = height > width ? heightFactor : widthFactor

        return CGSize(width: width / resizeFactor, height: height / resizeFactor)
    }

}

Fix access modifiers, rename method

//
//  UIImage.swift
//  Core
//
//  Created by Nahuel Gladstein on 6/8/17.
//  Copyright © 2017 Wolox. All rights reserved.
//

import UIKit

public extension UIImage {

    public func resizedTo(_ wantedSize: CGSize, cornerRadius: CGFloat = 0.0) -> UIImage {
        let newSize = size.resizedMaintainingRatio(wantedSize: wantedSize)

        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        if cornerRadius > 0 {
            let path = UIBezierPath(
                        roundedRect:CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height),
                        cornerRadius: cornerRadius)
            path.addClip()
        }
        draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return newImage
    }

}

fileprivate extension CGSize {

    fileprivate func resizedMaintainingRatio(wantedSize: CGSize) -> CGSize {
        let widthFactor = width / wantedSize.width
        let heightFactor = height / wantedSize.height
        let resizeFactor = height > width ? heightFactor : widthFactor

        return CGSize(width: width / resizeFactor, height: height / resizeFactor)
    }

}


//
//  UniformString.swift
//  UniformString
//
//  Created by Henry Tseng on 2015/2/12.
//  Copyright (c) 2015年 Cloudbay. All rights reserved.
//

import Foundation

extension String {

    public func length() -> Int! {
        return count(self)
    }

    public func search(str : String) -> Range<String.Index>? {
        return self.rangeOfString(str)
    }

    public func splitBy(character : Character) -> [String]? {
        return split(self, {$0==character}, maxSplit: Int.max, allowEmptySlices: false)
    }

    public func replace(string : String, withString : String) -> String {
        return self.stringByReplacingOccurrencesOfString(string, withString: withString, options: .LiteralSearch, range: nil)
    }

    public func trim() -> String {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }

    subscript (r: Range<Int>) -> String {
        get {
            let startIndex = advance(self.startIndex, r.startIndex)
            let endIndex = advance(startIndex, r.endIndex - r.startIndex)

            return self[Range(start: startIndex, end: endIndex)]
        }
    }
}

Add html string escape / unescape.

//
//  UniformString.swift
//  UniformString
//
//  Created by Henry Tseng on 2015/2/12.
//  Copyright (c) 2015年 Cloudbay. All rights reserved.
//

import Foundation

extension String {

    public func length() -> Int! {
        return count(self)
    }

    public func search(str : String) -> Range<String.Index>? {
        return self.rangeOfString(str)
    }

    public func splitBy(character : Character) -> [String]? {
        return split(self, {$0==character}, maxSplit: Int.max, allowEmptySlices: false)
    }

    public func sub(string : String, _ withString : String) -> String {
        return self.stringByReplacingOccurrencesOfString(string, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
    }

    public func gsub(string : String, withString : String) -> String {
        return self.stringByReplacingOccurrencesOfString(string, withString: withString, options: .LiteralSearch, range: nil)
    }

    public func trim() -> String {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }

    public func escape() -> String? {
        return self.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
    }

    public func unescape() -> String? {
        return self.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
    }

    subscript (r: Range<Int>) -> String {
        get {
            let startIndex = advance(self.startIndex, r.startIndex)
            let endIndex = advance(startIndex, r.endIndex - r.startIndex)

            return self[Range(start: startIndex, end: endIndex)]
        }
    }
}


//
//  Button.swift
//  GtsiapKit
//
//  Created by Giorgos Tsiapaliokas on 09/10/15.
//  Copyright © 2015 Giorgos Tsiapaliokas. All rights reserved.
//

import UIKit

extension UIButton {

    public convenience init(_ text: String, target: AnyObject, action: Selector) {
        self.init()
        setTitle(text, forState: .Normal)
        addTarget(target, action: action, forControlEvents: .TouchUpInside)

        translatesAutoresizingMaskIntoConstraints = false
    }

}

Add a type for the buttons

//
//  Button.swift
//  GtsiapKit
//
//  Created by Giorgos Tsiapaliokas on 09/10/15.
//  Copyright © 2015 Giorgos Tsiapaliokas. All rights reserved.
//

import UIKit

extension UIButton {

    public convenience init(_ text: String, target: AnyObject, action: Selector) {
        self.init(type: .System)
        setTitle(text, forState: .Normal)
        addTarget(target, action: action, forControlEvents: .TouchUpInside)

        translatesAutoresizingMaskIntoConstraints = false
    }

}


// MARK: Summation

prefix operator ∑
public prefix func ∑ <T>(values: [T]) -> T where T : Numeric & ExpressibleByIntegerLiteral {
    return values.reduce(0, +)
}

// MARK: Cartesian Product

prefix operator ∏
public prefix func ∏ <T>(values: [T]) -> T where T : Numeric & ExpressibleByIntegerLiteral {
    return values.reduce(1, *)
}

Redefine Summation and Cartesian Product operators in terms of Sequence type

// MARK: Summation

prefix operator ∑
public prefix func ∑ <S: Sequence>(values: S) -> S.Element where S.Element : Numeric & ExpressibleByIntegerLiteral {
    return values.reduce(0, +)
}

// MARK: Cartesian Product

prefix operator ∏
public prefix func ∏ <S: Sequence>(values: S) -> S.Element where S.Element : Numeric & ExpressibleByIntegerLiteral {
    return values.reduce(1, *)
}


//
//  RootRouter.swift
//  Peekazoo
//
//  Created by Thomas Sherwood on 13/05/2017.
//  Copyright © 2017 Peekazoo. All rights reserved.
//

import UIKit

struct RootRouter {

    var window: UIWindow

    init(window: UIWindow) {
        self.window = window
    }

    func navigateToRoot() -> (viewController: UIViewController, router: Any) {
        let homepage = HomepageViewController()
        window.rootViewController = UINavigationController(rootViewController: homepage)
        window.isHidden = false
        window.makeKey()

        return (viewController: homepage, router: HomepageRouter())
    }

}

Use convenience function for preparing window

//
//  RootRouter.swift
//  Peekazoo
//
//  Created by Thomas Sherwood on 13/05/2017.
//  Copyright © 2017 Peekazoo. All rights reserved.
//

import UIKit

struct RootRouter {

    var window: UIWindow

    init(window: UIWindow) {
        self.window = window
    }

    func navigateToRoot() -> (viewController: UIViewController, router: Any) {
        let homepage = HomepageViewController()
        window.rootViewController = UINavigationController(rootViewController: homepage)
        window.makeKeyAndVisible()

        return (viewController: homepage, router: HomepageRouter())
    }

}