//
//  Operators.swift
//  Pods
//
//  Created by doof nugget on 5/24/16.
//
//

// The bind operator for Monads.
infix operator =>> { associativity left precedence 150 }

// The continuation operator for Monads.
infix operator ->> { associativity left precedence 150 }

// The fmap operator for Functors.
infix operator <^> { associativity left precedence 150 }

Add the function composition operators.

//
//  Operators.swift
//  Pods
//
//  Created by doof nugget on 5/24/16.
//
//

// The bind operator for Monads.
infix operator =>> { associativity left precedence 150 }

// The continuation operator for Monads.
infix operator ->> { associativity left precedence 150 }

// The fmap operator for Functors.
infix operator <^> { associativity left precedence 150 }

// Left-to-right function composition.
infix operator .>> { associativity left precedence 200 }

/**
 Left-to-right point-free functino composition.

 parameters:
   - f: A function of type `T -> U`.
   - g: A function of type `U -> V`.
 returns: A new function of type `T -> U`.
 */
public func .>> <T, U, V> (f: T -> U, g: U -> V) -> T -> V {
    return { t in g(f(t)) }
}

// Right-to-left function composition.
infix operator .<< { associativity left precedence 200 }

/**
 Right-to-left point-free function composition.

 parameters:
 - g: A function of type `U -> V`.
 - f: A function of type `T -> U`.
 returns: A new function of type `T -> U`.
 */
public func .<< <T, U, V> (g: U -> V, f: T -> U) -> T -> V {
    return { t in g(f(t)) }
}


// REQUIRES: VENDOR=apple
// REQUIRES: OS=macosx

// RUN: %empty-directory(%t)

// RUN: %target-swift-frontend -typecheck %s -emit-tbd -emit-tbd-path %t/linker_directives.tbd -previous-module-installname-map-file %S/Inputs/install-name-map.json >& %t/remark.txt
// RUN: %FileCheck %s < %t/remark.txt

// CHECK: remark: default previous install name for Foo is /System/default
// CHECK: remark: previous install name for Foo in macOS is /System/MacOS
// CHECK: remark: previous install name for Foo in iOS is /System/Others
// CHECK: remark: previous install name for Foo in tvOS is /System/Others
// CHECK: remark: previous install name for Foo in watchOS is /System/Others

Disable test that fails on the ASAN bot

// REQUIRES: VENDOR=apple
// REQUIRES: OS=macosx

// RUN: %empty-directory(%t)

// RUN: %target-swift-frontend -typecheck %s -emit-tbd -emit-tbd-path %t/linker_directives.tbd -previous-module-installname-map-file %S/Inputs/install-name-map.json >& %t/remark.txt
// RUN: %FileCheck %s < %t/remark.txt

// CHECK: remark: default previous install name for Foo is /System/default
// CHECK: remark: previous install name for Foo in macOS is /System/MacOS
// CHECK: remark: previous install name for Foo in iOS is /System/Others
// CHECK: remark: previous install name for Foo in tvOS is /System/Others
// CHECK: remark: previous install name for Foo in watchOS is /System/Others

// REQUIRES: rdar58569201


/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

import Foundation
import FBSimulatorControl

let arguments = NSProcessInfo.processInfo().arguments.dropFirst(1)
let argumentSet = Set(arguments)
FBSimulatorControlGlobalConfiguration.setDebugLoggingEnabled(argumentSet.contains(Flags.DebugLogging))

let environment = NSProcessInfo.processInfo().environment

let returnCode = Command
  .fromArguments(Array(NSProcessInfo.processInfo().arguments.dropFirst(1)), environment: environment)
  .runFromCLI()

exit(returnCode)

Use existing arguments at top level

/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

import Foundation
import FBSimulatorControl

let arguments = Array(NSProcessInfo.processInfo().arguments.dropFirst(1))
let argumentSet = Set(arguments)
FBSimulatorControlGlobalConfiguration.setDebugLoggingEnabled(argumentSet.contains(Flags.DebugLogging))

let environment = NSProcessInfo.processInfo().environment

let returnCode = Command
  .fromArguments(arguments, environment: environment)
  .runFromCLI()

exit(returnCode)


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

extension Expression where Recur: TermType {
	public static var list: Module<Recur> {
		return Module([
			Declaration.Data("List", .Type, {
				[
					"nil": .End,
					"cons": .Argument($0, const(.Recursive(.End)))
				]
			})
		])
	}
}

import Prelude

Build a type constructor directly.

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

extension Expression where Recur: TermType {
	public static var list: Module<Recur> {
		return Module([
			Declaration.Datatype("List", .Argument(.Type, {
				.End([
					"nil": .End,
					"cons": .Argument($0, const(.Recursive(.End)))
				])
			}))
		])
	}
}

import Prelude


//
//  FBSimulator+PXCTestKit.swift
//  pxctest
//
//  Created by Johannes Plunien on 04/12/16.
//  Copyright © 2016 Johannes Plunien. All rights reserved.
//

import FBSimulatorControl
import Foundation

extension Sequence where Iterator.Element == FBSimulator {

    func boot(context: RunTestsCommand.Context) throws {
        let simulatorBootConfiguration = FBSimulatorBootConfiguration
            .withLocalizationOverride(FBLocalizationOverride.withLocale(context.locale))
            .withOptions(context.simulatorBootOptions)

        for simulator in self {
            if simulator.state == .booted {
                continue
            }

            try simulator.interact
                .prepare(forBoot: simulatorBootConfiguration)
                .bootSimulator(simulatorBootConfiguration)
                .perform()
        }
    }

    func loadPreferences(context: RunTestsCommand.Context) throws {
        for simulator in self {
            try simulator.interact
                .loadPreferences(context.preferences)
                .perform()
        }
    }

}

Move Sequence extension code around

//
//  FBSimulator+PXCTestKit.swift
//  pxctest
//
//  Created by Johannes Plunien on 04/12/16.
//  Copyright © 2016 Johannes Plunien. All rights reserved.
//

import FBSimulatorControl
import Foundation

extension FBSimulator {

    func boot(context: RunTestsCommand.Context) throws {
        guard state != .booted else { return }
        let simulatorBootConfiguration = FBSimulatorBootConfiguration
            .withLocalizationOverride(FBLocalizationOverride.withLocale(context.locale))
            .withOptions(context.simulatorBootOptions)
        try interact
            .prepare(forBoot: simulatorBootConfiguration)
            .bootSimulator(simulatorBootConfiguration)
            .perform()
    }

    func loadPreferences(context: RunTestsCommand.Context) throws {
        try interact
            .loadPreferences(context.preferences)
            .perform()
    }

}

extension Sequence where Iterator.Element == FBSimulator {

    func boot(context: RunTestsCommand.Context) throws {
        for simulator in self {
            try simulator.boot(context: context)
        }
    }

    func loadPreferences(context: RunTestsCommand.Context) throws {
        for simulator in self {
            try simulator.loadPreferences(context: context)
        }
    }

}


/*
 |  _   ____   ____   _
 | | |‾|  ⚈ |-| ⚈  |‾| |
 | | |  ‾‾‾‾| |‾‾‾‾  | |
 |  ‾        ‾        ‾
 */

import Foundation

public extension NSMutableAttributedString {

    public func increaseFontSize(by multiplier: CGFloat) {
        enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, length), options: []) { (font, range, stop) in
            guard let font = font as? UIFont else { return }
            let newFont = font.withSize(font.pointSize * multiplier)
            removeAttribute(NSFontAttributeName, range: range)
            addAttribute(NSFontAttributeName, value: newFont, range: range)
        }
    }

}

public extension NSAttributedString {

    public func withIncreasedFontSize(by multiplier: CGFloat) -> NSAttributedString {
        let mutableCopy = NSMutableAttributedString(attributedString: self)
        mutableCopy.increaseFontSize(by: multiplier)
        return mutableCopy
    }

}

Add highlighting for attributed strings

/*
 |  _   ____   ____   _
 | | |‾|  ⚈ |-| ⚈  |‾| |
 | | |  ‾‾‾‾| |‾‾‾‾  | |
 |  ‾        ‾        ‾
 */

import Foundation

public extension NSMutableAttributedString {

    public func increaseFontSize(by multiplier: CGFloat) {
        enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, length), options: []) { (font, range, stop) in
            guard let font = font as? UIFont else { return }
            let newFont = font.withSize(font.pointSize * multiplier)
            removeAttribute(NSFontAttributeName, range: range)
            addAttribute(NSFontAttributeName, value: newFont, range: range)
        }
    }

    func highlightStrings(_ stringToHighlight: String, color: UIColor) {
        guard !stringToHighlight.isEmpty else { return }
        do {
            let expression = try NSRegularExpression(pattern: stringToHighlight, options: [.caseInsensitive, .ignoreMetacharacters])
            let matches = expression.matches(in: string, options: [], range: NSRange(location: 0, length: length))
            for match in matches {
                self.addAttribute(NSBackgroundColorAttributeName, value: color, range: match.range)
            }
        } catch {
            print("status=could-not-create-regex error=\(error)")
        }
    }

}

public extension NSAttributedString {

    public func withIncreasedFontSize(by multiplier: CGFloat) -> NSAttributedString {
        let mutableCopy = NSMutableAttributedString(attributedString: self)
        mutableCopy.increaseFontSize(by: multiplier)
        return mutableCopy
    }

}


//
//  ViewController.swift
//  PinpointKitExample
//
//  Created by Paul Rehkugler on 2/7/16.
//  Copyright © 2016 Lickability. All rights reserved.
//

import UIKit
import PinpointKit

final class ViewController: UIViewController {

    let pinpointKit = PinpointKit(configuration: Configuration(feedbackRecipients: ["hello@lickability.com"]), delegate: nil)

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.lightGrayColor()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        pinpointKit.show(fromViewController: self)
    }
}

Revert "Adds some test code to see the recipients in action"

//
//  ViewController.swift
//  PinpointKitExample
//
//  Created by Paul Rehkugler on 2/7/16.
//  Copyright © 2016 Lickability. All rights reserved.
//

import UIKit
import PinpointKit

final class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.lightGrayColor()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        PinpointKit.defaultPinpointKit.show(fromViewController: self)
    }
}


import Console
import Command

/// Vapor's main command.
internal struct MainCommand: CommandGroup {
    var commands: [String: CommandRunnable]
    var defaultRunnable: CommandRunnable?
    var options: [CommandOption]
    var help: [String]

    init(commands: [String: CommandRunnable], defaultRunnable: CommandRunnable?) {
        self.commands = commands
        self.options = [
            .flag(name: "version", short: "c", help: ["Displays the framework's version"])
        ]
        self.help = ["Runs your Vapor application's commands"]
        self.defaultRunnable = defaultRunnable
    }

    func run(using context: CommandContext) throws {
        if context.options["version"] == "true" {
            context.console.info("Vapor Framework v", newLine: false)
            context.console.print("3.0")
        } else {
            if let lazy = self.defaultRunnable {
                try lazy.run(using: context)
            } else {
                throw VaporError(identifier: "noDefaultCommand", reason: "No default command has been registered.", source: .capture())
            }
        }
    }
}

Change short flag for version command to "v"

import Console
import Command

/// Vapor's main command.
internal struct MainCommand: CommandGroup {
    var commands: [String: CommandRunnable]
    var defaultRunnable: CommandRunnable?
    var options: [CommandOption]
    var help: [String]

    init(commands: [String: CommandRunnable], defaultRunnable: CommandRunnable?) {
        self.commands = commands
        self.options = [
            .flag(name: "version", short: "v", help: ["Displays the framework's version"])
        ]
        self.help = ["Runs your Vapor application's commands"]
        self.defaultRunnable = defaultRunnable
    }

    func run(using context: CommandContext) throws {
        if context.options["version"] == "true" {
            context.console.info("Vapor Framework v", newLine: false)
            context.console.print("3.0")
        } else {
            if let lazy = self.defaultRunnable {
                try lazy.run(using: context)
            } else {
                throw VaporError(identifier: "noDefaultCommand", reason: "No default command has been registered.", source: .capture())
            }
        }
    }
}


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

// RUN: not --crash %target-swift-frontend %s -emit-ir
// REQUIRES: asserts, OS=linux-gnu
f
let c
{{guard{return.h.E == Int

Mark test as requiring deterministic variable (due to type variables escaping).

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

// RUN: not --crash %target-swift-frontend %s -emit-ir
// REQUIRES: deterministic-behavior
f
let c
{{guard{return.h.E == Int


import Foundation

var input: Array<Array<Int>> = []

while true {
    let rowString = readLine(stripNewline: true)
    if rowString == nil || rowString!.isEmpty {
        break
    }
    let colStrings = rowString!.componentsSeparatedByString(" ")
    input.append(colStrings.map() { x in Int(x) ?? 0 })
}

let finder = PathFinder()
let (success, resistance, path) = finder.find(input)

print(success ? "Yes" : "No")
print(resistance)
print(path.map(){x in String(x)}.joinWithSeparator(" "))

Validate all rows have the same length

import Foundation

var input: Array<Array<Int>> = []

while true {
    let rowString = readLine(stripNewline: true)
    if rowString == nil || rowString!.isEmpty {
        break
    }
    let colStrings = rowString!.componentsSeparatedByString(" ")
    input.append(colStrings.map() { x in Int(x) ?? 0 })
}

var width: Int!
for row in input {
    width = width ?? row.count
    if row.count != width {
        fatalError("All rows must have the same length")
    }
}

let finder = PathFinder()
let (success, resistance, path) = finder.find(input)

print(success ? "Yes" : "No")
print(resistance)
print(path.map(){x in String(x)}.joinWithSeparator(" "))


import location;
import assert;

@dispatch=CONTROL
(int rank) f(int i) "turbine" "0.0.1" [
  "set <<rank>> [ adlb::rank ] ; puts \"HELLO <<i>>\""
];

@dispatch=WORKER
(int rank) g(int i) "turbine" "0.0.1" [
  "set <<rank>> [ adlb::rank ] ; puts \"HELLO <<i>>\""
];

main {
  foreach i in [1:50] {
    int engine_rank = randomEngineRank();
    assertEqual(@location=location_from_rank(engine_rank)f(0),
                engine_rank, "f(0)");

    f(1);

    int worker_rank = randomWorkerRank();
    assertEqual(@location=location_from_rank(worker_rank)g(2),
                worker_rank, "g(2)");

    g(3);
  }
}

Update test to work with new locations

import location;
import assert;

@dispatch=CONTROL
(int rank) f(int i) "turbine" "0.0.1" [
  "set <<rank>> [ adlb::rank ] ; puts \"HELLO <<i>>\""
];

@dispatch=WORKER
(int rank) g(int i) "turbine" "0.0.1" [
  "set <<rank>> [ adlb::rank ] ; puts \"HELLO <<i>>\""
];

main {
  foreach i in [1:50] {
    int engine_rank = random_engine().rank;
    assertEqual(@location=location_from_rank(engine_rank)f(0),
                engine_rank, "f(0)");

    f(1);

    int worker_rank = randomWorkerRank();
    assertEqual(@location=location_from_rank(worker_rank)g(2),
                worker_rank, "g(2)");

    g(3);
  }
}


//
//  TaggedToken.swift
//  Parsimmon
//
//  Created by Jordan Kay on 2/19/15.
//
//

import Foundation

//
//  ParsimmonTaggedToken.swift
//  Parsimmon
//
//  Created by Jordan Kay on 2/17/15.
//
//

import Foundation

class TaggedToken: NSObject, Equatable {
    let token: String
    let tag: String

    init(token: String, tag: String) {
        self.token = token
        self.tag = tag
    }

    override var hash: Int {
        return token.hash ^ tag.hash
    }

    override func isEqual(object: AnyObject?) -> Bool {
        if let taggedToken = object as? TaggedToken {
            return isEqualToTaggedToken(taggedToken)
        }
        return false
    }

    private func isEqualToTaggedToken(taggedToken: TaggedToken) -> Bool {
        return token == taggedToken.token && tag == taggedToken.tag
    }
}

extension TaggedToken: Printable {
    override var description: String {
        return "('\(token)' \(tag))"
    }
}

func ==(lhs: TaggedToken, rhs: TaggedToken) -> Bool {
    return lhs.token == rhs.token && lhs.tag == rhs.tag
}

Fix accidental duplicate boilerplate form copy-paste

//
//  TaggedToken.swift
//  Parsimmon
//
//  Created by Jordan Kay on 2/19/15.
//
//

import Foundation

class TaggedToken: NSObject, Equatable {
    let token: String
    let tag: String

    init(token: String, tag: String) {
        self.token = token
        self.tag = tag
    }

    override var hash: Int {
        return token.hash ^ tag.hash
    }

    override func isEqual(object: AnyObject?) -> Bool {
        if let taggedToken = object as? TaggedToken {
            return isEqualToTaggedToken(taggedToken)
        }
        return false
    }

    private func isEqualToTaggedToken(taggedToken: TaggedToken) -> Bool {
        return token == taggedToken.token && tag == taggedToken.tag
    }
}

extension TaggedToken: Printable {
    override var description: String {
        return "('\(token)' \(tag))"
    }
}

func ==(lhs: TaggedToken, rhs: TaggedToken) -> Bool {
    return lhs.token == rhs.token && lhs.tag == rhs.tag
}


import UIKit

extension ViewList
{
    func collectionView(
        _ collectionView:UICollectionView,
        layout collectionViewLayout:UICollectionViewLayout,
        sizeForItemAt indexPath:IndexPath) -> CGSize
    {
        guard

            let cellSize:CGSize = self.cellSize

        else
        {
            let width:CGFloat = collectionView.bounds.width
            let cellSize:CGSize = CGSize(
                width:width,
                height:kCellHeight)
            self.cellSize = cellSize

            return cellSize
        }

        return cellSize
    }

    func numberOfSections(
        in collectionView:UICollectionView) -> Int
    {
        return 1
    }

    func collectionView(
        _ collectionView:UICollectionView,
        numberOfItemsInSection section:Int) -> Int
    {
        let count:Int = controller.model.displayItems.count

        return count
    }

    func collectionView(
        _ collectionView:UICollectionView,
        cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
    {
        return UICollectionViewCell()
    }
}

Add cell for item at indexPath

import UIKit

extension ViewList
{
    //MARK: private

    private func modelAtIndex(indexPath:IndexPath) -> ModelListItem
    {
        let item:ModelListItem = controller.model.items[indexPath.item]

        return item
    }

    //MARK: internal

    func collectionView(
        _ collectionView:UICollectionView,
        layout collectionViewLayout:UICollectionViewLayout,
        sizeForItemAt indexPath:IndexPath) -> CGSize
    {
        guard

            let cellSize:CGSize = self.cellSize

        else
        {
            let width:CGFloat = collectionView.bounds.width
            let cellSize:CGSize = CGSize(
                width:width,
                height:kCellHeight)
            self.cellSize = cellSize

            return cellSize
        }

        return cellSize
    }

    func numberOfSections(
        in collectionView:UICollectionView) -> Int
    {
        return 1
    }

    func collectionView(
        _ collectionView:UICollectionView,
        numberOfItemsInSection section:Int) -> Int
    {
        let count:Int = controller.model.displayItems.count

        return count
    }

    func collectionView(
        _ collectionView:UICollectionView,
        cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
    {
        let item:ModelListItem = modelAtIndex(indexPath:indexPath)

        let cell:ViewListCollectionCell = collectionView.dequeueReusableCell(
            withReuseIdentifier:
            ViewListCollectionCell.reusableIdentifier,
            for:indexPath) as! ViewListCollectionCell
        cell.config(model:item)

        return cell
    }
}


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

import PackageDescription

let package = Package(
    name: "RxGCXMulticastDNSKit",
    platforms: [
        .iOS(.v9),
    ],
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "RxGCXMulticastDNSKit",
            targets: ["RxGCXMulticastDNSKit"]),
    ],
    dependencies: [
        .package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMinor(from: "6.0.0")),
        .package(url: "https://github.com/grandcentrix/GCXMulticastDNSKit.git", .upToNextMinor(from: "1.3.1"))
    ],
    targets: [
        .target(
            name: "RxGCXMulticastDNSKit",
            dependencies: ["RxSwift", "GCXMulticastDNSKit"],
            path: "RxGCXMulticastDNSKit"),
        .testTarget(
            name: "RxGCXMulticastDNSKitTests",
            dependencies: ["RxGCXMulticastDNSKit"],
            path: "RxGCXMulticastDNSKitTests"),
    ],
    swiftLanguageVersions: [.v5]
)

Fix SPM Dependency definition to RxSwift

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

import PackageDescription

let package = Package(
    name: "RxGCXMulticastDNSKit",
    platforms: [
        .iOS(.v9),
    ],
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "RxGCXMulticastDNSKit",
            targets: ["RxGCXMulticastDNSKit"]),
    ],
    dependencies: [
        .package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMajor(from: "6.0.0")),
        .package(url: "https://github.com/grandcentrix/GCXMulticastDNSKit.git", .upToNextMinor(from: "1.3.1"))
    ],
    targets: [
        .target(
            name: "RxGCXMulticastDNSKit",
            dependencies: ["RxSwift", "GCXMulticastDNSKit"],
            path: "RxGCXMulticastDNSKit"),
        .testTarget(
            name: "RxGCXMulticastDNSKitTests",
            dependencies: ["RxGCXMulticastDNSKit"],
            path: "RxGCXMulticastDNSKitTests"),
    ],
    swiftLanguageVersions: [.v5]
)


// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "LogicKit",
    products: [
        .library(name: "LogicKit", type: .static, targets: ["LogicKit"]),
        .executable(name: "lki", targets: ["lki"]),
    ],
    dependencies: [
        .package(url: "https://github.com/rxwei/Parsey", from: "2.0.0"),
    ],
    targets: [
        .target(name: "LogicKit"),
        .target(name: "LogicKitParser", dependencies: ["LogicKit", "Parsey"]),
        .target(name: "lki", dependencies: ["LogicKit", "LogicKitParser", "linenoise"]),
        .target(name: "linenoise"),

        .testTarget(name: "LogicKitTests", dependencies: ["LogicKit"]),
        .testTarget(name: "LogicKitParserTests", dependencies: ["LogicKit", "LogicKitParser"]),
    ]
)

Switch from rxwei/Parsey to kyouko-taiga/Parsey.

// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "LogicKit",
    products: [
        .library(name: "LogicKit", type: .static, targets: ["LogicKit"]),
        .executable(name: "lki", targets: ["lki"]),
    ],
    dependencies: [
        .package(url: "https://github.com/kyouko-taiga/Parsey", .branch("master")),
    ],
    targets: [
        .target(name: "LogicKit"),
        .target(name: "LogicKitParser", dependencies: ["LogicKit", "Parsey"]),
        .target(name: "lki", dependencies: ["LogicKit", "LogicKitParser", "linenoise"]),
        .target(name: "linenoise"),

        .testTarget(name: "LogicKitTests", dependencies: ["LogicKit"]),
        .testTarget(name: "LogicKitParserTests", dependencies: ["LogicKit", "LogicKitParser"]),
    ]
)


// swift-tools-version:3.1

import PackageDescription

let package = Package(
  name: "Umbrella"
)

Add a target to package description

// swift-tools-version:3.1

import PackageDescription

let package = Package(
  name: "Umbrella",
  targets: [
    Target(name: "Umbrella"),
  ]
)


// RUN: %target-run-simple-swift | FileCheck %s

func curry<T, U, V>(f: (T, U) -> V)(_ x: T)(_ y: U) -> V {
  return f(x, y)
}

let insult = curry(+)("I'm with stupid ☞ ")
println(insult("😡")) // CHECK: I'm with stupid ☞ 😡

let plus1 = curry(+)(1)
println(plus1(5)) // CHECK-NEXT: 6

let plus5 = curry(+)(5)
println(plus5(5)) // CHECK-NEXT: 10

println(insult("😰")) // CHECK-NEXT: I'm with stupid ☞ 😰

Add test cases from rdar://problem/19195470.

// RUN: %target-run-simple-swift | FileCheck %s

func curry<T, U, V>(f: (T, U) -> V)(_ x: T)(_ y: U) -> V {
  return f(x, y)
}

let insult = curry(+)("I'm with stupid ☞ ")
println(insult("😡")) // CHECK: I'm with stupid ☞ 😡

let plus1 = curry(+)(1)
println(plus1(5)) // CHECK-NEXT: 6

let plus5 = curry(+)(5)
println(plus5(5)) // CHECK-NEXT: 10

println(insult("😰")) // CHECK-NEXT: I'm with stupid ☞ 😰

// rdar://problem/19195470

func pair<T,U> (a: T) -> U -> (T,U) {
	return { b in (a,b)	}
}

func pair_<T,U> (a: T)(b: U) -> (T,U) {
	return (a,b)
}

infix operator <+> { }
func <+><T,U,V> (lhs: T?, rhs: T -> U -> V) -> U -> V? {
	if let x = lhs {
		return rhs(x)
	} else {
		return { _ in nil }
	}
}

let a : Int? = 23
let b : Int? = 42
println((b <+> pair)(a!)) // CHECK-NEXT: (42, 23)
println((b <+> pair_)(a!)) // CHECK-NEXT: (42, 23)


#include <builtins.swift>

main
{
  int A[][];

  int rows = 3;
  int columns = 3;
  foreach i in [0:rows-1]
  {
    A[i][0] = 0;
  }
  foreach i in [0:rows-1]
  {
    foreach j in [0:columns-1]
    {
      A[i][j] = 1;
    }
  }
}

Fix double-write bug in test, now passes

#include <builtins.swift>

main
{
  int A[][];

  int rows = 3;
  int columns = 3;
  foreach i in [0:rows-1]
  {
    A[i][0] = 0;
  }
  foreach i in [0:rows-1]
  {
    foreach j in [0:columns-1]
    {
      A[i][j+1] = 1;
    }
  }
}


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

import Either
import Prelude
import XCTest

final class EitherTests: XCTestCase {
	let left = Either<Int, String>.left(4)
	let right = Either<Int, String>.right("four")

	func isFull<T>(string: String) -> Either<T, Bool> {
		return .right(!string.isEmpty)
	}

	// MARK: - either

	func testEitherExtractsFromLeft() {
		let value = left.either(id, countElements)
		XCTAssertEqual(value, 4)
	}

	func testEitherExtractsFromRight() {
		let value = right.either(toString, id)
		XCTAssertEqual(value, "four")
	}

	// MARK: - map

	func testMapIgnoresLeftValues() {
		let result = left.map(const(5)).either(id, id)
		XCTAssertEqual(result, 4)
	}

	func testMapAppliesToRightValues() {
		let result = right.map(const(5)).either(id, id)
		XCTAssertEqual(result, 5)
	}
}

Test >>- over left values.

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

import Either
import Prelude
import XCTest

final class EitherTests: XCTestCase {
	let left = Either<Int, String>.left(4)
	let right = Either<Int, String>.right("four")

	func isFull<T>(string: String) -> Either<T, Bool> {
		return .right(!string.isEmpty)
	}

	// MARK: - either

	func testEitherExtractsFromLeft() {
		let value = left.either(id, countElements)
		XCTAssertEqual(value, 4)
	}

	func testEitherExtractsFromRight() {
		let value = right.either(toString, id)
		XCTAssertEqual(value, "four")
	}

	// MARK: - map

	func testMapIgnoresLeftValues() {
		let result = left.map(const(5)).either(id, id)
		XCTAssertEqual(result, 4)
	}

	func testMapAppliesToRightValues() {
		let result = right.map(const(5)).either(id, id)
		XCTAssertEqual(result, 5)
	}

	// MARK: - >>-

	func testFlatMapRetypesLeftValues() {
		let result = (left >>- isFull).either(id, const(0))
		XCTAssertEqual(result, 4)
	}
}


//
//  GTProgressBar.swift
//  Pods
//
//  Created by Grzegorz Tatarzyn on 19/09/2016.
//
//

import UIKit

public class GTProgressBar: UIView {
    private let backgroundView = UIView()
    private let fillView = UIView()
    private let backgroundViewBorder: CGFloat = 2
    private let backgroundViewBorderColor: UIColor = UIColor.black
    private let fillViewInset: CGFloat = 2
    private let fillViewBackgroundColor = UIColor.black

    public override init(frame: CGRect) {
        super.init(frame: frame)
        prepareSubviews()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        prepareSubviews()
    }

    private func prepareSubviews() {
        addSubview(backgroundView)
        addSubview(fillView)
    }

    public override func layoutSubviews() {
        backgroundView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
        backgroundView.layer.borderWidth = backgroundViewBorder
        backgroundView.layer.borderColor = backgroundViewBorderColor.cgColor

        let offset = backgroundViewBorder + fillViewInset
        fillView.frame = backgroundView.frame.insetBy(dx: offset, dy: offset)
        fillView.backgroundColor = fillViewBackgroundColor
    }
}

Use different constructor for creating frame for backgroundView. It makes the code look a bit cleaner

//
//  GTProgressBar.swift
//  Pods
//
//  Created by Grzegorz Tatarzyn on 19/09/2016.
//
//

import UIKit

public class GTProgressBar: UIView {
    private let backgroundView = UIView()
    private let fillView = UIView()
    private let backgroundViewBorder: CGFloat = 2
    private let backgroundViewBorderColor: UIColor = UIColor.black
    private let fillViewInset: CGFloat = 2
    private let fillViewBackgroundColor = UIColor.black

    public override init(frame: CGRect) {
        super.init(frame: frame)
        prepareSubviews()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        prepareSubviews()
    }

    private func prepareSubviews() {
        addSubview(backgroundView)
        addSubview(fillView)
    }

    public override func layoutSubviews() {
        backgroundView.frame = CGRect(origin: CGPoint.zero, size: frame.size)
        backgroundView.layer.borderWidth = backgroundViewBorder
        backgroundView.layer.borderColor = backgroundViewBorderColor.cgColor

        let offset = backgroundViewBorder + fillViewInset
        fillView.frame = backgroundView.frame.insetBy(dx: offset, dy: offset)
        fillView.backgroundColor = fillViewBackgroundColor
    }
}


import Foundation
import UIKit

public protocol OmiseTextFieldValidationDelegate {
    func textField(field: OmiseTextField, didChangeValidity isValid: Bool)
}

public class OmiseTextField: UITextField {
    public var isValid: Bool {
        // child-class override hook to provide validation logic.
        return true
    }

    public override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    init() {
        super.init(frame: CGRectZero)
        setup()
    }

    private func setup() {
        // addTarget(self, action: #selector(textChanged), forControlEvents: .EditingChanged)
        addTarget(self, action: #selector(OmiseTextField.textDidChange), forControlEvents: .EditingChanged)
        addTarget(self, action: #selector(OmiseTextField.didBeginEditing), forControlEvents: .EditingDidBegin)
        addTarget(self, action: #selector(OmiseTextField.didEndEditing), forControlEvents: .EditingDidEnd)
    }

    func didBeginEditing() {
        textColor = .blackColor()
    }

    func didEndEditing() {
        // TODO: 👇 unnecessary?
        textColor = isValid ? .blackColor() : .redColor();
    }

    func textDidChange() {
        textColor = isValid ? .blackColor() : .redColor();
    }
}

Fix red text during edition.

import Foundation
import UIKit

public protocol OmiseTextFieldValidationDelegate {
    func textField(field: OmiseTextField, didChangeValidity isValid: Bool)
}

public class OmiseTextField: UITextField {
    public var isValid: Bool {
        // child-class override hook to provide validation logic.
        return true
    }

    public override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    init() {
        super.init(frame: CGRectZero)
        setup()
    }

    private func setup() {
        // addTarget(self, action: #selector(textChanged), forControlEvents: .EditingChanged)
        addTarget(self, action: #selector(OmiseTextField.textDidChange), forControlEvents: .EditingChanged)
        addTarget(self, action: #selector(OmiseTextField.didBeginEditing), forControlEvents: .EditingDidBegin)
        addTarget(self, action: #selector(OmiseTextField.didEndEditing), forControlEvents: .EditingDidEnd)
    }

    func didBeginEditing() {
        textColor = .blackColor()
    }

    func didEndEditing() {
        textColor = isValid ? .blackColor() : .redColor();
    }

    func textDidChange() {
        // no-op for child overrides
    }
}


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

final class LocationTests: XCTestCase {
	func testTraversingAnExpressionReturnsALocationAtTheTraversedExpression() {
		assert(identity.explore().it, ==, identity)
	}

	func testTopLevelNodesHaveNoParents() {
		assert(Expression<Term>.Unit.explore().up?.it, ==, nil)
	}

	func testTopLevelNodesHaveNoSiblings() {
		assert(Expression<Term>.Unit.explore().left?.it, ==, nil)
		assert(Expression<Term>.Unit.explore().right?.it, ==, nil)
	}
}

import Assertions
@testable import Manifold
import XCTest

Test nullary nodes have no children.

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

final class LocationTests: XCTestCase {
	func testTraversingAnExpressionReturnsALocationAtTheTraversedExpression() {
		assert(identity.explore().it, ==, identity)
	}

	func testTopLevelNodesHaveNoParents() {
		assert(Expression<Term>.Unit.explore().up?.it, ==, nil)
	}

	func testTopLevelNodesHaveNoSiblings() {
		assert(Expression<Term>.Unit.explore().left?.it, ==, nil)
		assert(Expression<Term>.Unit.explore().right?.it, ==, nil)
	}

	func testNullaryNodesHaveNoChildren() {
		assert(Expression<Term>.Unit.explore().down?.it, ==, nil)
	}
}

import Assertions
@testable import Manifold
import XCTest


internal class QuickSelectedTestSuiteBuilder: QuickTestSuiteBuilder {

    let testCaseClass: AnyClass!

    var namespacedClassName: String {
        return NSStringFromClass(testCaseClass)
    }

    private static func className(fromTestCaseWithName name: String) -> String? {
        return name.characters.split("/").first.map(String.init)
    }

    private static func testCaseClass(forTestCaseWithName name: String) -> AnyClass? {
        guard let className = className(fromTestCaseWithName: name) else { return nil }
        guard let bundle = NSBundle.currentTestBundle else { return nil }

        if let testCaseClass = bundle.classNamed(className) {
            return testCaseClass
        }

        guard let moduleName = bundle.bundlePath.fileName else { return nil }

        return NSClassFromString("\(moduleName).\(className)")
    }

    init?(forTestCaseWithName name: String) {
        guard let testCaseClass = QuickSelectedTestSuiteBuilder.testCaseClass(forTestCaseWithName: name) else {
            self.testCaseClass = nil
            return nil
        }

        self.testCaseClass = testCaseClass
    }

    func buildTestSuite() -> QuickTestSuite {
        return QuickTestSuite(forTestCaseClass: testCaseClass)
    }

}

Move private static methods to private top-level functions

internal class QuickSelectedTestSuiteBuilder: QuickTestSuiteBuilder {

    let testCaseClass: AnyClass!

    var namespacedClassName: String {
        return NSStringFromClass(testCaseClass)
    }

    init?(forTestCaseWithName name: String) {
        guard let testCaseClass = testCaseClassForTestCaseWithName(name) else {
            self.testCaseClass = nil
            return nil
        }

        self.testCaseClass = testCaseClass
    }

    func buildTestSuite() -> QuickTestSuite {
        return QuickTestSuite(forTestCaseClass: testCaseClass)
    }

}

private func testCaseClassForTestCaseWithName(name: String) -> AnyClass? {
    func extractClassName(name: String) -> String? {
        return name.characters.split("/").first.map(String.init)
    }

    guard let className = extractClassName(name) else { return nil }
    guard let bundle = NSBundle.currentTestBundle else { return nil }

    if let testCaseClass = bundle.classNamed(className) {
        return testCaseClass
    }

    guard let moduleName = bundle.bundlePath.fileName else { return nil }

    return NSClassFromString("\(moduleName).\(className)")
}


// RUN: %target-swift-frontend -O -primary-file %s -emit-ir -g -o - | FileCheck %s

// CHECK-LABEL: define{{.*}}2fn
func fn() {
  print("two")
// CHECK-DAG: ![[LOC:.*]] = !DILocation(line: [[@LINE+1]], column: 11,
  print(0 - UInt(Process.arguments.count))
// CHECK-DAG: ![[LOC2:.*]] = !DILocation(line: [[@LINE+1]], column: 11,
  print(1 - UInt(Process.arguments.count))
  print("three")
}

// CHECK-DAG: call void @llvm.trap(), !dbg ![[LOC]]
// CHECK-DAG: unreachable, !dbg ![[LOC]]
// CHECK-DAG: call void @llvm.trap(), !dbg ![[LOC2]]
// CHECK-DAG: unreachable, !dbg ![[LOC2]]

Simplify this testcase and remove uses of print and Process.arguments. rdar://problem/20864015

// RUN: %target-swift-frontend -O -primary-file %s -emit-ir -g -o - | FileCheck %s
import StdlibUnittest
// CHECK-LABEL: define{{.*}}2fn
public var i : UInt32 = 1
public func fn() {
  _blackHole(i)
// CHECK-DAG: ![[LOC:.*]] = !DILocation(line: [[@LINE+1]], column: 16,
  _blackHole(0 - i)
// CHECK-DAG: ![[LOC2:.*]] = !DILocation(line: [[@LINE+1]], column: 16,
  _blackHole(0 - i)
  _blackHole(i)
}

// CHECK-DAG: call void @llvm.trap(), !dbg ![[LOC]]
// CHECK-DAG: unreachable, !dbg ![[LOC]]
// CHECK-DAG: call void @llvm.trap(), !dbg ![[LOC2]]
// CHECK-DAG: unreachable, !dbg ![[LOC2]]


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

import Foundation

class ResetPasswordOperation: ServiceOperation {

    private let request: ResetPasswordRequest

    init(email: String) {
        request = ResetPasswordRequest(email: email)
        super.init()
    }

    func start() {
        service.request(request, completion: handleResponse)
    }

    private func handleResponse(_ response: RequestResult<AnyObject>) {
        switch response {
        case .success: return
        case .failure: print ("error")
        }
    }

}

Return information if request was sent succesfull

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

import Foundation

class ResetPasswordOperation: ServiceOperation {

    private let request: ResetPasswordRequest
    var resultCompletion: ((_ success: Bool) -> ())?

    init(email: String) {
        request = ResetPasswordRequest(email: email)
        super.init()
    }

    func start(completion: ((_ success: Bool)->())?) {
        self.resultCompletion = completion
        service.request(request, completion: handleResponse)
    }

    private func handleResponse(_ response: RequestResult<AnyObject>) {
        switch response {
        case .success:
            resultCompletion?(true)
            return
        case .failure:
            resultCompletion?(false)
        }
    }

}


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

import AVFoundation

extension AVPlayerItem {

    public class func playerItemWithData(data : NSData) throws -> AVPlayerItem {
        let tempURL = NSURL.temporaryFileURL()
        try data.writeToURL(tempURL, options: NSDataWritingOptions(rawValue: 0))
        return self(URL: tempURL)
    }

}

Fix warning for missing init

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

import AVFoundation

extension AVPlayerItem {

    public class func playerItemWithData(data : NSData) throws -> AVPlayerItem {
        let tempURL = NSURL.temporaryFileURL()
        try data.writeToURL(tempURL, options: NSDataWritingOptions(rawValue: 0))
        return self.init(URL: tempURL)
    }

}


// RUN: %target-build-swift -module-cache-path %t/clang-module-cache -emit-ir -g %s -o - | FileCheck %s

import Dispatch
// CHECK-DAG: ![[QUEUE_T:[0-9]+]] = {{.*}} [_TtGSQaSC21dispatch_queue_attr_t_]
// CHECK-DAG: metadata ![[QUEUE_T]]{{.*}} ; [ DW_TAG_variable ] [queue] [line [[@LINE+1]]] [def]
var queue = dispatch_queue_create("queue", nil)

dispatch_sync(queue) { println("Hello world"); }

Clear module cache before running this test.

// RUN: rm -rf %t/clang-module-cache
// RUN: %target-build-swift -module-cache-path %t/clang-module-cache -emit-ir -g %s -o - | FileCheck %s

import Dispatch
// CHECK-DAG: ![[QUEUE_T:[0-9]+]] = {{.*}} [_TtGSQaSC21dispatch_queue_attr_t_]
// CHECK-DAG: metadata ![[QUEUE_T]]{{.*}} ; [ DW_TAG_variable ] [queue] [line [[@LINE+1]]] [def]
var queue = dispatch_queue_create("queue", nil)

dispatch_sync(queue) { println("Hello world"); }


//
//  FCConfiguration.swift
//  FlipConnectSDK
//
//  Created by Munir Wanis on 01/08/17.
//  Copyright © 2017 Flip Connect. All rights reserved.
//

import Foundation

public class FCConfiguration {

    /**
     Initialize the necessary configurations to run the SDK

     - Parameters:
        - apiToken: Token received to use API
        - clientID: Your ClientID
        - clientSecret: Your Client Secret
        - redirectURI: The desired redirect URI (example: some://example)
        - fingerPrintID: Used to send information to antifraud
    **/
    public init(environment: FCEnvironmentEnum, clientID: String, clientSecret: String, redirectURI: String, fingerPrintID: String? = nil) {
        FCConfiguration.environment = environment
        self.fingerPrintID = fingerPrintID
        self.clientID = clientID
        self.clientSecret = clientSecret
        self.redirectURI = redirectURI
    }

    /// Used to send information to antifraud
    public var fingerPrintID: String?

    /// Your ClientID
    public var clientID: String

    /// Your Client Secret
    public var clientSecret: String

    /// The desired redirect URI (example: some://example)
    public var redirectURI: String

    internal static var environment: FCEnvironmentEnum = .sandbox
}

Make Configuration properties static and internal

//
//  FCConfiguration.swift
//  FlipConnectSDK
//
//  Created by Munir Wanis on 01/08/17.
//  Copyright © 2017 Flip Connect. All rights reserved.
//

import Foundation

public class FCConfiguration {

    /**
     Initialize the necessary configurations to run the SDK

     - Parameters:
        - apiToken: Token received to use API
        - clientID: Your ClientID
        - clientSecret: Your Client Secret
        - redirectURI: The desired redirect URI (example: some://example)
        - fingerPrintID: Used to send information to antifraud
    **/
    public init(environment: FCEnvironmentEnum, clientID: String, clientSecret: String, redirectURI: String, fingerPrintID: String? = nil) {
        FCConfiguration.environment = environment
        FCConfiguration.fingerPrintID = fingerPrintID
        FCConfiguration.clientID = clientID
        FCConfiguration.clientSecret = clientSecret
        FCConfiguration.redirectURI = redirectURI
    }

    /// Used to send information to antifraud
    internal static var fingerPrintID: String?

    /// Your ClientID
    internal static var clientID: String = ""

    /// Your Client Secret
    internal static var clientSecret: String = ""

    /// The desired redirect URI (example: some://example)
    internal static var redirectURI: String = ""

    internal static var environment: FCEnvironmentEnum = .sandbox
}


//
//  Problem3.swift
//  ProjectEuler
//
//  Created by Tiago Henriques on 08/05/16.
//  Copyright © 2016 Tiago Henriques. All rights reserved.
//

import Foundation

class Problem3: Solvable {

    func solve() -> Int {
        return largestPrimeFactorOf(600851475143)
    }

    func largestPrimeFactorOf(number: Int) -> Int {
        var divisor = Int(sqrt(Float(number)))

        while divisor > 1 {
            if number % divisor == 0 && divisor.prime {
                return divisor
            }

            divisor -= 1
        }

        return 0
    }

}

Fix bug in Problem 3

//
//  Problem3.swift
//  ProjectEuler
//
//  Created by Tiago Henriques on 08/05/16.
//  Copyright © 2016 Tiago Henriques. All rights reserved.
//

import Foundation

class Problem3: Solvable {

    func solve() -> Int {
        return largestPrimeFactorOf(600851475143)
    }

    func largestPrimeFactorOf(number: Int) -> Int {
        var divisor = Int(ceil(sqrt(Float(number))))

        while divisor > 1 {
            if number % divisor == 0 && divisor.prime {
                return divisor
            }

            divisor -= 1
        }

        return 0
    }

}


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

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

private let module = Expression<Term>.list

@testable import Manifold
import XCTest

Test the expected type of `cons` specifically.

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

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

	func testTypeOfConsIsParameterizedByAType() {
		assert(module.context["cons"], ==, .lambda(.Type, { A in .lambda(A, const(.lambda(.Application("List", A), const(.Application("List", A))))) }))
	}
}

private let module = Expression<Term>.list

import Assertions
@testable import Manifold
import Prelude
import XCTest


/*
The challenge here is to implement the longestRun function so that the
longest run of the same continuous character will be selected from a String.
This excercise lends itself to TDD and we have provided a few basic tests below.
*/

import Cocoa

func longestRun(whole: String) -> String {
    return whole
}

// identity test
var zzzz = "zzzz"
assert(zzzz == longestRun(zzzz), "\(zzzz) should be the longest run of chars")

// book
// var book = "book"
// assert("oo" == longestRun(book), "longest run in \(book) is 'oo'")

Change return type to string array

/*
The challenge here is to implement the longestRun function so that the
longest run of the same continuous character will be selected from a String.
This excercise lends itself to TDD and we have provided a few basic tests below.
*/

import Cocoa

func longestRun(whole: String) -> [String] {
    return [whole]
}

// identity test
var zzzz = "zzzz"
assert([zzzz] == longestRun(zzzz), "\(zzzz) should be the longest run of chars")

// book
// var book = "book"
// assert("oo" == longestRun(book), "longest run in \(book) is 'oo'")


import CoreData

public protocol Model: class, Equatable, Hashable
{
    associatedtype Configuration: ModelConfiguration

    var id: Object.Id? { get set }
}

extension Model
{
    public var identified: Bool {
        return self.id != nil
    }
}

extension Model
{
    public var hashValue: Int {
        return ObjectIdentifier(self).hashValue
    }
}

public func ==<Lhs:Model, Rhs:Model>(lhs: Lhs, rhs: Rhs) -> Bool {
    return lhs === rhs
}

// MARK: -

public protocol ModelInitialiser
{
    init(id: Object.Id?)
}

Add identified protocol underneath model

import CoreData

public protocol Identified: class
{
    var id: Object.Id? { get set }
}

extension Identified
{
    public var identified: Bool {
        return self.id != nil
    }
}

// MARK: -

public protocol Model: class, Identified, Equatable, Hashable
{
    associatedtype Configuration: ModelConfiguration
}

extension Model
{
    public var hashValue: Int {
        return ObjectIdentifier(self).hashValue
    }
}

public func ==<Lhs:Model, Rhs:Model>(lhs: Lhs, rhs: Rhs) -> Bool {
    return lhs === rhs
}

// MARK: -

public protocol ModelInitialiser
{
    init(id: Object.Id?)
}


//
//  AbstractModel+SoftSerialization.swift
//  Apic
//
//  Created by Juan Jose Arreola on 20/04/16.
//  Copyright © 2016 Juanjo. All rights reserved.
//

import Foundation

public extension AbstractModel {

    public var softDictionary: [String: Any] {
        let mirror = Mirror(reflecting: self)
        var result = [String: Any]()
        for child in mirror.children {
            guard let property = child.label else {
                continue
            }
            let modelType = mirror.subjectType as! AbstractModel.Type
            if property == modelType.descriptionProperty {
                result["description"] = self.value(forKey: property)
                continue
            }
            if let value = self.value(forKey: property) {
                if let model = value as? AbstractModel {
                    result[property] = model.softDictionary
                } else if let models = value as? [AbstractModel] {
                    result[property] = models.map({ (model) -> [String: Any] in
                        return model.softDictionary
                    })
                } else {
                    result[property] = value
                }
            }
        }
        return result
    }
}

public extension Array where Element: AbstractModel {
    var softArray: [[String: Any]] {
        var result = [[String: Any]]()
        for element in self {
            result.append(element.softDictionary)
        }
        return result
    }
}

Fix remove public from extension

//
//  AbstractModel+SoftSerialization.swift
//  Apic
//
//  Created by Juan Jose Arreola on 20/04/16.
//  Copyright © 2016 Juanjo. All rights reserved.
//

import Foundation

public extension AbstractModel {

    var softDictionary: [String: Any] {
        let mirror = Mirror(reflecting: self)
        var result = [String: Any]()
        for child in mirror.children {
            guard let property = child.label else {
                continue
            }
            let modelType = mirror.subjectType as! AbstractModel.Type
            if property == modelType.descriptionProperty {
                result["description"] = self.value(forKey: property)
                continue
            }
            if let value = self.value(forKey: property) {
                if let model = value as? AbstractModel {
                    result[property] = model.softDictionary
                } else if let models = value as? [AbstractModel] {
                    result[property] = models.map({ (model) -> [String: Any] in
                        return model.softDictionary
                    })
                } else {
                    result[property] = value
                }
            }
        }
        return result
    }
}

public extension Array where Element: AbstractModel {
    var softArray: [[String: Any]] {
        var result = [[String: Any]]()
        for element in self {
            result.append(element.softDictionary)
        }
        return result
    }
}


//
//  Audible.swift
//  ZamzamCore
//
//  Created by Basem Emara on 3/25/16.
//  Copyright © 2016 Zamzam Inc. All rights reserved.
//

#if os(iOS)
import AVFoundation
import Foundation.NSBundle
import UIKit.UIApplication

public protocol Audible: AnyObject {
    var audioPlayer: AVAudioPlayer? { get set }
}

public extension Audible {
    func setupAudioPlayer(_ application: UIApplication, forResource fileName: String, bundle: Bundle = .main) {
        guard let sound = bundle.url(forResource: fileName, withExtension: nil),
            (audioPlayer == nil || audioPlayer?.url != sound) else {
                return
        }

        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
            try AVAudioSession.sharedInstance().setActive(true)

            application.beginReceivingRemoteControlEvents()

            audioPlayer = try AVAudioPlayer(contentsOf: sound)
            audioPlayer?.prepareToPlay()
        } catch {
            // TODO: Call injectable logger
            debugPrint(error)
        }
    }
}
#endif

Refactor audible audio player protocol

//
//  Audible.swift
//  ZamzamCore
//
//  Created by Basem Emara on 3/25/16.
//  Copyright © 2016 Zamzam Inc. All rights reserved.
//

import AVFoundation
import Foundation.NSBundle
import Foundation.NSURL

public protocol Audible: AnyObject {
    var audioPlayer: AVAudioPlayer? { get set }
}

public extension Audible {
    /// Configures and plays audio from a file.
    ///
    /// - Parameters:
    ///   - url: A `URL` that identifies the local audio file to play.
    ///   - application: The application used to control the audio events.
    func play(contentsOf url: URL, application: AudibleApplication? = nil) throws {
        if audioPlayer == nil || audioPlayer?.url != url {
            if audioPlayer?.isPlaying == true {
                audioPlayer?.stop()
            }

            audioPlayer = try AVAudioPlayer(contentsOf: url)
        }

        if audioPlayer?.currentTime != 0 {
            audioPlayer?.currentTime = 0
        }

        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)
        application?.beginReceivingRemoteControlEvents()

        audioPlayer?.play()
    }
}

#if os(iOS)
import UIKit.UIApplication

public protocol AudibleApplication {
    func beginReceivingRemoteControlEvents()
}

extension UIApplication: AudibleApplication {}
#endif


//
//  StringResource.swift
//  R.swift.Library
//
//  Created by Tom Lokhorst on 2016-04-23.
//  Copyright © 2016 Mathijs Kadijk. All rights reserved.
//

import Foundation

public protocol StringResourceType {

  /// Key for the string
  var key: String { get }

  /// File in containing the string
  var tableName: String { get }

  /// Locales of the a localizable string
  var locales: [String] { get }
}

public struct StringResource: StringResourceType {

  /// Key for the string
  public let key: String

  /// File in containing the string
  public let tableName: String

  /// Locales of the a localizable string
  public let locales: [String]

  public init(key: String, tableName: String, locales: [String]) {
    self.key = key
    self.tableName = tableName
    self.locales = locales
  }
}

Add bundle to string resource

//
//  StringResource.swift
//  R.swift.Library
//
//  Created by Tom Lokhorst on 2016-04-23.
//  Copyright © 2016 Mathijs Kadijk. All rights reserved.
//

import Foundation

public protocol StringResourceType {

  /// Key for the string
  var key: String { get }

  /// File in containing the string
  var tableName: String { get }

  /// Bundle this string is in
  var bundle: NSBundle { get }

  /// Locales of the a localizable string
  var locales: [String] { get }
}

public struct StringResource: StringResourceType {

  /// Key for the string
  public let key: String

  /// File in containing the string
  public let tableName: String

  /// Bundle this string is in
  public let bundle: NSBundle

  /// Locales of the a localizable string
  public let locales: [String]

  public init(key: String, tableName: String, bundle: NSBundle, locales: [String]) {
    self.key = key
    self.tableName = tableName
    self.bundle = bundle
    self.locales = locales
  }
}


import Darwin

let fns = [profitBruteforce, profitLinear]

let tests: [(prices: [Int], profit: Int)] = [
    (
        prices: [],
        profit: 0
    ),
    (
        prices: [1],
        profit: 0
    ),
    (
        prices: [1, 2],
        profit: 1
    ),
    (
        prices: [2, 1],
        profit: 0
    ),
    (
        prices: [3, 5, 1, 4],
        profit: 3
    ),
    (
        prices: [0, 5, 1, 4],
        profit: 5
    ),
    (
        prices: [0, 4, 1, 5],
        profit: 5
    ),
    (
        prices: [310, 315, 275, 295, 260, 270, 290, 230, 255, 250],
        profit: 30
    ),
]

for fn in fns {
    for test in tests {
        var actual = fn(test.prices)
        guard actual == test.profit else {
            print("For prices \(test.prices), expected profit to be \(test.profit), " +
                "but was \(actual)")
            exit(1)
        }
    }
}

Convert to new Swift version

import Darwin

let fns = [profitBruteforce, profitLinear]

let tests: [(prices: [Int], profit: Int)] = [
    (
        prices: [],
        profit: 0
    ),
    (
        prices: [1],
        profit: 0
    ),
    (
        prices: [1, 2],
        profit: 1
    ),
    (
        prices: [2, 1],
        profit: 0
    ),
    (
        prices: [3, 5, 1, 4],
        profit: 3
    ),
    (
        prices: [0, 5, 1, 4],
        profit: 5
    ),
    (
        prices: [0, 4, 1, 5],
        profit: 5
    ),
    (
        prices: [310, 315, 275, 295, 260, 270, 290, 230, 255, 250],
        profit: 30
    ),
]

for fn in fns {
    for test in tests {
        let actual = fn(test.prices)
        guard actual == test.profit else {
            print("For prices \(test.prices), expected profit to be \(test.profit), " +
                "but was \(actual)")
            exit(1)
        }
    }
}


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

import Set
import XCTest

final class MultisetCountTests: XCTestCase {
	func testCountSumsElementsMultiplicities() {
		XCTAssertEqual(Multiset(0, 1, 1).count, 3)
	}

	func testCountOfAnElementIsItsMultiplicity() {
		XCTAssertEqual(Multiset(0, 1, 1).count(1), 2)
	}

	func testContainsIsTrueWhenCountIsGreaterThanZero() {
		XCTAssert(Multiset(0, 1, 1).contains(0))
		XCTAssert(Multiset(0, 1, 1).contains(1))
		XCTAssertFalse(Multiset(0, 1, 1).contains(2))
	}

	func testNullMultisetIsEmpty() {
		XCTAssert(Multiset<Int>().isEmpty)
	}
}

Test that non-null multisets are not empty.

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

import Set
import XCTest

final class MultisetCountTests: XCTestCase {
	func testCountSumsElementsMultiplicities() {
		XCTAssertEqual(Multiset(0, 1, 1).count, 3)
	}

	func testCountOfAnElementIsItsMultiplicity() {
		XCTAssertEqual(Multiset(0, 1, 1).count(1), 2)
	}

	func testContainsIsTrueWhenCountIsGreaterThanZero() {
		XCTAssert(Multiset(0, 1, 1).contains(0))
		XCTAssert(Multiset(0, 1, 1).contains(1))
		XCTAssertFalse(Multiset(0, 1, 1).contains(2))
	}

	func testNullMultisetIsEmpty() {
		XCTAssert(Multiset<Int>().isEmpty)
	}

	func testNonNullConstructedMultisetIsNotEmpty() {
		XCTAssertFalse(Multiset(0).isEmpty)
	}
}


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

public enum Telescope<Recur: TermType> {
	case End
	indirect case Recursive(Telescope)
	indirect case Argument(Recur, Recur -> Telescope)

	public func fold(recur: Recur, terminal: Recur, combine: (Recur, Recur) -> Recur) -> Recur {
		switch self {
		case .End:
			return terminal
		case let .Recursive(rest):
			return combine(recur, rest.fold(recur, terminal: terminal, combine: combine))
		case let .Argument(type, continuation):
			return type => { continuation($0).fold(recur, terminal: terminal, combine: combine) }
		}
	}
}

import Prelude

Move the End case down.

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

public enum Telescope<Recur: TermType> {
	indirect case Recursive(Telescope)
	indirect case Argument(Recur, Recur -> Telescope)
	case End

	public func fold(recur: Recur, terminal: Recur, combine: (Recur, Recur) -> Recur) -> Recur {
		switch self {
		case .End:
			return terminal
		case let .Recursive(rest):
			return combine(recur, rest.fold(recur, terminal: terminal, combine: combine))
		case let .Argument(type, continuation):
			return type => { continuation($0).fold(recur, terminal: terminal, combine: combine) }
		}
	}
}

import Prelude


import Foundation

class RawSocketFactory {
    static func getRawSocket() -> RawSocketProtocol {
//        return GCDTCPSocket()
        return NWTCPSocket()
    }
}

Fix the bug that it now works with and without NetworkExtension

import Foundation

class RawSocketFactory {
    static func getRawSocket() -> RawSocketProtocol {
        if NetworkInterface.TunnelProvider == nil {
            return GCDTCPSocket()
        } else {
            return NWTCPSocket()
        }
    }
}


//
//  Bundle.swift
//  ISEmojiView
//
//  Created by Beniamin Sarkisyan on 01/08/2018.
//

import Foundation

extension Bundle {

    class var podBundle: Bundle {
        let podBundle = Bundle(for: EmojiView.classForCoder())

        guard let bundleURL = podBundle.url(forResource: "ISEmojiView", withExtension: "bundle") else {
            fatalError("Could not create a path to the bundle")
        }

        guard let bundle = Bundle(url: bundleURL) else {
            fatalError("Could not load the bundle")
        }

        return bundle
    }

}

Fix Carthage bundle load error

//
//  Bundle.swift
//  ISEmojiView
//
//  Created by Beniamin Sarkisyan on 01/08/2018.
//

import Foundation

extension Bundle {

    class var podBundle: Bundle {
        var podBundle = Bundle(for: EmojiView.classForCoder())

        // CocoaPods -> ISEmojiView.framework/ISEmojiView.bundle
        // Carthage  -> ISEmojiView.framework/
        if let bundleURL = podBundle.url(forResource: "ISEmojiView", withExtension: "bundle") {
            if let bundle = Bundle(url: bundleURL) {
                podBundle = bundle
            }
        }

        return podBundle
    }

}


import UIKit

/// Make your UIView subclasses
/// conform to this protocol when they *are* NIB-based
/// to be able to instantiate them from NIB in a type-safe manner
public protocol NibLoadable: class {
  /// The nib file to use to load a new instance of the View designed in a XIB
  static var nib: UINib { get }
}

// MARK: - Default implementation form NibLoadable

public extension NibLoadable {
  /// By default, use the nib which have the same name as the name of the class,
  /// and located in the main bundle
  static var nib: UINib {
    return UINib(nibName: String(Self), bundle: nil)
  }
}

// MARK: - Support for instantiation from nib

public extension NibLoadable where Self: UIView {
  /**
   Returns a `UIView` object instantiated from nib

   - returns: A `NibLoadable`, `UIView` instance
   */
  static func loadFromNib() -> Self {
    return nib.instantiateWithOwner(nil, options: nil).first as! Self
  }
}

Use correct bundle for class when loading nib

import UIKit

/// Make your UIView subclasses
/// conform to this protocol when they *are* NIB-based
/// to be able to instantiate them from NIB in a type-safe manner
public protocol NibLoadable: class {
  /// The nib file to use to load a new instance of the View designed in a XIB
  static var nib: UINib { get }
}

// MARK: - Default implementation form NibLoadable

public extension NibLoadable {
  /// By default, use the nib which have the same name as the name of the class,
  /// and located in the bundle of that class
  static var nib: UINib {
    return UINib(nibName: String(Self), bundle: NSBundle(forClass: self))
  }
}

// MARK: - Support for instantiation from nib

public extension NibLoadable where Self: UIView {
  /**
   Returns a `UIView` object instantiated from nib

   - returns: A `NibLoadable`, `UIView` instance
   */
  static func loadFromNib() -> Self {
    return nib.instantiateWithOwner(nil, options: nil).first as! Self
  }
}


/*
 This source file is part of the Swift.org open source project

 Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See http://swift.org/LICENSE.txt for license information
 See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/

/// Computes the number of edits needed to transform first string to second.
public func editDistance(_ first: String, _ second: String) -> Int {
    let a = Array(first.utf16)
    let b = Array(second.utf16)
    var distance = [[Int]](repeating: [Int](repeating: 0, count: b.count + 1), count: a.count + 1)
    for i in 0...a.count {
        for j in 0...b.count {
            if i == 0 {
                distance[i][j] = j
            } else if j == 0 {
                distance[i][j] = i
            } else if a[i - 1] == b[j - 1] {
                distance[i][j] = distance[i - 1][j - 1]
            } else {
                distance[i][j] = 1 + min(distance[i - 1][j], distance[i][ j - 1], distance[i - 1][j - 1])
            }
        }
    }
    return distance[a.count][b.count]
}

Break an expression in edit distance algorithm

/*
 This source file is part of the Swift.org open source project

 Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See http://swift.org/LICENSE.txt for license information
 See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/

/// Computes the number of edits needed to transform first string to second.
public func editDistance(_ first: String, _ second: String) -> Int {
    let a = Array(first.utf16)
    let b = Array(second.utf16)
    var distance = [[Int]](repeating: [Int](repeating: 0, count: b.count + 1), count: a.count + 1)
    for i in 0...a.count {
        for j in 0...b.count {
            if i == 0 {
                distance[i][j] = j
            } else if j == 0 {
                distance[i][j] = i
            } else if a[i - 1] == b[j - 1] {
                distance[i][j] = distance[i - 1][j - 1]
            } else {
                let insertion = distance[i][ j - 1]
                let deletion = distance[i - 1][j]
                let replacement = distance[i - 1][j - 1]
                distance[i][j] = 1 + min(insertion, deletion, replacement)
            }
        }
    }
    return distance[a.count][b.count]
}


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

import Foundation

public extension UserDefaults {

    public func observe<T: DefaultsSerializable>(key: DefaultsKey<T>, options: NSKeyValueObservingOptions, handler: @escaping (DefaultsObserver<T>.Update) -> Void) -> DefaultsDisposable {
        return DefaultsObserver(key: key, userDefaults: self, options: options, handler: handler)
    }
}

Add default options to defaults.observe()

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

import Foundation

public extension UserDefaults {

    public func observe<T: DefaultsSerializable>(key: DefaultsKey<T>, options: NSKeyValueObservingOptions = [.initial, .old, .new], handler: @escaping (DefaultsObserver<T>.Update) -> Void) -> DefaultsDisposable {
        return DefaultsObserver(key: key, userDefaults: self, options: options, handler: handler)
    }
}


//
//  TreemapSerieSpec.swift
//  SwiftyEcharts
//
//  Created by Pluto Y on 20/08/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import Quick
import Nimble
@testable import SwiftyEcharts

class TreemapSerieSpec: QuickSpec {
    override func spec() {
        describe("For TreemapSerie.NodeClick") {
            let disableString = "false"
            let zoomToNodeString = "zoomToNode"
            let linkString = "link"

            let disableNodeClick = TreemapSerie.NodeClick.disable
            let zoomToNodeNodeClick = TreemapSerie.NodeClick.zoomToNode
            let linkNodeClick = TreemapSerie.NodeClick.link

            it("needs to check the enum case jsonString") {
                expect(disableNodeClick.jsonString).to(equal(disableString.jsonString))
                expect(zoomToNodeNodeClick.jsonString).to(equal(zoomToNodeString.jsonString))
                expect(linkNodeClick.jsonString).to(equal(linkString.jsonString))
            }
        }
    }
}

Add test cases for `TreemapSerie.ColorMappingBy`

//
//  TreemapSerieSpec.swift
//  SwiftyEcharts
//
//  Created by Pluto Y on 20/08/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import Quick
import Nimble
@testable import SwiftyEcharts

class TreemapSerieSpec: QuickSpec {
    override func spec() {
        describe("For TreemapSerie.NodeClick") {
            let disableString = "false"
            let zoomToNodeString = "zoomToNode"
            let linkString = "link"

            let disableNodeClick = TreemapSerie.NodeClick.disable
            let zoomToNodeNodeClick = TreemapSerie.NodeClick.zoomToNode
            let linkNodeClick = TreemapSerie.NodeClick.link

            it("needs to check the enum case jsonString") {
                expect(disableNodeClick.jsonString).to(equal(disableString.jsonString))
                expect(zoomToNodeNodeClick.jsonString).to(equal(zoomToNodeString.jsonString))
                expect(linkNodeClick.jsonString).to(equal(linkString.jsonString))
            }
        }

        describe("For TreemapSerie.ColorMappingBy") {
            let valueString = "value"
            let indexString = "index"
            let idString = "id"

            let valueColorMappingBy = TreemapSerie.ColorMappingBy.value
            let indexColorMappingBy = TreemapSerie.ColorMappingBy.index
            let idColorMappingBy = TreemapSerie.ColorMappingBy.id

            it("needs to check the enum case jsonString") {
                expect(valueColorMappingBy.jsonString).to(equal(valueString.jsonString))
                expect(indexColorMappingBy.jsonString).to(equal(indexString.jsonString))
                expect(idColorMappingBy.jsonString).to(equal(idString.jsonString))
            }
        }
    }
}


//
//  TimeUnitTestsUtilities.swift
//  Tunits
//
//  Created by Tom on 12/27/15.
//  Copyright © 2015 CocoaPods. All rights reserved.
//

import Foundation

Add utility class for test calendars

//
//  TimeUnitTestsUtilities.swift
//  Tunits
//
//  Created by Tom on 12/27/15.
//  Copyright © 2015 CocoaPods. All rights reserved.
//

import Foundation
import Tunits

public class TimeUnitTestsUtilities : NSObject {
    public enum Weekday : Int {
        case Sunday = 1
        case Monday = 2
        case Tuesday = 3
        case Wednesday = 4
        case Thursday = 5
        case Friday = 6
        case Saturday = 7
    }

    public func timeUnitWithCalendarWithMondayAsFirstWeekday() -> TimeUnit {
        return self.timeUnitWithCalendarWithFirstWeekday(Weekday.Monday);
    }

    public func timeUnitWithCalendarWithSundayAsFirstWeekday() -> TimeUnit {
        return self.timeUnitWithCalendarWithFirstWeekday(Weekday.Sunday);
    }

    public func timeUnitWithCalendarWithFirstWeekday(weekday : Weekday) -> TimeUnit {
        let tunit = TimeUnit()
        tunit.calendar = self.calendarWithFirstWeekday(weekday)
        return tunit
    }

    public func calendarWithSundayAsFirstWeekday() -> NSCalendar {
        return self.calendarWithFirstWeekday(Weekday.Sunday)
    }

    public func calendarWithMondayAsFirstWeekday() -> NSCalendar {
        return self.calendarWithFirstWeekday(Weekday.Monday)
    }

    public func calendarWithFirstWeekday(weekday: Weekday) -> NSCalendar {
        let calendar = NSCalendar.currentCalendar()
        calendar.firstWeekday = weekday.rawValue
        return calendar
    }
}


//
//  Extension.swift
//  PageKit
//
//  Created by Jack on 4/6/17.
//  Copyright © 2017 Jack. All rights reserved.
//

import UIKit

public extension Int {

    /// Begin Page
    public static let begin: Int = -1

    /// End Page
    public static let end: Int = -2

    /// Easy to convert Int to CGFloat
    public var cgfloat: CGFloat { return CGFloat(self) }
}

public extension CGFloat {
    public var double: Double { return Double(self) }
}

public extension Array {
    func enumIndex(_ block: (Index, Element) -> ()) {
        for (index, element) in self.enumerated() { block(index, element) }
    }
}

Add resetBy UIEdgeInsets into extension

//
//  Extension.swift
//  PageKit
//
//  Created by Jack on 4/6/17.
//  Copyright © 2017 Jack. All rights reserved.
//

import UIKit

public extension Int {

    /// Begin Page
    public static let begin: Int = -1

    /// End Page
    public static let end: Int = -2

    /// Easy to convert Int to CGFloat
    public var cgfloat: CGFloat { return CGFloat(self) }
}

public extension CGFloat {
    public var double: Double { return Double(self) }
}

public extension Array {
    func enumIndex(_ block: (Index, Element) -> ()) {
        for (index, element) in self.enumerated() { block(index, element) }
    }
}

public extension CGRect {
    func resetBy(_ inset: UIEdgeInsets) -> CGRect {
        return CGRect(x: origin.x - inset.left,
                      y: origin.y - inset.top,
                      width: size.width - inset.left - inset.right,
                      height: size.height - inset.top - inset.bottom)
    }
}


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

import Quick
import Nimble
import RealmSwift
@testable import Habits

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

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

        describe("Store") {}
    }
}

Make sure Realm is empty before every test

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

import Quick
import Nimble
import RealmSwift
@testable import Habits

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

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

        describe("Store") {
            beforeEach {
                // Make sure Realm is empty before every test
                realm.write {
                    realm.deleteAll()
                }
            }
        }
    }
}


//
//  ChartAxisLabel.swift
//  swift_charts
//
//  Created by ischuetz on 01/03/15.
//  Copyright (c) 2015 ivanschuetz. All rights reserved.
//

import UIKit

/// A model of an axis label
public class ChartAxisLabel {

    /// Displayed text. Can be truncated.
    public let text: String

    public let settings: ChartLabelSettings

    public private(set) var originalText: String

    var hidden: Bool = false

    /// The size of the bounding rectangle for the axis label, taking into account the font and rotation it will be drawn with
    public lazy var textSize: CGSize = {
        let size = self.text.size(self.settings.font)
        if self.settings.rotation =~ 0 {
            return size
        } else {
            return CGRectMake(0, 0, size.width, size.height).boundingRectAfterRotating(radians: self.settings.rotation * CGFloat(M_PI) / 180.0).size
        }
    }()

    public init(text: String, settings: ChartLabelSettings) {
        self.text = text
        self.settings = settings
        self.originalText = text
    }

    func copy(text text: String? = nil, settings: ChartLabelSettings? = nil, originalText: String? = nil, hidden: Bool? = nil) -> ChartAxisLabel {
        let label = ChartAxisLabel(
            text: text ?? self.text,
            settings: settings ?? self.settings
        )
        self.originalText = originalText ?? self.originalText
        self.hidden = hidden ?? self.hidden
        return label
    }
}

Fix label not copying original text

//
//  ChartAxisLabel.swift
//  swift_charts
//
//  Created by ischuetz on 01/03/15.
//  Copyright (c) 2015 ivanschuetz. All rights reserved.
//

import UIKit

/// A model of an axis label
public class ChartAxisLabel {

    /// Displayed text. Can be truncated.
    public let text: String

    public let settings: ChartLabelSettings

    public private(set) var originalText: String

    var hidden: Bool = false

    /// The size of the bounding rectangle for the axis label, taking into account the font and rotation it will be drawn with
    public lazy var textSize: CGSize = {
        let size = self.text.size(self.settings.font)
        if self.settings.rotation =~ 0 {
            return size
        } else {
            return CGRectMake(0, 0, size.width, size.height).boundingRectAfterRotating(radians: self.settings.rotation * CGFloat(M_PI) / 180.0).size
        }
    }()

    public init(text: String, settings: ChartLabelSettings) {
        self.text = text
        self.settings = settings
        self.originalText = text
    }

    func copy(text text: String? = nil, settings: ChartLabelSettings? = nil, originalText: String? = nil, hidden: Bool? = nil) -> ChartAxisLabel {
        var label = ChartAxisLabel(
            text: text ?? self.text,
            settings: settings ?? self.settings
        )
        label.originalText = originalText ?? self.originalText
        label.hidden = hidden ?? self.hidden
        return label
    }
}


import UIKit

public extension UIControl {

    /// Adds a handler that will be invoked for the specified control events
    public func on(controlEvents: UIControlEvents, invokeHandler handler: (UIControl) -> Void) -> AnyObject {
        let closureHandler = ClosureHandler(handler: handler, control: self)
        addTarget(closureHandler, action: ClosureHandlerSelector, forControlEvents: controlEvents)
        return closureHandler
    }
}

Allow handlers to be removed from the UIControl they are attached to

import UIKit

public extension UIControl {

    /// Adds a handler that will be invoked for the specified control events
    public func on(controlEvents: UIControlEvents, invokeHandler handler: (UIControl) -> Void) -> AnyObject {
        let closureHandler = ClosureHandler(handler: handler, control: self)
        addTarget(closureHandler, action: ClosureHandlerSelector, forControlEvents: controlEvents)
        var handlers = self.handlers ?? Set<ClosureHandler<UIControl>>()
        handlers.insert(closureHandler)
        self.handlers = handlers
        return closureHandler
    }

    /// Removes a handler from the control
    public func removeHandler(handler: AnyObject) {
        guard let handler = handler as? ClosureHandler<UIControl> else { return }
        removeTarget(handler, action: ClosureHandlerSelector, forControlEvents: .AllEvents)
        if var handlers = self.handlers {
            handlers.remove(handler)
            self.handlers = handlers
        }
    }
}

private var HandlerKey: UInt8 = 0

private extension UIControl {

    private var handlers: Set<ClosureHandler<UIControl>>? {
        get { return objc_getAssociatedObject(self, &HandlerKey) as? Set<ClosureHandler<UIControl>> }
        set { objc_setAssociatedObject(self, &HandlerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
    }
}


//
//  TabBarViewController.swift
//  Shari-Demo
//
//  Created by nakajijapan on 2016/10/19.
//  Copyright © 2016年 nakajijapan. All rights reserved.
//

import UIKit
import Shari

class TabBarViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    @IBAction func buttonDidTap(button: UIButton) {

        guard let modalNavigationController = storyboard!.instantiateViewController(withIdentifier: "ModalNavigationController") as? ShariNavigationController else {
            fatalError("Need the ShariNavigationController")
        }

        // Transition Setting
        //ShariSettings.shouldTransformScaleDown = false
        //ShariSettings.backgroundColorOfOverlayView = UIColor.red

        modalNavigationController.parentTabBarController = tabBarController
        tabBarController?.si.present(modalNavigationController)
    }
}

Add more cornerRadius in the viewController that was open via TabBar

//
//  TabBarViewController.swift
//  Shari-Demo
//
//  Created by nakajijapan on 2016/10/19.
//  Copyright © 2016年 nakajijapan. All rights reserved.
//

import UIKit
import Shari

class TabBarViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    @IBAction func buttonDidTap(button: UIButton) {

        guard let modalNavigationController = storyboard!.instantiateViewController(withIdentifier: "ModalNavigationController") as? ShariNavigationController else {
            fatalError("Need the ShariNavigationController")
        }

        // Transition Setting
        //ShariSettings.shouldTransformScaleDown = false
        //ShariSettings.backgroundColorOfOverlayView = UIColor.red

        modalNavigationController.parentTabBarController = tabBarController
        modalNavigationController.cornerRadius = 8
        tabBarController?.si.present(modalNavigationController)
    }
}


import Foundation

public typealias Id = UUID
public typealias Date = Foundation.Date

public struct ToDos {
    public static let initial = ToDos.init(todos: [])

    public enum Box {
        case inbox
        case today
        case later
    }

    internal struct ToDoInBox {
        let todo: ToDo
        let box: Box
    }

    internal let todos: [ToDoInBox]
}

extension ToDos {
    public var inbox: [ToDo] {
        return todos
            .filter { $0.box == .inbox }
            .map { $0.todo }
    }
    public var today: [ToDo] {
        return todos
            .filter { $0.box == .today }
            .map { $0.todo }
    }
    public var later: [ToDo] {
        return todos
            .filter { $0.box == .later }
            .map { $0.todo }
    }

    public var schedueld: [ToDo] {
        return todos
            .filter { $0.todo.due != nil }
            .map { $0.todo }
    }

    public var all: [ToDo] {
        return todos.map { $0.todo }
    }
}

public struct Tag {
    public let name: String
}

Add `done` to ToDos as a computed var

import Foundation

public typealias Id = UUID
public typealias Date = Foundation.Date

public struct ToDos {
    public static let initial = ToDos.init(todos: [])

    public enum Box {
        case inbox
        case today
        case later
    }

    internal struct ToDoInBox {
        let todo: ToDo
        let box: Box
    }

    internal let todos: [ToDoInBox]
}

extension ToDos {
    public var inbox: [ToDo] {
        return todos
            .filter { $0.box == .inbox }
            .map { $0.todo }
    }
    public var today: [ToDo] {
        return todos
            .filter { $0.box == .today }
            .map { $0.todo }
    }
    public var later: [ToDo] {
        return todos
            .filter { $0.box == .later }
            .map { $0.todo }
    }

    public var all: [ToDo] {
        return todos.map { $0.todo }
    }
    public var done: [ToDo] {
        return all.filter { $0.done }
    }
    public var schedueld: [ToDo] {
        return all.filter { $0.due != nil }
    }
}

public struct Tag {
    public let name: String
}


//
//  Copyright © 2017 SwiftCoders. All rights reserved.
//

import XCTest

class UITestCase: XCTestCase {

    private static let sharedApp: XCUIApplication = .init()

    var app: XCUIApplication { return UITestCase.sharedApp }

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

    func assertAppIsDisplayingAllItems() {

        let element = app.navigationBars["All Items"]
        assertApp(isDisplaying: element)
    }

    func assertAppIsDisplayingAddItemCell() {
        let element = XCUIApplication().cells.staticTexts["Add Item"]
        assertApp(isDisplaying: element)
    }
}

public final class UITestHelper {
    public static func debugPerform(resetAction: ResetAction, application: XCUIApplication) {
        application.navigationBars["All Items"].buttons["debug"].tap()
        application.sheets["DEBUG"].buttons[resetAction.rawValue].tap()
    }
    public enum ResetAction {
        case data
        case userDefaults
        case dataAndUserDefaults
        case cancel

        var rawValue: String {
            switch self {
            case .data:
                return Globals.UITestingResetAction.data
            case .userDefaults:
                return Globals.UITestingResetAction.defaults
            case .dataAndUserDefaults:
                return Globals.UITestingResetAction.dataAndDefaults
            case .cancel:
                return Globals.UITestingResetAction.cancel
            }
        }
    }
}

Change string Debug to Reset in UITestHelper

//
//  Copyright © 2017 SwiftCoders. All rights reserved.
//

import XCTest

class UITestCase: XCTestCase {

    private static let sharedApp: XCUIApplication = .init()

    var app: XCUIApplication { return UITestCase.sharedApp }

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

    func assertAppIsDisplayingAllItems() {

        let element = app.navigationBars["All Items"]
        assertApp(isDisplaying: element)
    }

    func assertAppIsDisplayingAddItemCell() {
        let element = XCUIApplication().cells.staticTexts["Add Item"]
        assertApp(isDisplaying: element)
    }
}

public final class UITestHelper {
    public static func debugPerform(resetAction: ResetAction, application: XCUIApplication) {
        application.navigationBars["All Items"].buttons["debug"].tap()
        application.sheets["RESET"].buttons[resetAction.rawValue].tap()
    }
    public enum ResetAction {
        case data
        case userDefaults
        case dataAndUserDefaults
        case cancel

        var rawValue: String {
            switch self {
            case .data:
                return Globals.UITestingResetAction.data
            case .userDefaults:
                return Globals.UITestingResetAction.defaults
            case .dataAndUserDefaults:
                return Globals.UITestingResetAction.dataAndDefaults
            case .cancel:
                return Globals.UITestingResetAction.cancel
            }
        }
    }
}


/*
 |  _   ____   ____   _
 | | |‾|  ⚈ |-| ⚈  |‾| |
 | | |  ‾‾‾‾| |‾‾‾‾  | |
 |  ‾        ‾        ‾
 */

import Foundation
import Reactor
import CloudKit

public struct UpdateCloudKitBadge<U: State>: Command {

    public var badgeCount: Int

    public init(to count: Int) {
        badgeCount = count
    }

    public func execute(state: U, core: Core<U>) {
        let operation = CKModifyBadgeOperation(badgeValue: badgeCount)
        operation.modifyBadgeCompletionBlock = { error in
            if let error = error {
                core.fire(event: CloudKitBadgeError(error: error))
            } else {
                core.fire(event: CloudKitBadgeUpdated(badgeCount: self.badgeCount))
            }
        }
        operation.qualityOfService = .userInitiated
        CKContainer.default().add(operation)
    }

}

Add completion to update badge command

/*
 |  _   ____   ____   _
 | | |‾|  ⚈ |-| ⚈  |‾| |
 | | |  ‾‾‾‾| |‾‾‾‾  | |
 |  ‾        ‾        ‾
 */

import Foundation
import Reactor
import CloudKit

public struct UpdateCloudKitBadge<U: State>: Command {

    let badgeCount: Int
    let completion: () -> Void

    public init(to count: Int, completion: @escaping (() -> Void) = { }) {
        badgeCount = count
        self.completion = completion
    }

    public func execute(state: U, core: Core<U>) {
        let operation = CKModifyBadgeOperation(badgeValue: badgeCount)
        operation.modifyBadgeCompletionBlock = { error in
            if let error = error {
                core.fire(event: CloudKitBadgeError(error: error))
            } else {
                core.fire(event: CloudKitBadgeUpdated(badgeCount: self.badgeCount))
            }
            self.completion()
        }
        operation.qualityOfService = .userInitiated
        CKContainer.default().add(operation)
    }

}


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

/// A type that can represent either failure with an error or success with a result value.
public protocol ResultType {
	typealias Value
	typealias Error: ErrorType

	/// Constructs a successful result wrapping a `value`.
	init(value: Value)

	/// Constructs a failed result wrapping an `error`.
	init(error: Error)

	/// Case analysis for ResultType.
	///
	/// Returns the value produced by appliying `ifFailure` to the error if self represents a failure, or `ifSuccess` to the result value if self represents a success.
	func analysis<U>(@noescape ifSuccess ifSuccess: Value -> U, @noescape ifFailure: Error -> U) -> U
}

public extension ResultType {

	/// Returns the value if self represents a success, `nil` otherwise.
	public var value: Value? {
		return analysis(ifSuccess: { $0 }, ifFailure: { _ in nil })
	}

	/// Returns the error if self represents a failure, `nil` otherwise.
	public var error: Error? {
		return analysis(ifSuccess: { _ in nil }, ifFailure: { $0 })
	}
}

Declare value/error in the protocol.

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

/// A type that can represent either failure with an error or success with a result value.
public protocol ResultType {
	typealias Value
	typealias Error: ErrorType

	/// Constructs a successful result wrapping a `value`.
	init(value: Value)

	/// Constructs a failed result wrapping an `error`.
	init(error: Error)

	/// Case analysis for ResultType.
	///
	/// Returns the value produced by appliying `ifFailure` to the error if self represents a failure, or `ifSuccess` to the result value if self represents a success.
	func analysis<U>(@noescape ifSuccess ifSuccess: Value -> U, @noescape ifFailure: Error -> U) -> U

	/// Returns the value if self represents a success, `nil` otherwise.
	///
	/// A default implementation is provided by a protocol extension. Conforming types may specialize it.
	var value: Value? { get }

	/// Returns the error if self represents a failure, `nil` otherwise.
	///
	/// A default implementation is provided by a protocol extension. Conforming types may specialize it.
	var error: Error? { get }
}

public extension ResultType {

	/// Returns the value if self represents a success, `nil` otherwise.
	public var value: Value? {
		return analysis(ifSuccess: { $0 }, ifFailure: { _ in nil })
	}

	/// Returns the error if self represents a failure, `nil` otherwise.
	public var error: Error? {
		return analysis(ifSuccess: { _ in nil }, ifFailure: { $0 })
	}
}


//
//  Print.swift
//  SwiftShell
//
//  Created by Justin Jia on 7/5/16.
//  Copyright © 2016 SwiftShell. All rights reserved.
//

import Foundation

func print(command: String, with arguments: [String]? = nil) {
    var output = "SwiftShell $ \(command)"
    if let arguments = arguments {
        output += arguments.reduce("", combine: { $0 + " " + $1 })
    }
    print(output)
}

Update to Swift 3 beta 4 syntax

//
//  Print.swift
//  SwiftShell
//
//  Created by Justin Jia on 7/5/16.
//  Copyright © 2016 SwiftShell. All rights reserved.
//

import Foundation

func print(command: String, with arguments: [String]? = nil) {
    var output = "SwiftShell $ \(command)"
    if let arguments = arguments {
        output += arguments.reduce("", { $0 + " " + $1 })
    }
    print(output)
}


//
//  Box.swift
//  swiftz_core
//
//  Created by Andrew Cobb on 6/9/14.
//  Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//

/// An immutable box, necessary for recursive datatypes (such as List) to avoid compiler crashes
public final class Box<T> {
	private let _value : () -> T

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

	public var value: T {
		return _value()
	}

	public func map<U>(f: T -> U) -> Box<U> {
		return Box<U>(f(value)) // TODO: file rdar, type inf fails without <U>
	}
}

public func <^><T, U>(f: T -> U, x: Box<T>) -> Box<U> {
	return x.map(f)
}

extension Box: Printable {
    public var description: String {
        return "Box(\(toString(value)))"
    }
}

Use tabs instead of spaces