//
//  Discover utility for bonjour/zeroconf
//
//  Copyright © 2015 Michael Weibel. All rights reserved.
//  License: MIT
//

import Foundation

class Discover : NSObject, NSNetServiceBrowserDelegate, NSNetServiceDelegate {
    var afpBrowser : NSNetServiceBrowser
    var connection : Connection?
    var netService: NSNetService?

    static let sharedInstance = Discover.init()

    override init() {
        self.afpBrowser = NSNetServiceBrowser()
        self.afpBrowser.includesPeerToPeer = true

        super.init()

        self.afpBrowser.delegate = self
    }

    func netServiceBrowser(aNetServiceBrowser: NSNetServiceBrowser, didFindService aNetService: NSNetService, moreComing: Bool) {
        if !moreComing {
            self.connection = Connection.init(netService: aNetService)
            self.netService = aNetService
            aNetService.delegate = self.connection
            aNetService.startMonitoring()
            aNetService.resolveWithTimeout(NSTimeInterval.init(100))
        }
    }

    func startSearch() {
        afpBrowser.searchForServicesOfType("_esrhttp._tcp.", inDomain: "local.")
    }

    func stop() {
        afpBrowser.stop()
    }
}

Fix discovery of desktop app

//
//  Discover utility for bonjour/zeroconf
//
//  Copyright © 2015 Michael Weibel. All rights reserved.
//  License: MIT
//

import Foundation

class Discover : NSObject, NSNetServiceBrowserDelegate, NSNetServiceDelegate {
    var afpBrowser : NSNetServiceBrowser
    var connection : Connection?
    var netService: NSNetService?
    var searching : Bool = false

    static let sharedInstance = Discover.init()

    override init() {
        self.afpBrowser = NSNetServiceBrowser()
        self.afpBrowser.includesPeerToPeer = true

        super.init()

        self.afpBrowser.delegate = self
    }

    func netServiceBrowser(aNetServiceBrowser: NSNetServiceBrowser, didFindService aNetService: NSNetService, moreComing: Bool) {
        if !moreComing {
            self.connection = Connection.init(netService: aNetService)
            self.netService = aNetService
            aNetService.delegate = self.connection
            aNetService.startMonitoring()
            aNetService.resolveWithTimeout(NSTimeInterval.init(100))
        }
    }

    func startSearch() {
        if !searching {
            afpBrowser.searchForServicesOfType("_esrhttp._tcp.", inDomain: "local.")
            searching = true
        }
    }

    func stop() {
        afpBrowser.stop()
        searching = false
    }
}


//
//  Errors.swift
//  SwiftDataStore
//
//  Created by Ahmed Onawale on 2/5/17.
//  Copyright © 2017 Ahmed Onawale. All rights reserved.
//

struct ModelError: Error {

}

public enum NetworkError: Error {
    case noInternetConnection
    case badResponse
    case other(String)
}

extension NetworkError: LocalizedError {
    public var errorDescription: String? {
        switch self {
        case .noInternetConnection:
            return "No Internet connection"
        case .badResponse:
            return "Bad response"
        case .other(let message):
            return message
        }
    }
}

public enum SerializerError: Error {
    case requireID
    case invalidJSON
}

extension SerializerError: LocalizedError {
    public var errorDescription: String? {
        switch self {
        case .requireID:
            return "Requires id"
        case .invalidJSON:
            return "Invalid JSON"
        }
    }
}

Remove ModelError. Redefine AdapterError cases.

//
//  Errors.swift
//  SwiftDataStore
//
//  Created by Ahmed Onawale on 2/5/17.
//  Copyright © 2017 Ahmed Onawale. All rights reserved.
//

public enum AdapterError: Int, Error {
    case unauthorized = 401
    case forbidden = 403
    case notFound = 404
    case timeout = 408
    case conflict = 409
    case invalid = 422
    case server = 500

    case abort
    case badResponse
    case unknown

    init(_ code: Int) {
        if let error = AdapterError(rawValue: code) {
            self = error
        } else {
            self = .unknown
        }
    }
}

public enum SerializerError: Error {
    case requiresID
    case invalidJSON
}

extension SerializerError: LocalizedError {
    public var errorDescription: String? {
        switch self {
        case .requiresID:
            return "Requires id"
        case .invalidJSON:
            return "Invalid JSON"
        }
    }
}


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

final class BinaryTreeTests: XCTestCase {
	func testEmptyTreesAreNotLeaves() {
		XCTAssertFalse(BinaryTree<Int>().isLeaf)
	}

	func testLeavesAreLeaves() {
		XCTAssert(BinaryTree(0).isLeaf)
	}

	func testLeavesAreNonEmpty() {
		XCTAssertFalse(BinaryTree(0).isEmpty)
	}

	func testLeavesAreNotBranches() {
		XCTAssertFalse(BinaryTree(0).isBranch)
	}
}

import BinaryTree
import XCTest

Test that empty trees are empty.

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

final class BinaryTreeTests: XCTestCase {
	func testEmptyTreesAreEmpty() {
		XCTAssert(BinaryTree<Int>().isEmpty)
	}

	func testEmptyTreesAreNotLeaves() {
		XCTAssertFalse(BinaryTree<Int>().isLeaf)
	}

	func testLeavesAreLeaves() {
		XCTAssert(BinaryTree(0).isLeaf)
	}

	func testLeavesAreNonEmpty() {
		XCTAssertFalse(BinaryTree(0).isEmpty)
	}

	func testLeavesAreNotBranches() {
		XCTAssertFalse(BinaryTree(0).isBranch)
	}
}

import BinaryTree
import XCTest


//
//  UserAgent.swift
//  RSWeb
//
//  Created by Brent Simmons on 8/27/16.
//  Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//

import Foundation

public struct UserAgent {

	public static func fromInfoPlist() -> String? {

		guard let userAgentName = Bundle.main.object(forInfoDictionaryKey: "UserAgent") else {
			return nil
		}
		guard let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") else {
			return nil
		}
		return "\(userAgentName) \(version)"
	}

	public static func headers() -> [AnyHashable: String]? {

		guard let userAgent = fromInfoPlist() else {
			return nil
		}

		return [HTTPRequestHeader.userAgent: userAgent]
	}
}

Add the OS to the User-Agent header, as in Macintosh or iOS.

//
//  UserAgent.swift
//  RSWeb
//
//  Created by Brent Simmons on 8/27/16.
//  Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//

import Foundation

public struct UserAgent {

	public static func fromInfoPlist() -> String? {

		guard let userAgentName = Bundle.main.object(forInfoDictionaryKey: "UserAgent") else {
			return nil
		}
		guard let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") else {
			return nil
		}

		#if os(macOS)
			let osString = "Macintosh"
		#elseif os(iOS)
			let osString = "iOS"
		#endif

		return "\(userAgentName)/\(version) (\(osString))"
	}

	public static func headers() -> [AnyHashable: String]? {

		guard let userAgent = fromInfoPlist() else {
			return nil
		}

		return [HTTPRequestHeader.userAgent: userAgent]
	}
}


//
//  WhatsNewViewController.swift
//  SparkMap
//
//  Created by Edvard Holst on 13/06/16.
//  Copyright © 2016 Zygote Labs. All rights reserved.
//

import UIKit

class WhatsNewViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

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

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

Set WhatsNew view controller title.

//
//  WhatsNewViewController.swift
//  SparkMap
//
//  Created by Edvard Holst on 13/06/16.
//  Copyright © 2016 Zygote Labs. All rights reserved.
//

import UIKit

class WhatsNewViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let whatsNewTitleString = NSLocalizedString("Whats New", comment: "Whats New View Title")
        self.title = whatsNewTitleString
        // Do any additional setup after loading the view.
    }

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

}


/**
 * Question Link: https://leetcode.com/problems/minimum-window-substring/
 * Primary idea: Use dictionary and int to verify if contain all characters, and update
 *               startIndex and miniWindow as well
 *
 * Time Complexity: O(n^2), Space Complexity: O(n)
 *
 */

class MinimumWindowSubstring {

    func minWindow(_ s: String, _ t: String) -> String {
        var tFreqs = Dictionary(t.map { ($0, 1) }, uniquingKeysWith: +), count = 0
        var sChars = Array(s), res = "", start = 0

        for (i, sChar) in sChars.enumerated() {
            guard let freq = tFreqs[sChar] else {
                continue
            }

            tFreqs[sChar] = freq - 1

            if freq > 0 {
                count += 1
            }

            while count == t.count {
                // jump over redundants
                guard let startFreq = tFreqs[sChars[start]] else {
                    start += 1
                    continue
                }

                tFreqs[sChars[start]] = startFreq + 1

                if startFreq == 0 {
                    // update res
                    if res.isEmpty || res.count > i - start + 1 {
                        res = String(sChars[start...i])
                    }

                    count -= 1
                }

                start += 1

            }
        }

        return res
    }
}

Update the solution to Minimum Window Substring

/**
 * Question Link: https://leetcode.com/problems/minimum-window-substring/
 * Primary idea: Use dictionary and int to verify if contain all characters, and update
 *               startIndex and miniWindow as well
 *
 * Time Complexity: O(n^2), Space Complexity: O(n)
 *
 */

class MinimumWindowSubstring {

    func minWindow(_ s: String, _ t: String) -> String {
        let sChars = Array(s), tChars = Array(t)
        var tFreq = Dictionary(tChars.map { ($0, 1) }, uniquingKeysWith: +)
        var left = 0, shortestLen = Int.max, start = 0, matters = 0

        for (i, sChar) in sChars.enumerated() {
            guard let sCharFreq = tFreq[sChar] else {
                continue
            }

            tFreq[sChar] = sCharFreq - 1

            if sCharFreq > 0 {
                matters += 1
            }

            while matters == tChars.count {
                guard let leftFreq = tFreq[sChars[left]] else {
                    left += 1
                    continue
                }

                if leftFreq == 0 {
                    matters -= 1

                    if i - left + 1 < shortestLen {
                        shortestLen = i - left + 1
                        start = left
                    }

                }

                tFreq[sChars[left]] = leftFreq + 1
                left += 1
            }
        }

        return shortestLen == Int.max ? "" : String(sChars[start..<start + shortestLen])
    }
}


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

import PackageDescription

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

Drop Swift 3 support from Swift PM

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

import PackageDescription

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


// swift-tools-version:3.1

import Foundation
import PackageDescription

var dependencies: [Package.Dependency] = [
  .Package(url: "https://github.com/ReactiveX/RxSwift.git", majorVersion: 3),
]

let isTest = ProcessInfo.processInfo.environment["TEST"] == "1"
if isTest {
  dependencies.append(
    .Package(url: "https://github.com/devxoul/RxExpect.git", majorVersion: 0, minor: 5)
  )
}

let package = Package(
  name: "ReactorKit",
  dependencies: dependencies
)

Use latest version to RxExpect

// swift-tools-version:3.1

import Foundation
import PackageDescription

var dependencies: [Package.Dependency] = [
  .Package(url: "https://github.com/ReactiveX/RxSwift.git", majorVersion: 3),
]

let isTest = ProcessInfo.processInfo.environment["TEST"] == "1"
if isTest {
  dependencies.append(
    .Package(url: "https://github.com/devxoul/RxExpect.git", majorVersion: 0)
  )
}

let package = Package(
  name: "ReactorKit",
  dependencies: dependencies
)


#!/usr/bin/swift
import Foundation
struct Command {
    var file: String
    var cmd: String
    var args: [String]
}

let commands = [
    Command(file: "Procfile.rob", cmd: "foreman", args:["foreman", "start", "-f", "Procfile.rob"]),
    Command(file: "Procfile", cmd: "foreman", args:["foreman", "start"]),
    Command(file: "bin/rails", cmd: "bin/rails", args:["rails", "s"]),
    Command(file: "ember", cmd: "ember", args:["ember", "serve"]),
    Command(file: ".", cmd: "/bin/ls", args: ["ls", "-l"]) // . will always exist in a files system so this gives a safe terminator.
]

func lookupCommand() -> Command {
    let fileManager = FileManager()
    let command = commands.first(where: { fileManager.fileExists(atPath: $0.file) })
    return command!
}

func exec(cmd: Command) {
    // Array of UnsafeMutablePointer<Int8>
    let cargs = cmd.args.map { strdup($0) } + [nil]
    execvp(cmd.cmd, cargs)
}

let command = lookupCommand()
exec(cmd: command)
print("failed to exec command")

Use NSUserName not hardcoded user name.

#!/usr/bin/swift
import Foundation
struct Command {
    var file: String
    var cmd: String
    var args: [String]
}

let commands = [
    Command(file: "Procfile.rob", cmd: "foreman", args:["foreman", "start", "-f", "Procfile.\(NSUserName())"]),
    Command(file: "Procfile", cmd: "foreman", args:["foreman", "start"]),
    Command(file: "bin/rails", cmd: "bin/rails", args:["rails", "s"]),
    Command(file: "ember", cmd: "ember", args:["ember", "serve"]),
    Command(file: ".", cmd: "/bin/ls", args: ["ls", "-l"]) // . will always exist in a files system so this gives a safe terminator.
]

func lookupCommand() -> Command {
    let fileManager = FileManager()
    let command = commands.first(where: { fileManager.fileExists(atPath: $0.file) })
    return command!
}

func exec(cmd: Command) {
    // Array of UnsafeMutablePointer<Int8>
    let cargs = cmd.args.map { strdup($0) } + [nil]
    execvp(cmd.cmd, cargs)
}

let command = lookupCommand()
exec(cmd: command)
print("failed to exec command")


//
//  Rx.swift
//  Rx
//
//  Created by Krunoslav Zaher on 2/14/15.
//  Copyright © 2015 Krunoslav Zaher. All rights reserved.
//

import Foundation

#if TRACE_RESOURCES
/// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development.
public var resourceCount: AtomicInt = 0
#endif

/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass.
func abstractMethod() -> Swift.Never {
    rxFatalError("Abstract method")
}

func rxFatalError(_ lastMessage: String) -> Swift.Never  {
    // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
    fatalError(lastMessage)
}

func incrementChecked(_ i: inout Int) throws -> Int {
    if i == Int.max {
        throw RxError.overflow
    }
    let result = i
    i += 1
    return result
}

func decrementChecked(_ i: inout Int) throws -> Int {
    if i == Int.min {
        throw RxError.overflow
    }
    let result = i
    i -= 1
    return result
}

Use instead of intermediate variable for increment/decrement and return.

//
//  Rx.swift
//  Rx
//
//  Created by Krunoslav Zaher on 2/14/15.
//  Copyright © 2015 Krunoslav Zaher. All rights reserved.
//

import Foundation

#if TRACE_RESOURCES
/// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development.
public var resourceCount: AtomicInt = 0
#endif

/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass.
func abstractMethod() -> Swift.Never {
    rxFatalError("Abstract method")
}

func rxFatalError(_ lastMessage: String) -> Swift.Never  {
    // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
    fatalError(lastMessage)
}

func incrementChecked(_ i: inout Int) throws -> Int {
    if i == Int.max {
        throw RxError.overflow
    }
    defer { i += 1 }
    return i
}

func decrementChecked(_ i: inout Int) throws -> Int {
    if i == Int.min {
        throw RxError.overflow
    }
    defer { i -= 1 }
    return i
}


//
//  MessageTableViewCell.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 25/07/2017.
//  Copyright © 2017 Eurofurence. All rights reserved.
//

import UIKit

class MessageTableViewCell: UITableViewCell {

    static var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.doesRelativeDateFormatting = true
        formatter.dateStyle = .short
        formatter.timeStyle = .short

        return formatter
    }()

    @IBOutlet weak var messageAuthorLabel: UILabel!
    @IBOutlet weak var messageSubjectLabel: UILabel!
    @IBOutlet weak var messageReceivedDateLabel: UILabel!
    @IBOutlet weak var messageSynopsisLabel: UILabel!
    @IBOutlet weak var unreadMessageIndicator: UnreadMessageIndicator!
    private var presentedMessage: Message?

    override func prepareForReuse() {
        super.prepareForReuse()

        accessibilityLabel = nil
        messageAuthorLabel.text = nil
        messageSubjectLabel.text = nil
        messageReceivedDateLabel.text = nil
        messageSynopsisLabel.text = nil
    }

    func show(message: Message) {
        let receivedDateString = MessageTableViewCell.dateFormatter.string(from: message.receivedDateTime)
        messageAuthorLabel.text = message.authorName
        messageSubjectLabel.text = message.subject
        messageReceivedDateLabel.text = receivedDateString
        messageSynopsisLabel.text = message.contents
        unreadMessageIndicator.isHidden = message.isRead

        accessibilityLabel = "Message from \(message.authorName), \"\(message.subject)\". Received \(receivedDateString)."
    }

}

Improve pronounciation of message dates through Voiceover

//
//  MessageTableViewCell.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 25/07/2017.
//  Copyright © 2017 Eurofurence. All rights reserved.
//

import UIKit

class MessageTableViewCell: UITableViewCell {

    private static var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.doesRelativeDateFormatting = true
        formatter.dateStyle = .medium
        formatter.timeStyle = .short

        return formatter
    }()

    @IBOutlet weak var messageAuthorLabel: UILabel!
    @IBOutlet weak var messageSubjectLabel: UILabel!
    @IBOutlet weak var messageReceivedDateLabel: UILabel!
    @IBOutlet weak var messageSynopsisLabel: UILabel!
    @IBOutlet weak var unreadMessageIndicator: UnreadMessageIndicator!
    private var presentedMessage: Message?

    override func prepareForReuse() {
        super.prepareForReuse()

        accessibilityLabel = nil
        messageAuthorLabel.text = nil
        messageSubjectLabel.text = nil
        messageReceivedDateLabel.text = nil
        messageSynopsisLabel.text = nil
    }

    func show(message: Message) {
        let receivedDateString = MessageTableViewCell.dateFormatter.string(from: message.receivedDateTime)
        messageAuthorLabel.text = message.authorName
        messageSubjectLabel.text = message.subject
        messageReceivedDateLabel.text = receivedDateString
        messageSynopsisLabel.text = message.contents
        unreadMessageIndicator.isHidden = message.isRead

        accessibilityLabel = "Message from \(message.authorName), \"\(message.subject)\". Received \(receivedDateString))."
    }

}


// Run test ASTSection.swift, with separate compile and link steps.

// RUN: rm -rf %t
// RUN: mkdir %t

// RUN: %target-swift-frontend -c -sdk /fake/sdk/path -Xcc -DA -Xcc -DB -emit-module -o %t %S/ASTSection.swift
// RUN: %swift-ide-test -test-CompilerInvocation-from-module -source-filename=%t/ASTSection.swiftmodule

// Test the inline section mechanism.
// RUN: %target-swiftc_driver %t/ASTSection.o -Xlinker -sectcreate -Xlinker __SWIFT -Xlinker __ast -Xlinker %t/ASTSection.swiftmodule -o %t/ASTSection.dylib
// RUN: %lldb-moduleimport-test %t/ASTSection.dylib | FileCheck %s

// Test the symbol table entry.
// RUN: %target-swiftc_driver %t/ASTSection.o -Xlinker -add_ast_path -Xlinker %t/ASTSection.swiftmodule -o %t/ASTSection.dylib
// RUN: %lldb-moduleimport-test %t/ASTSection.dylib | FileCheck %s

// REQUIRES: OS=macosx
// REQUIRES: ld-add_ast_path

// CHECK: Loaded module ASTSection from
// CHECK: - Target: {{.+}}-{{.+}}-{{.+}}
// CHECK: - SDK path: /fake/sdk/path{{$}}
// CHECK: - -Xcc options: -DA -DB
// CHECK: Importing ASTSection... ok!

Revert "tests: use a %target-* substitution instead of calling 'ld' directly"

// Run test ASTSection.swift, with separate compile and link steps.

// RUN: rm -rf %t
// RUN: mkdir %t

// RUN: %target-swift-frontend -c -sdk /fake/sdk/path -Xcc -DA -Xcc -DB -emit-module -o %t %S/ASTSection.swift
// RUN: %swift-ide-test -test-CompilerInvocation-from-module -source-filename=%t/ASTSection.swiftmodule

// Test the inline section mechanism.
// RUN: ld %t/ASTSection.o -sectcreate __SWIFT __ast %t/ASTSection.swiftmodule -o %t/ASTSection.dylib -L%platform-module-dir -dylib -lSystem
// RUN: %lldb-moduleimport-test %t/ASTSection.dylib | FileCheck %s

// Test the symbol table entry.
// RUN: ld %t/ASTSection.o -add_ast_path %t/ASTSection.swiftmodule -o %t/ASTSection.dylib -L%platform-module-dir -dylib -lSystem
// RUN: %lldb-moduleimport-test %t/ASTSection.dylib | FileCheck %s

// REQUIRES: OS=macosx
// REQUIRES: ld-add_ast_path

// CHECK: Loaded module ASTSection from
// CHECK: - Target: {{.+}}-{{.+}}-{{.+}}
// CHECK: - SDK path: /fake/sdk/path{{$}}
// CHECK: - -Xcc options: -DA -DB
// CHECK: Importing ASTSection... ok!


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

import PackageDescription

let package = Package(
    name: "MarqueeLabel",
    platforms: [
        .iOS(.v9),
        .tvOS(.v9)
    ],
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "MarqueeLabel",
            targets: ["MarqueeLabel"]),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "MarqueeLabel",
	    path: "Sources")
    ],
    swiftLanguageVersions: [.v5]
)

Exclude random project files from SPM.

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

import PackageDescription

let package = Package(
    name: "MarqueeLabel",
    platforms: [
        .iOS(.v9),
        .tvOS(.v9)
    ],
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "MarqueeLabel",
            targets: ["MarqueeLabel"]),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "MarqueeLabel",
	          path: "Sources",
            exclude: ["Carthage", "Extras", "MarqueeLabel", "MarqueeLabelTV", "Metadata", "CHANGELOG.md", "MarqueeLabel.podpsec"])
    ],
    swiftLanguageVersions: [.v5]
)


// swift-tools-version:5.2

import PackageDescription

let package = Package(
    name: "website publisher",
    products: [
        .executable(name: "WebsitePublisher", targets: ["WebsitePublisher"]),
    ],
    dependencies: [
        .package(url: "https://github.com/johnsundell/publish.git", from: "0.1.0"),
    ],
    targets: [
        .target(
            name: "WebsitePublisher",
            dependencies: ["Publish"]),
    ]
)

Make Publish dependency name explicit

// swift-tools-version:5.2

import PackageDescription

let package = Package(
    name: "website publisher",
    products: [
        .executable(name: "WebsitePublisher", targets: ["WebsitePublisher"]),
    ],
    dependencies: [
        .package(name: "Publish", url: "https://github.com/johnsundell/publish.git", from: "0.1.0"),
    ],
    targets: [
        .target(
            name: "WebsitePublisher",
            dependencies: ["Publish"]),
    ]
)


// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "APIKit",
    platforms: [
        .macOS(.v10_10), .iOS(.v8), .tvOS(.v9), .watchOS(.v2)
    ],
    products: [
        .library(name: "APIKit", targets: ["APIKit"]),
    ],
    dependencies: [],
    targets: [
        .target(
            name: "APIKit",
            dependencies: [],
            exclude: ["BodyParameters/AbstractInputStream.m"]
        ),
         .testTarget(
            name: "APIKitTests",
            dependencies: ["APIKit"]
        ),
    ],
    swiftLanguageVersions: [.v5]
)

Change iOS deployment target for Xcode 12

// swift-tools-version:5.0
import PackageDescription

var platforms: [SupportedPlatform] {
    #if compiler(<5.3)
        return [
            .macOS(.v10_10), .iOS(.v8), .tvOS(.v9), .watchOS(.v2)
        ]
    #else
        // Xcode 12 (which ships with Swift 5.3) drops support for iOS 8
        return [
            .macOS(.v10_10), .iOS(.v9), .tvOS(.v9), .watchOS(.v2)
        ]
    #endif
}

let package = Package(
    name: "APIKit",
    platforms: platforms,
    products: [
        .library(name: "APIKit", targets: ["APIKit"]),
    ],
    dependencies: [],
    targets: [
        .target(
            name: "APIKit",
            dependencies: [],
            exclude: ["BodyParameters/AbstractInputStream.m"]
        ),
         .testTarget(
            name: "APIKitTests",
            dependencies: ["APIKit"]
        ),
    ],
    swiftLanguageVersions: [.v5]
)


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

public enum Constraint {
	public init(_ c1: Constraint, and c2: Constraint) {
		self = And(Box(c1), Box(c2))
	}

	public init(exists: Variable, inConstraint: Constraint) {
		self = Existential(exists, Box(inConstraint))
	}

	public init(_ t1: Type, equals t2: Type) {
		self = Congruence(t1, t2)
	}

	case And(Box<Constraint>, Box<Constraint>)
	case Existential(Variable, Box<Constraint>)
	case Congruence(Type, Type)
}

// MARK: - Imports

import Box

Remove all but Equality constraints.

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

public enum Constraint {
	case Equality(Type, Type)
}


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

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

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

final class B: A<String> {

}

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

}

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

}

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

Fix typo: filtring → filtering

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

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

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

final class B: A<String> {

}

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

}

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

}

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


//
//  ArticleListCoordinator.swift
//  Artikolo
//
//  Created by Grant Butler on 4/30/17.
//  Copyright © 2017 Grant Butler. All rights reserved.
//

import Foundation

class ArticleListCoordinator: Coordinator {

    override func start() {
        let dataManager: DataManager = try! container.resolve()

        let viewController = ArticleTableViewController(urls: dataManager.urls)
        navigationController.pushViewController(viewController, animated: false)
    }

}

Add basic UI for adding a URL to the application.

//
//  ArticleListCoordinator.swift
//  Artikolo
//
//  Created by Grant Butler on 4/30/17.
//  Copyright © 2017 Grant Butler. All rights reserved.
//

import UIKit

class ArticleListCoordinator: Coordinator {

    override func start() {
        let dataManager: DataManager = try! container.resolve()

        let viewController = ArticleTableViewController(urls: dataManager.urls)

        viewController.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ArticleListCoordinator.askForURL))

        navigationController.pushViewController(viewController, animated: false)
    }

    @objc
    func askForURL() {
        let alertController = UIAlertController(title: "Add URL", message: nil, preferredStyle: .alert)
        alertController.addTextField { (textField) in
            textField.placeholder = "https://"
            textField.keyboardType = .URL
        }
        alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        alertController.addAction(UIAlertAction(title: "Add", style: .default, handler: { [weak alertController] (action) in
            guard let textField = alertController?.textFields?.first else { return }
            guard let urlString = textField.text else { return }
            guard let url = URL(string: urlString) else { return }

            let dataManager: DataManager = try! self.container.resolve()
            dataManager.save(url: url)
        }))

        navigationController.present(alertController, animated: true, completion: nil)
    }

}


import XCTest
import PenguinParallel

final class ZipPipelineIteratorTests: XCTestCase {

    func testZipAndMapTwoArrays() {
        let arr = [0, 1, 2, 3, 4]
        var tmp = PipelineIterator.zip(arr.makePipelineIterator(), arr.makePipelineIterator().map { $0 + 1 })
        var itr = tmp.map { $0.0 + $0.1 }
        XCTAssertEqual(1, try! itr.next())
        XCTAssertEqual(3, try! itr.next())
        XCTAssertEqual(5, try! itr.next())
        XCTAssertEqual(7, try! itr.next())
        XCTAssertEqual(9, try! itr.next())
        XCTAssertEqual(nil, try! itr.next())
    }

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

Add test to verify correct early termination behavior.

import XCTest
import PenguinParallel

final class ZipPipelineIteratorTests: XCTestCase {

    func testZipAndMapTwoArrays() {
        let arr = [0, 1, 2, 3, 4]
        let tmp = PipelineIterator.zip(arr.makePipelineIterator(), arr.makePipelineIterator().map { $0 + 1 })
        var itr = tmp.map { $0.0 + $0.1 }
        XCTAssertEqual(1, try! itr.next())
        XCTAssertEqual(3, try! itr.next())
        XCTAssertEqual(5, try! itr.next())
        XCTAssertEqual(7, try! itr.next())
        XCTAssertEqual(9, try! itr.next())
        XCTAssertEqual(nil, try! itr.next())
    }

    func testZipEndEarly() {
        var itr = PipelineIterator.zip([0, 1, 2].makePipelineIterator(), [0, 1].makePipelineIterator())
        XCTAssert(try! itr.next() != nil)
        XCTAssert(try! itr.next() != nil)
        XCTAssert(try! itr.next() == nil)
    }

    static var allTests = [
        ("testZipAndMapTwoArrays", testZipAndMapTwoArrays),
        ("testZipEndEarly", testZipEndEarly),
    ]
}


// https://github.com/Quick/Quick

import Quick
import Nimble
import SwiftVersionUtils

class TableOfContentsSpec: QuickSpec {
    override func spec() {
        describe("Version Info file") {

            it("has build 'number'") {
                expect("1 Test") == SwiftVersionUtils.getBuildNumber()
            }

            it("has version name") {
                expect("1.0 Test") == SwiftVersionUtils.getVersion()
            }

            it("will fail for travis test") {
                expect("TestFail") == "TestPass"
            }
        }
    }
}

Remove fail test for travis check

// https://github.com/Quick/Quick

import Quick
import Nimble
import SwiftVersionUtils

class TableOfContentsSpec: QuickSpec {
    override func spec() {
        describe("Version Info file") {

            it("has build 'number'") {
                expect("1 Test") == SwiftVersionUtils.getBuildNumber()
            }

            it("has version name") {
                expect("1.0 Test") == SwiftVersionUtils.getVersion()
            }
        }
    }
}


import XCTest
@testable import gattaca

class TMGifOrganizer:XCTestCase
{
    private var coreData:Database?
    private var session:MSession?
    private var model:MHome?
    private let kIdentifier:String = "lorem ipsum"
    private let kWaitExpectation:TimeInterval = 1

    override func setUp()
    {
        super.setUp()

        let session:MSession = MSession()
        self.session = session

        model = MHome(session:session)

        let bundle:Bundle = Bundle(for:TMHomeLoader.self)
        coreData = Database(bundle:bundle)
    }

    //MARK: internal

    func testNewItem()
    {
        guard

            let coreData:Database = self.coreData

        else
        {
            return
        }

        let addExpectation:XCTestExpectation = XCTestExpectation(
            description:"add item")
        let identifier:String = kIdentifier

        coreData.create
        { [weak self] (item:DGif) in

            item.initialValues(identifier:identifier)
            self?.model?.gif.newItem(item:item)
            addExpectation.fulfill()
        }

        waitForExpectations(timeout:kWaitExpectation)
        { [weak self] (error:Error?) in

            guard

                let gif:MGif = self?.model?.gif

            else
            {
                return
            }

            XCTAssertEqual(
                gif.itemsNotReady.count,
                1,
                "failed adding item to not ready")

            let storedItem:DGif? = gif.map[identifier]

            XCTAssertNotNil(
                storedItem,
                "failed mapping item")
        }
    }
}

Use expectation nor just instantiate

import XCTest
@testable import gattaca

class TMGifOrganizer:XCTestCase
{
    private var coreData:Database?
    private var session:MSession?
    private var model:MHome?
    private let kIdentifier:String = "lorem ipsum"
    private let kWaitExpectation:TimeInterval = 1

    override func setUp()
    {
        super.setUp()

        let session:MSession = MSession()
        self.session = session

        model = MHome(session:session)

        let bundle:Bundle = Bundle(for:TMHomeLoader.self)
        coreData = Database(bundle:bundle)
    }

    //MARK: internal

    func testNewItem()
    {
        guard

            let coreData:Database = self.coreData

        else
        {
            return
        }

        let addExpectation:XCTestExpectation = expectation(
            description:"add item expection")
        let identifier:String = kIdentifier

        coreData.create
        { [weak self] (item:DGif) in

            item.initialValues(identifier:identifier)
            self?.model?.gif.newItem(item:item)
            addExpectation.fulfill()
        }

        waitForExpectations(timeout:kWaitExpectation)
        { [weak self] (error:Error?) in

            guard

                let gif:MGif = self?.model?.gif

            else
            {
                return
            }

            XCTAssertEqual(
                gif.itemsNotReady.count,
                1,
                "failed adding item to not ready")

            let storedItem:DGif? = gif.map[identifier]

            XCTAssertNotNil(
                storedItem,
                "failed mapping item")
        }
    }
}


import XCTest
import Gift
import LlamaKit

class GiftTests: XCTestCase {
  func testExample() {
    let fileURL = NSURL(fileURLWithPath: "/Users/bgesiak/Desktop/RepositoryTest")
    let repository = initializeEmptyRepository(fileURL!, RepositoryOptions())
    AssertSuccess(
      repository.flatMap { $0.gitDirectoryURL }.map { $0.path! },
      "/Users/bgesiak/Desktop/RepositoryTest/.git"
    )

    AssertSuccess(repository.flatMap { $0.index }.map { $0.entryCount }, 0)

    let quickOriginURL = NSURL(string: "https://github.com/Quick/Quick.git")
    let quickDestURL = NSURL(fileURLWithPath: "/Users/bgesiak/Desktop/ClonedQuick")
    cloneRepository(quickOriginURL!, quickDestURL!, CloneOptions())
  }
}

Generalize test directory for collaboration

import XCTest
import Gift
import LlamaKit

class GiftTests: XCTestCase {
  func testExample() {
    let desktopPath = "~/Desktop".stringByExpandingTildeInPath
    let repoPathString = "\(desktopPath)/RepositoryTest"
    let fileURL = NSURL(fileURLWithPath: repoPathString)
    let repository = initializeEmptyRepository(fileURL!, RepositoryOptions())
    AssertSuccess(
      repository.flatMap { $0.gitDirectoryURL }.map { $0.path! },
      "\(repoPathString)/.git"
    )

    AssertSuccess(repository.flatMap { $0.index }.map { $0.entryCount }, 0)

    let quickOriginURL = NSURL(string: "https://github.com/Quick/Quick.git")
    let quickDestURL = NSURL(fileURLWithPath: "\(desktopPath)/ClonedQuick")
    cloneRepository(quickOriginURL!, quickDestURL!, CloneOptions())
  }
}


//
//  LoopEnacted.swift
//  RileyLink
//
//  Created by Pete Schwamb on 7/28/16.
//  Copyright © 2016 Pete Schwamb. All rights reserved.
//

import Foundation

public struct LoopEnacted {
    typealias RawValue = [String: Any]

    let rate: Double
    let duration: TimeInterval
    let timestamp: Date
    let received: Bool

    public init(rate: Double, duration: TimeInterval, timestamp: Date, received: Bool) {
        self.rate = rate
        self.duration = duration
        self.timestamp = timestamp
        self.received = received
    }

    public var dictionaryRepresentation: [String: Any] {

        var rval = [String: Any]()

        rval["rate"] = rate
        rval["duration"] = duration / 60.0
        rval["timestamp"] = TimeFormat.timestampStrFromDate(timestamp)
        rval["received"] = received
        return rval
    }

    init?(rawValue: RawValue) {
        guard
            let rate = rawValue["rate"] as? Double,
            let durationMinutes = rawValue["duration"] as? Double,
            let timestampStr = rawValue["timestamp"] as? String,
            let timestamp = TimeFormat.dateFromTimestamp(timestampStr),
            let received = rawValue["received"] as? Bool
        else {
            return nil
        }

        self.rate = rate
        self.duration = TimeInterval(minutes: durationMinutes)
        self.timestamp = timestamp
        self.received = received
    }
}

Add bolusVolume to NS enacted struct

//
//  LoopEnacted.swift
//  RileyLink
//
//  Created by Pete Schwamb on 7/28/16.
//  Copyright © 2016 Pete Schwamb. All rights reserved.
//

import Foundation

public struct LoopEnacted {
    typealias RawValue = [String: Any]

    let rate: Double
    let duration: TimeInterval
    let timestamp: Date
    let received: Bool
    let bolusVolume: Double

    public init(rate: Double, duration: TimeInterval, timestamp: Date, received: Bool, bolusVolume: Double = 0) {
        self.rate = rate
        self.duration = duration
        self.timestamp = timestamp
        self.received = received
        self.bolusVolume = bolusVolume
    }

    public var dictionaryRepresentation: [String: Any] {

        var rval = [String: Any]()

        rval["rate"] = rate
        rval["duration"] = duration / 60.0
        rval["timestamp"] = TimeFormat.timestampStrFromDate(timestamp)
        rval["received"] = received
        rval["bolusVolume"] = bolusVolume
        return rval
    }

    init?(rawValue: RawValue) {
        guard
            let rate = rawValue["rate"] as? Double,
            let durationMinutes = rawValue["duration"] as? Double,
            let timestampStr = rawValue["timestamp"] as? String,
            let timestamp = TimeFormat.dateFromTimestamp(timestampStr),
            let received = rawValue["received"] as? Bool
        else {
            return nil
        }

        self.rate = rate
        self.duration = TimeInterval(minutes: durationMinutes)
        self.timestamp = timestamp
        self.received = received
        self.bolusVolume = rawValue["bolusVolume"] as? Double ?? 0
    }
}


//
//  EmonCMSAccount.swift
//  EmonCMSiOS
//
//  Created by Matt Galloway on 12/09/2016.
//  Copyright © 2016 Matt Galloway. All rights reserved.
//

import Foundation

import Realm
import RealmSwift

struct Account {

  let uuid: UUID
  let url: String
  let apikey: String

  private func realmConfiguration() -> Realm.Configuration {
    let fileURL = URL(fileURLWithPath: RLMRealmPathForFile(self.uuid.uuidString + ".realm"), isDirectory: false)
    let config = Realm.Configuration(fileURL: fileURL)
    return config
  }

  func createRealm() -> Realm {
    let config = self.realmConfiguration()
    let realm = try! Realm(configuration: config)
    return realm
  }

  init(uuid: UUID, url: String, apikey: String) {
    self.uuid = uuid
    self.url = url
    self.apikey = apikey
  }

}

Delete the realm if migration is needed - for dev only

//
//  EmonCMSAccount.swift
//  EmonCMSiOS
//
//  Created by Matt Galloway on 12/09/2016.
//  Copyright © 2016 Matt Galloway. All rights reserved.
//

import Foundation

import Realm
import RealmSwift

struct Account {

  let uuid: UUID
  let url: String
  let apikey: String

  private func realmConfiguration() -> Realm.Configuration {
    let fileURL = URL(fileURLWithPath: RLMRealmPathForFile(self.uuid.uuidString + ".realm"), isDirectory: false)
    var config = Realm.Configuration(fileURL: fileURL)

    //FIXME
    config.deleteRealmIfMigrationNeeded = true

    return config
  }

  func createRealm() -> Realm {
    let config = self.realmConfiguration()
    let realm = try! Realm(configuration: config)
    return realm
  }

  init(uuid: UUID, url: String, apikey: String) {
    self.uuid = uuid
    self.url = url
    self.apikey = apikey
  }

}


// swift-tools-version:5.3

import PackageDescription

let package = Package(
    name: "PKHUD",
    platforms: [
        .iOS(.v8),
    ],
    products: [
        .library(
            name: "PKHUD",
            targets: ["PKHUD"]
        ),
    ],
    targets: [
        .target(
            name: "PKHUD",
            path: "PKHUD",
            resources: [
                .process("Images.xcassets")
            ]
        ),
    ],
    swiftLanguageVersions: [.v5]
)

Exclude the `Info.plist` file from the SPM package.

// swift-tools-version:5.3

import PackageDescription

let package = Package(
    name: "PKHUD",
    platforms: [
        .iOS(.v8),
    ],
    products: [
        .library(
            name: "PKHUD",
            targets: ["PKHUD"]
        ),
    ],
    targets: [
        .target(
            name: "PKHUD",
            path: "PKHUD",
            exclude: [
                "Info.plist",
            ]
        ),
    ],
    swiftLanguageVersions: [.v5]
)


import Foundation
import PackageDescription

let package = Package(
    name: "iCalendar",
    dependencies: [
        .Package(url: "https://github.com/antitypical/Result.git", versions: Version(3, 2, 3)..<Version(3, .max, .max)),
        .Package(url: "https://github.com/Quick/Quick.git", majorVersion: 1, minor: 1),
        .Package(url: "https://github.com/Quick/Nimble.git", majorVersion: 7)
    ],
    swiftLanguageVersions: [3, 4]
)

Update package manifest to Swift 4 format.

// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "iCalendar",
    products: [
        .library(
            name: "iCalendar",
            targets: ["iCalendar"]),
    ],
    dependencies: [
        .package(url: "https://github.com/antitypical/Result.git", from: "3.0.0"),
        .package(url: "https://github.com/Quick/Quick.git", .upToNextMinor(from: "1.1.0")),
        .package(url: "https://github.com/Quick/Nimble.git", from: "7.0.0"),
    ],
    targets: [
        .target(
            name: "iCalendar",
            dependencies: ["Result"],
            path: "Sources"),
        .testTarget(
            name: "iCalendarTests",
            dependencies: ["iCalendar", "Quick", "Nimble"]),
    ],
    swiftLanguageVersions: [3, 4]
)


import PackageDescription

let package = Package(
    name: "libsane",
    dependencies: [
        .Package(url: "../Clibsane", majorVersion: 1)
    ]
)

Put Clibsane dependency out of edit mode

import PackageDescription

let package = Package(
    name: "libsane",
    dependencies: [
        .Package(url: "https://github.com/tamaracha/Clibsane", majorVersion: 1)
    ]
)


import XCTest
@testable import worldcities

class TestModelListParser:XCTestCase
{
    var modelList:ModelList?

    override func setUp()
    {
        super.setUp()
        modelList = ModelList()
    }

    func testFactoryResourceUrl()
    {
        let url:URL? = ModelList.factoryResourceUrl()
        XCTAssertNotNil(url, "failed creating resource url")
    }

    func testLoadData()
    {
        guard

            let url:URL = ModelList.factoryResourceUrl()

        else
        {
            return
        }

        let data:Data? = modelList?.loadData(url:url)
        XCTAssertNotNil(data, "failed loading data from url")
    }

    func testLoadJson()
    {
        guard

            let url:URL = ModelList.factoryResourceUrl(),
            let data:Data = modelList?.loadData(url:url)

        else
        {
            return
        }

        let json:Any? = modelList?.loadJson(data:data)
        XCTAssertNotNil(json, "failed loading json from data")
    }
}

Create test for loading list

import XCTest
@testable import worldcities

class TestModelListParser:XCTestCase
{
    var modelList:ModelList?

    override func setUp()
    {
        super.setUp()
        modelList = ModelList()
    }

    func testFactoryResourceUrl()
    {
        let url:URL? = ModelList.factoryResourceUrl()
        XCTAssertNotNil(url, "failed creating resource url")
    }

    func testLoadData()
    {
        guard

            let url:URL = ModelList.factoryResourceUrl()

        else
        {
            return
        }

        let data:Data? = modelList?.loadData(url:url)
        XCTAssertNotNil(data, "failed loading data from url")
    }

    func testLoadJson()
    {
        guard

            let url:URL = ModelList.factoryResourceUrl(),
            let data:Data = modelList?.loadData(url:url)

        else
        {
            return
        }

        let json:Any? = modelList?.loadJson(data:data)
        XCTAssertNotNil(json, "failed loading json from data")
    }

    func testLoadJsonList()
    {
        guard

            let url:URL = ModelList.factoryResourceUrl(),
            let data:Data = modelList?.loadData(url:url),
            let json:Any = modelList?.loadJson(data:data)

        else
        {
            return
        }

        let jsonList:[AnyObject]? = modelList?.loadJsonList(
            json:json)
        XCTAssertNotNil(jsonList, "failed loading json list from json")
    }
}


import Foundation
import Socket

#if os(macOS) || os(iOS) || os(tvOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif

extension Socket {

    // Avoid race conditions in BlueSocket when closing a socket from another
    // thread by closing the sockets file descriptor using system calls.
    //
    // Assumes socket is being listened to and is connected
    //
    // swiftlint:disable:next identifier_name
    static func forceClose(socketfd fd: Int32) {
        #if os(Linux)
        _ = Glibc.shutdown(fd, Int32(SHUT_RDWR))
        _ = Glibc.close(fd)
        #else
        _ = Darwin.shutdown(fd, Int32(SHUT_RDWR))
        _ = Darwin.close(fd)
        #endif
    }
}

Indent inner scope of conditionals


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

/// Traverse a recursive language.
func reduce<Into, Alphabet>(language: Language<Alphabet>, initial: Into, combine: (Into, Language<Alphabet>) -> Into) -> Into {
	var memo = Dictionary<Language<Alphabet>, Into>()
	return _reduce(memo, language, initial, combine)
}

func _reduce<Into, Alphabet>(var memo: Dictionary<Language<Alphabet>, Into>, language: Language<Alphabet>, initial: Into, combine: (Into, Language<Alphabet>) -> Into) -> Into {
	if let cached = memo[language] { return cached }

	memo[language] = initial
	var into = combine(initial, language)
	memo[language] = into

	switch language {
		case .Empty:
			fallthrough
		case .Null:
			fallthrough
		case .Literal:
			break

		case let .Alternation(left, right):
			into = _reduce(memo, left, into, combine)
			into = _reduce(memo, right, into, combine)

		case let .Concatenation(first, second):
			into = _reduce(memo, first, into, combine)
			into = _reduce(memo, second, into, combine)

		case let .Repetition(language):
			into = _reduce(memo, language, into, combine)

		case let .Reduction(language, _):
			into = _reduce(memo, language, into, combine)
	}

	return into
}

Move reduce into the Language type.

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

/// Traverse a recursive language.
extension Language : Testable {
	func reduce<Into>(initial: Into, combine: (Into, Language<Alphabet>) -> Into) -> Into {
		var memo = Dictionary<Language<Alphabet>, Into>()
		return _reduce(memo, self, initial, combine)
	}
}

func _reduce<Into, Alphabet>(var memo: Dictionary<Language<Alphabet>, Into>, language: Language<Alphabet>, initial: Into, combine: (Into, Language<Alphabet>) -> Into) -> Into {
	if let cached = memo[language] { return cached }

	memo[language] = initial
	var into = combine(initial, language)
	memo[language] = into

	switch language {
		case .Empty:
			fallthrough
		case .Null:
			fallthrough
		case .Literal:
			break

		case let .Alternation(left, right):
			into = _reduce(memo, left, into, combine)
			into = _reduce(memo, right, into, combine)

		case let .Concatenation(first, second):
			into = _reduce(memo, first, into, combine)
			into = _reduce(memo, second, into, combine)

		case let .Repetition(language):
			into = _reduce(memo, language, into, combine)

		case let .Reduction(language, _):
			into = _reduce(memo, language, into, combine)
	}

	return into
}


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

import Foundation

struct Code {

    /// Number of bits used for `code`.
    let bits: Int
    let code: Int
    let symbol: Int

}

Add a func which generates Huffman codes based on their lengths

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

import Foundation

struct Code {

    /// Number of bits used for `code`.
    let bits: Int
    let code: Int
    let symbol: Int

    /// `lengths` don't have to be sorted, but there must not be any 0 code lengths.
    static func huffmanCodes(from lengths: [CodeLength]) -> (codes: [Code], maxBits: Int) {
        // Sort `lengths` array to calculate canonical Huffman code.
        let sortedLengths = lengths.sorted()

        // Calculate maximum amount of leaves possible in a tree.
        let maxBits = sortedLengths.last!.codeLength
        var codes = [Code]()
        codes.reserveCapacity(sortedLengths.count)

        var loopBits = -1
        var symbol = -1
        for length in sortedLengths {
            precondition(length.codeLength > 0, "Code length must not be 0 during HuffmanTree construction.")
            symbol += 1
            // We sometimes need to make symbol to have length.bits bit length.
            let bits = length.codeLength
            if bits != loopBits {
                symbol <<= (bits - loopBits)
                loopBits = bits
            }
            // Then we need to reverse bit order of the symbol.
            let code = symbol.reversed(bits: loopBits)
            codes.append(Code(bits: length.codeLength, code: code, symbol: length.symbol))
        }
        return (codes, maxBits)
    }

}


// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not %target-swift-frontend %s -emit-ir
// REQUIRES: asserts
#if0 *

Remove "REQUIRES: asserts" from fixed crasher

// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not %target-swift-frontend %s -emit-ir
#if0 *


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

import UIKit

public extension UIAlertAction {

    private enum Keys {
        static let checked = "checked"
    }

    public class var cancel: UIAlertAction {
        return UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button title"), style: .cancel) { _ in
            if #available(iOS 10.0, *) {
                UIImpactFeedbackGenerator(style: .light).impactOccurred()
            }
        }
    }

    public func updateChecked(to isChecked: Bool) {
        setValue(isChecked, forKey: Keys.checked)
    }

}

Add support for setting image on UIAlertAction

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

import UIKit

public extension UIAlertAction {

    private enum Keys {
        static let checked = "checked"
        static let image = "image"
    }

    public class var cancel: UIAlertAction {
        return UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button title"), style: .cancel) { _ in
            if #available(iOS 10.0, *) {
                UIImpactFeedbackGenerator(style: .light).impactOccurred()
            }
        }
    }

    public func updateChecked(to isChecked: Bool) {
        setValue(isChecked, forKey: Keys.checked)
    }

    public func updateImage(to image: UIImage) {
        setValue(image, forKey: Keys.image)
    }

}


//
//  DetailViewController.swift
//  Vortaro
//
//  Created by Jan Andersson on 2015-12-28.
//  Copyright © 2015 Visuell Data. All rights reserved.
//

import UIKit

class DetailViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!

    var detailItem: Translation? {
        didSet {
            // Update the view.
            self.configureView()
        }
    }

    func configureView() {
        // Update the user interface for the detail item.
        if let detail = self.detailItem {
            if let view = self.webView {
                var lbl = "" +
                "" +
                "
Esperanto

\(detail.eo)

English
"
                for word in detail.ens() {
                    lbl = lbl + "
\(word)
"
                }
                lbl = lbl + ""
                view.loadHTMLString(lbl, baseURL: nil)
            }
        }
    }

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

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

}

Add links to Wikipedia and Wiktionary

//
//  DetailViewController.swift
//  Vortaro
//
//  Created by Jan Andersson on 2015-12-28.
//  Copyright © 2015 Visuell Data. All rights reserved.
//

import UIKit

class DetailViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!

    var detailItem: Translation? {
        didSet {
            // Update the view.
            self.configureView()
        }
    }

    func configureView() {
        // Update the user interface for the detail item.
        if let detail = self.detailItem {
            if let view = self.webView {
                var lbl = "" +
                "" +
                "
Esperanto

\(detail.eo)

English
"
                for word in detail.ens() {
                    lbl = lbl + "
\(word)
"
                }
                lbl = lbl + "
Vikipedio
"
                lbl = lbl + "
Vikivortaro
"
                lbl = lbl + ""
                view.loadHTMLString(lbl, baseURL: nil)
            }
        }
    }

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

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

}


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

final class ElaborationTests: XCTestCase {
	func testInfersTheTypeOfType() {
		let term: Term = .Type
		assert(try? term.elaborateType(nil, [:], [:]), ==, .Unroll(.Type(1), .Identity(.Type(0))))
	}

	func testChecksLambdasAgainstFunctionTypes() {
		let actual = try? Term.Lambda(.Local(0), .Type, 0).elaborateType(.Type --> .Type, [:], [:])
		let expected: AnnotatedTerm<Term> = .Unroll(.Type --> .Type, .Identity(.Lambda(.Unroll(.Type(1), .Identity(.Type(0))), .Unroll(.Type, .Abstraction(.Local(0), .Unroll(.Type, .Variable(.Local(0))))))))
		assert(actual, ==, expected)
	}
}

import Assertions
import Manifold
import XCTest

Add an assertion that an expression does not throw.

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

final class ElaborationTests: XCTestCase {
	func testInfersTheTypeOfType() {
		let term: Term = .Type
		assert(try? term.elaborateType(nil, [:], [:]), ==, .Unroll(.Type(1), .Identity(.Type(0))))
	}

	func testChecksLambdasAgainstFunctionTypes() {
		let actual = try? Term.Lambda(.Local(0), .Type, 0).elaborateType(.Type --> .Type, [:], [:])
		let expected: AnnotatedTerm<Term> = .Unroll(.Type --> .Type, .Identity(.Lambda(.Unroll(.Type(1), .Identity(.Type(0))), .Unroll(.Type, .Abstraction(.Local(0), .Unroll(.Type, .Variable(.Local(0))))))))
		assert(actual, ==, expected)
	}
}

func assertNoThrow<A>(@autoclosure test: () throws -> A, file: String = __FILE__, line: UInt = __LINE__) -> A? {
	do {
		return try test()
	} catch {
		XCTFail("\(error)", file: file, line: line)
		return nil
	}
}

import Assertions
import Manifold
import XCTest


/**
 * Question Link: https://leetcode.com/problems/decode-ways/
 * Primary idea: Dynamic Programming, dp[i] = dp[i - 1] + dp[i - 2],
 *               determine if current one or two characters are number at first
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 */

class DecodeWays {
    func numDecodings(_ s: String) -> Int {
        let chars = Array(s.characters), len = chars.count

        guard len > 0 else {
            return 0
        }

        var dp = Array(repeating: 0, count: len + 1)
        dp[0] = 1
        dp[1] = isValid(String(chars[0 ..< 1])) ? 1 : 0

        guard len >= 2 else {
            return dp[len]
        }

        for i in 2 ... len {
            if isValid(String(chars[i - 1 ..< i])) {
                dp[i] += dp[i - 1]
            }
            if isValid(String(chars[i - 2 ..< i])) {
                dp[i] += dp[i - 2]
            }
        }

        return dp[len]
    }

    private func isValid(_ str: String) -> Bool {
        let chars = Array(str.characters)

        if chars[0] == "0" {
            return false
        }

        let num = Int(str)!

        return num > 0 && num <= 26
    }
}

Optimize code style for Decode Ways

/**
 * Question Link: https://leetcode.com/problems/decode-ways/
 * Primary idea: Dynamic Programming, dp[i] = dp[i - 1] + dp[i - 2],
 *               determine if current one or two characters are number at first
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 */

class DecodeWays {
    func numDecodings(_ s: String) -> Int {
        let sChars = Array(s.characters), len = sChars.count
        var dp = Array(repeating: 0, count: len + 1)
        dp[0] = 1

        guard len >= 1 else {
            return 0
        }

        for i in 1 ... len {
            if isValid(String(sChars[i - 1 ..< i])) {
                dp[i] += dp[i - 1]
            }
            if i >= 2 && isValid(String(sChars[i - 2 ..< i])) {
                dp[i] += dp[i - 2]
            }
        }

        return dp[len]
    }

    private func isValid(_ numStr: String) -> Bool {
        if Array(numStr.characters).first == "0" {
            return false
        }

        guard let num = Int(numStr) else {
            return false
        }

        return num >= 1 && num <= 26
    }
}


import IGListKit

class PostViewModel {
    let post: Post

    init(_ post: Post) {
        self.post = post
    }
}

extension PostViewModel: ListDiffable {
    func diffIdentifier() -> NSObjectProtocol {
        return NSNumber(value: post.id)
    }

    func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
        guard let object = object as? PostViewModel else {
            return false
        }
        return post.actions == object.post.actions &&
            post.content == object.post.content &&
            post.descendants == object.post.descendants
    }
}

class ItemListViewModel {
    let fetching: ContainerFetchState?
    let hasMoreItems: Bool
    let selectedItem: ItemDetails?
    fileprivate let allPosts: [Post]

    lazy var posts: [PostViewModel] = self.allPosts.map(PostViewModel.init)

    init(list: ItemList = ItemList(), details: ItemDetails? = .none) {
        fetching = list.fetching
        allPosts = list.posts
        hasMoreItems = list.ids.isEmpty || list.posts.count < list.ids.count
        selectedItem = details
    }
}

extension ItemListViewModel: Equatable {
    static func == (_ lhs: ItemListViewModel, _ rhs: ItemListViewModel) -> Bool {
        return lhs.fetching == rhs.fetching &&
            lhs.hasMoreItems == rhs.hasMoreItems &&
            (
                (lhs.selectedItem == nil && rhs.selectedItem == nil) ||
                (lhs.selectedItem != nil && rhs.selectedItem != nil)
            ) &&
            lhs.allPosts == rhs.allPosts
    }
}

Fix duplicate fetching of posts in item list

import IGListKit

class PostViewModel {
    let post: Post

    init(_ post: Post) {
        self.post = post
    }
}

extension PostViewModel: ListDiffable {
    func diffIdentifier() -> NSObjectProtocol {
        return NSNumber(value: post.id)
    }

    func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
        guard let object = object as? PostViewModel else {
            return false
        }
        return post.actions == object.post.actions &&
            post.content == object.post.content &&
            post.descendants == object.post.descendants
    }
}

class ItemListViewModel {
    let fetching: ContainerFetchState?
    let hasMoreItems: Bool
    let selectedItem: ItemDetails?
    fileprivate let allPosts: [Post]

    lazy var posts: [PostViewModel] = self.allPosts.map(PostViewModel.init)

    init(list: ItemList = ItemList(), details: ItemDetails? = .none) {
        fetching = list.fetching
        allPosts = list.posts
        selectedItem = details
        hasMoreItems = list.fetching == .none ||
            list.fetching == .items(.finished) && list.posts.count < list.ids.count
    }
}

extension ItemListViewModel: Equatable {
    static func == (_ lhs: ItemListViewModel, _ rhs: ItemListViewModel) -> Bool {
        return lhs.fetching == rhs.fetching &&
            lhs.hasMoreItems == rhs.hasMoreItems &&
            (
                (lhs.selectedItem == nil && rhs.selectedItem == nil) ||
                (lhs.selectedItem != nil && rhs.selectedItem != nil)
            ) &&
            lhs.allPosts == rhs.allPosts
    }
}


//
//  Created by Cihat Gündüz on 18.12.15.
//  Copyright © 2015 Flinesoft. All rights reserved.
//

import Foundation

extension Int {
    /// Initializes a new `Int ` instance with a random value below a given `Int`.
    ///
    /// - Parameters:
    ///   - randomBelow: The upper bound value to create a random value with.
    public init?(randomBelow upperLimit: Int) {
        guard upperLimit > 0 else { return nil }
        self.init(Int.random(in: 0..<upperLimit))
    }

    /// Runs the code passed as a closure the specified number of times.
    ///
    /// - Parameters:
    ///   - closure: The code to be run multiple times.
    public func times(_ closure: () -> Void) {
        guard self > 0 else { return }
        for _ in 0..<self { closure() }
    }

    /// Runs the code passed as a closure the specified number of times
    /// and creates an array from the return values.
    ///
    /// - Parameters:
    ///   - closure: The code to deliver a return value multiple times.
    public func timesMake<ReturnType>(_ closure: () -> ReturnType) -> [ReturnType] {
        guard self > 0 else { return [] }
        return (0..<self).map { _ in return closure() }
    }
}

Refactor init method (formerly: Linux support)

//
//  Created by Cihat Gündüz on 18.12.15.
//  Copyright © 2015 Flinesoft. All rights reserved.
//

import Foundation

extension Int {
    /// Initializes a new `Int ` instance with a random value below a given `Int`.
    ///
    /// - Parameters:
    ///   - randomBelow: The upper bound value to create a random value with.
    public init?(randomBelow upperLimit: Int) {
        guard upperLimit > 0 else { return nil }
        self = .random(in: 0 ..< upperLimit)
    }

    /// Runs the code passed as a closure the specified number of times.
    ///
    /// - Parameters:
    ///   - closure: The code to be run multiple times.
    public func times(_ closure: () -> Void) {
        guard self > 0 else { return }
        for _ in 0..<self { closure() }
    }

    /// Runs the code passed as a closure the specified number of times
    /// and creates an array from the return values.
    ///
    /// - Parameters:
    ///   - closure: The code to deliver a return value multiple times.
    public func timesMake<ReturnType>(_ closure: () -> ReturnType) -> [ReturnType] {
        guard self > 0 else { return [] }
        return (0..<self).map { _ in return closure() }
    }
}


// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swiftc_driver -o %t/main -module-name main -stats-output-dir %t %s -trace-stats-events
// RUN: %FileCheck -input-file %t/*.csv %s

// CHECK: {{"Sema.NumTypesDeserialized"}}

public func foo() {
    print("hello")
}

Expand -trace-stats-events test to cover recent work.

// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swiftc_driver -o %t/main -module-name main -stats-output-dir %t %s -trace-stats-events
// RUN: %FileCheck -input-file %t/*.csv %s

// CHECK: {{[0-9]+,[0-9]+,"exit","check-conformance","Sema.NominalTypeLookupDirectCount",[0-9]+,[0-9]+,"<conformance Bar : Proto>","\[.*stats_dir_tracer.swift:21:1 - line:27:1\]"}}
// CHECK: {{[0-9]+,[0-9]+,"exit","typecheck-fn","Sema.NumTypesDeserialized",[0-9]+,[0-9]+,"foo\(\)","\[.*stats_dir_tracer.swift:9:8 - line:11:1\]"}}
// CHECK: {{[0-9]+,[0-9]+,"exit","typecheck-decl","Sema.NumConstraintScopes",[0-9]+,[0-9]+,"<pattern binding>","\[.*stats_dir_tracer.swift:23:5 - line:23:13\]"}}

public func foo() {
    print("hello")
}

protocol Proto {
  func bar() -> Int;
}

class Bar {
  typealias T = Int
}

extension Bar : Proto {
  func bar() -> T {
    let x = 1
    let y = Int(1.0)
    return x + y
  }
}


import Foundation

extension MHome
{
    //MARK: internal

    func asyncLoadItems(
        completion:@escaping(([MHomeItem]) -> ()))
    {
        guard

            let coreData:Database = self.coreData

        else
        {
            return
        }

        gif.strategy?.load(coreData:coreData)
        { [weak self] in

            self?.loadItemsDone(completion:completion)
        }
    }

    func loadItemsDone(
        completion:@escaping(([MHomeItem]) -> ()))
    {
        let itemsReady:[DGif] = gif.itemsReady
        let count:Int = itemsReady.count

        if count > 0
        {
            let items:[MHomeItem] = MHome.factoryItems(
                gifItems:itemsReady)
            gif.strategy?.download()

            completion(items)
        }
        else
        {
            requestGifs()
        }
    }
}

Clear items ready after adding

import Foundation

extension MHome
{
    //MARK: internal

    func asyncLoadItems(
        completion:@escaping(([MHomeItem]) -> ()))
    {
        guard

            let coreData:Database = self.coreData

        else
        {
            return
        }

        gif.strategy?.load(coreData:coreData)
        { [weak self] in

            self?.loadItemsDone(completion:completion)
        }
    }

    func loadItemsDone(
        completion:@escaping(([MHomeItem]) -> ()))
    {
        let itemsReady:[DGif] = gif.itemsReady
        let count:Int = itemsReady.count

        if count > 0
        {
            gif.itemsReady = []

            let items:[MHomeItem] = MHome.factoryItems(
                gifItems:itemsReady)
            gif.strategy?.download()

            completion(items)
        }
        else
        {
            requestGifs()
        }
    }
}


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

Test that the null multiset is 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)
	}
}


//
//  Urls.swift
//  DuckDuckGo
//
//  Created by Mia Alexiou on 24/01/2017.
//  Copyright © 2017 DuckDuckGo. All rights reserved.
//

import Foundation

struct Urls {
    static let home = "https://www.duckduckgo.com"
    static let duckduckGoSearch = "https://www.duckduckgo.com"
}

Update ddg url query params to hide website search bar in app

//
//  Urls.swift
//  DuckDuckGo
//
//  Created by Mia Alexiou on 24/01/2017.
//  Copyright © 2017 DuckDuckGo. All rights reserved.
//

import Foundation

struct Urls {
    static let home = "https://www.duckduckgo.com?ko=-1"
}


//
//  AppDelegate.swift
//  BlenderX
//
//  Created by Tony Ingraldi on 8/13/15.
//  Copyright (c) 2015 Majesty Software. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

}

Exit app when window is closed

//
//  AppDelegate.swift
//  BlenderX
//
//  Created by Tony Ingraldi on 8/13/15.
//  Copyright (c) 2015 Majesty Software. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }
}


// Tailor Mac Playground

import Cocoa
import Tailor

struct Person: Inspectable, Mappable, Equatable {
  var firstName: String = ""
  var lastName: String? = ""

  init(_ map: [String : AnyObject]) {
    firstName <- map.property("firstName")
    lastName  <- map.property("lastName")
  }
}

func ==(lhs: Person, rhs: Person) -> Bool {
  return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName
}

let taylor = Person(["firstName" : "Taylor", "lastName" : "Swift"])
print(taylor.firstName)
print(taylor.lastName)

var firstName: String
firstName <- taylor.property("firstName") ?? ""

print(taylor.properties())

Remove silly code in playground


//
//  BASubscriptionViewController.swift
//  BA-iOS-Application
//
//  Created by Maxime Mongeau on 2016-02-13.
//  Copyright © 2016 Samuel Bellerose. All rights reserved.
//

import UIKit

class BASubscriptionViewController: UIViewController {

    var goodDeed: GoodDeed?

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var descTextView: UITextView!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var dateDebutLabel: UILabel!
    @IBOutlet weak var dateFinLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        if let gd = goodDeed {
            self.title = gd.title
            let formatter = NSDateFormatter()
            formatter.dateFormat = "YYYY/MM/dd - HH:mm"
            self.descTextView.text = gd.desc
            self.dateDebutLabel.text = formatter.stringFromDate(gd.startDate)
            self.dateFinLabel.text = formatter.stringFromDate(gd.endDate)
        }
    }

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

    @IBAction func cancelTapped(sender: UIBarButtonItem) {
        self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
    }

    @IBAction func propositionTapped() {

    }

}

Add some user info in subs view

//
//  BASubscriptionViewController.swift
//  BA-iOS-Application
//
//  Created by Maxime Mongeau on 2016-02-13.
//  Copyright © 2016 Samuel Bellerose. All rights reserved.
//

import UIKit

class BASubscriptionViewController: UIViewController {

    var goodDeed: GoodDeed?

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var descTextView: UITextView!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var dateDebutLabel: UILabel!
    @IBOutlet weak var dateFinLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        if let gd = goodDeed {
            self.title = gd.title
            let formatter = NSDateFormatter()
            formatter.dateFormat = "YYYY/MM/dd - HH:mm"
            self.descTextView.text = gd.desc
            self.dateDebutLabel.text = formatter.stringFromDate(gd.startDate)
            self.dateFinLabel.text = formatter.stringFromDate(gd.endDate)
            self.usernameLabel.text = gd.creator.name
            self.imageView.image = UIImage(named: gd.creator.name)
        }
    }

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

    @IBAction func cancelTapped(sender: UIBarButtonItem) {
        self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
    }

    @IBAction func propositionTapped() {

    }

}


public typealias Revision = String

extension Service {
    public class Info: InfoBase {

        public init(name: String,
                    serialNumber: String,
                    manufacturer: String = "undefined",
                    model: String = "undefined",
                    firmwareRevision: Revision = "1.0.0") {
            super.init(characteristics: [.firmwareRevision()])
            self.name.value = name
            self.manufacturer.value = manufacturer
            self.model.value = model
            self.serialNumber.value = serialNumber
            self.firmwareRevision?.value = firmwareRevision
        }

        open override func characteristic<T>(_ characteristic: GenericCharacteristic<T>,
                                             didChangeValue newValue: T?) {
            if characteristic === identify {
                if let accessory = accessory {
                    accessory.device?.delegate?.didRequestIdentificationOf(accessory)
                }
            }
            super.characteristic(characteristic, didChangeValue: newValue)
        }
    }
}

Make use of new shorthand initialisation

public typealias Revision = String

extension Service {
    public class Info: InfoBase {

        public init(name: String,
                    serialNumber: String,
                    manufacturer: String = "unknown",
                    model: String = "unknown",
                    firmwareRevision: Revision = "1") {
            super.init(characteristics: [
                .name(name),
                .serialNumber(serialNumber),
                .manufacturer(manufacturer),
                .model(model),
                .firmwareRevision(firmwareRevision)
            ])
        }

        open override func characteristic<T>(_ characteristic: GenericCharacteristic<T>,
                                             didChangeValue newValue: T?) {
            if characteristic === identify {
                if let accessory = accessory {
                    accessory.device?.delegate?.didRequestIdentificationOf(accessory)
                }
            }
            super.characteristic(characteristic, didChangeValue: newValue)
        }
    }
}


/*
* Released under the MIT License (MIT), http://opensource.org/licenses/MIT
*
* Copyright (c) 2015 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com)
*
*/

import Foundation

Add read and write methods to NSFilehandle.

/*
* Released under the MIT License (MIT), http://opensource.org/licenses/MIT
*
* Copyright (c) 2015 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com)
*
*/

import Foundation

extension NSFileHandle {

	public func readSome (encoding encoding: UInt = main.encoding) -> String? {
		let data: NSData = self.availableData

		guard data.length > 0 else { return nil }
		guard let result = NSString(data: data, encoding: encoding) else {
			printErrorAndExit("Fatal error - could not convert stream to text.")
		}

		return result as String
	}

	public func read (encoding encoding: UInt = main.encoding) -> String {
		let data: NSData = self.readDataToEndOfFile()

		guard let result = NSString(data: data, encoding: encoding) else {
			printErrorAndExit("Fatal error - could not convert stream to text.")
		}

		return result as String
	}
}

extension NSFileHandle {

	public func write (string: String, encoding: UInt = main.encoding) {
		writeData(string.dataUsingEncoding(encoding, allowLossyConversion:false)!)
	}

	public func writeln (string: String = "", encoding: UInt = main.encoding) {
		self.write(string + "\n", encoding: encoding)
	}
}


//
//  UIKit+TMBarItem.swift
//  Tabman
//
//  Created by Merrick Sapsford on 19/10/2018.
//  Copyright © 2018 UI At Six. All rights reserved.
//

import UIKit

extension UINavigationItem: TMBarItemable {

    public var image: UIImage? {
        return nil
    }
}

extension UITabBarItem: TMBarItemable {
}

Add item support to UIViewController

//
//  UIKit+TMBarItem.swift
//  Tabman
//
//  Created by Merrick Sapsford on 19/10/2018.
//  Copyright © 2018 UI At Six. All rights reserved.
//

import UIKit

extension UINavigationItem: TMBarItemable {

    public var image: UIImage? {
        return nil
    }
}

extension UITabBarItem: TMBarItemable {
}

extension UIViewController: TMBarItemable {

    public var image: UIImage? {
        return tabBarItem.image
    }
}


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

public enum Description<Index> {
	// MARK: Constructors

	public static func end(index: Index) -> Description {
		return .End(Box(index))
	}

	// MARK: Destructors

	var end: Index? {
		return analysis(ifEnd: unit)
	}

	// MARK: Analyses

	public func analysis<T>(@noescape #ifEnd: Index -> T) -> T {
		switch self {
		case let .End(index):
			return ifEnd(index.value)
		}
	}

	// MARK: Cases

	case End(Box<Index>)
}

import Box

Add a recursive case to type descriptions.

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

public enum Description<Index> {
	// MARK: Constructors

	public static func end(index: Index) -> Description {
		return .End(Box(index))
	}

	// MARK: Destructors

	var end: Index? {
		return analysis(
			ifEnd: unit,
			ifRecursive: const(nil))
	}

	// MARK: Analyses

	public func analysis<T>(
		@noescape #ifEnd: Index -> T,
		@noescape ifRecursive: (Index, Description) -> T) -> T {
		switch self {
		case let .End(index):
			return ifEnd(index.value)
		case let .Recursive(index, description):
			return ifRecursive(index.value, description.value)
		}
	}

	// MARK: Cases

	case End(Box<Index>)
	case Recursive(Box<Index>, Box<Description>)
}

import Box


// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// http://www.openradar.me/19744740

import Foundation
Optional(""as NSString)?.caseInsensitiveCompare("") == .OrderedSame

Add newline at end of file.


//
//  RxOperators.swift
//  Unilib
//
//  Created by David James on 10/10/16.
//  Copyright © 2016 David B James. All rights reserved.
//

import Foundation
import RxSwift

// TODO: Install RxSwiftExt and remove these redundant extensions
// (however, keep this file so you can write your own extensions, looks easy)

extension Observable {
    /**
     Suppress duplicate items emitted by an Observable
     - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
     - parameter predicate: predicate determines whether element distinct

     - returns: An observable sequence only containing the distinct contiguous elements, based on predicate, from the source sequence.
     */
    public func distinct(_ predicate: @escaping (Element) throws -> Bool) -> Observable<E> {
        var cache = [Element]()
        return flatMap { element -> Observable<Element> in
            if try cache.contains(where: predicate) {
                return Observable<Element>.empty()
            } else {
                cache.append(element)
                return Observable<Element>.just(element)
            }
        }
    }
}

extension Observable where Element: Hashable {
    /**
     Suppress duplicate items emitted by an Observable
     - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
     - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
     */
    public func distinct() -> Observable<Element> {
        var cache = Set<Element>()
        return flatMap { element -> Observable<Element> in
            if cache.contains(element) {
                return Observable<Element>.empty()
            } else {
                cache.insert(element)
                return Observable<Element>.just(element)
            }
        }
    }
}

extension Observable where Element: Equatable {
    /**
     Suppress duplicate items emitted by an Observable
     - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
     - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
     */
    public func distinct() -> Observable<Element> {
        var cache = [Element]()
        return flatMap { element -> Observable<Element> in
            if cache.contains(element) {
                return Observable<Element>.empty()
            } else {
                cache.append(element)
                return Observable<Element>.just(element)
            }
        }
    }
}

Remove copied distinct() observables because we're now using RxSwiftExt.

//
//  RxOperators.swift
//  Unilib
//
//  Created by David James on 10/10/16.
//  Copyright © 2016 David B James. All rights reserved.
//

import Foundation
import RxSwift

// Rx Extensions go here. See RxSwift and RxSwiftExt for examples


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

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

private let module = Module<Term>.churchBoolean

import Manifold
import XCTest

Test the evaluation of `true`.

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

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

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

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

import Assertions
import Manifold
import XCTest


//
//  String.swift
//  RNCryptor
//
//  Created by Rob Napier on 7/1/15.
//  Copyright © 2015 Rob Napier. All rights reserved.
//

import Foundation

extension String {
    init?(UTF8String: UnsafePointer<UInt8>) {
        self.init(UnsafePointer<Int8>(UTF8String))
    }
}

Add experimental string bridge (may not be a good idea)

//
//  String.swift
//  RNCryptor
//
//  Created by Rob Napier on 7/1/15.
//  Copyright © 2015 Rob Napier. All rights reserved.
//

import Foundation

extension String {
    init?(UTF8String: UnsafePointer<UInt8>) {
        self.init(UTF8String: UnsafePointer<Int8>(UTF8String))
    }
}


//
//  DebugLogDemoTests.swift
//  DebugLogDemoTests
//
//  Created by Yasuhiro Inami on 2014/06/22.
//  Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//

import XCTest
import CoreGraphics
import QuartzCore

class DebugLogTests: XCTestCase {

    override func setUp()
    {
        super.setUp()

        println()
        println("===== SET UP =====")
#if DEBUG
        println("=== DEBUG MODE ===")
#endif
    }

    override func tearDown()
    {
        println()
        println("===== TEAR DOWN =====")

        super.tearDown()
    }

    func testPrintlnPerformance()
    {
        self.measureBlock() {
            for _ in 0..1000 {
#if DEBUG
                println("hoge")
#endif
            }
        }
    }

    func testDebugLogPerformance()
    {
        self.measureBlock() {
            for _ in 0..1000 {
                LOG("hoge")
            }
        }
    }

}

Add implicitlyUnwrappedOptional test which cause EXC_BAD_INSTRUCTION.

//
//  DebugLogDemoTests.swift
//  DebugLogDemoTests
//
//  Created by Yasuhiro Inami on 2014/06/22.
//  Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//

import XCTest
import CoreGraphics
import QuartzCore

class DebugLogTests: XCTestCase {

    override func setUp()
    {
        super.setUp()

        println()
        println("===== SET UP =====")
#if DEBUG
        println("=== DEBUG MODE ===")
#endif
    }

    override func tearDown()
    {
        println()
        println("===== TEAR DOWN =====")

        super.tearDown()
    }

    func testDebugLog()
    {
        let str: String = "hi"
        LOG_OBJECT(str)

        let optional: String? = nil
        LOG_OBJECT(optional)

        let implictlyUnwrappedOptional: String! = nil
        LOG_OBJECT(implictlyUnwrappedOptional)
    }

    func testPrintlnPerformance()
    {
        self.measureBlock() {
            for _ in 0..1000 {
#if DEBUG
                println("hoge")
#endif
            }
        }
    }

    func testDebugLogPerformance()
    {
        self.measureBlock() {
            for _ in 0..1000 {
                LOG("hoge")
            }
        }
    }

}


import UIKit

struct ApplicationAppearance {
    static func setupAppearance() {
        UINavigationBar.appearance().setBackgroundImage(UIImage(named: "NavigationBarBackground"), forBarMetrics: .Default)

        let attributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
        UIBarButtonItem.appearance().setTitleTextAttributes(attributes, forState: .Normal)
        UINavigationBar.appearance().titleTextAttributes = attributes
    }
}

Set bar button item tint color

import UIKit

struct ApplicationAppearance {
    static func setupAppearance() {
        UINavigationBar.appearance().setBackgroundImage(UIImage(named: "NavigationBarBackground"), forBarMetrics: .Default)

        let attributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
        UIBarButtonItem.appearance().setTitleTextAttributes(attributes, forState: .Normal)
        UIBarButtonItem.appearance().tintColor  = UIColor.whiteColor()
        UINavigationBar.appearance().titleTextAttributes = attributes
    }
}


//
//  UIView+Localization.swift
//  Pageboy
//
//  Created by Merrick Sapsford on 18/06/2017.
//  Copyright © 2018 UI At Six. All rights reserved.
//

import UIKit

extension UIView {

    /// Whether the layout direction of the view is right to left.
    var layoutIsRightToLeft: Bool {
        if #available(iOS 9.0, *) {
            return UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .rightToLeft
        } else {
            return UIApplication.safeShared?.userInterfaceLayoutDirection == .rightToLeft
        }
    }

}

Fix threading issue with layout direction detection

//
//  UIView+Localization.swift
//  Pageboy
//
//  Created by Merrick Sapsford on 18/06/2017.
//  Copyright © 2018 UI At Six. All rights reserved.
//

import UIKit

extension UIView {

    /// Whether the layout direction of the view is right to left.
    var layoutIsRightToLeft: Bool {
        var layoutDirection: UIUserInterfaceLayoutDirection!
        if Thread.isMainThread {
            layoutDirection = getUserInterfaceLayoutDirection()
        } else {
            DispatchQueue.main.sync {
                layoutDirection = getUserInterfaceLayoutDirection()
            }
        }
        return layoutDirection == .rightToLeft
    }

    private func getUserInterfaceLayoutDirection() -> UIUserInterfaceLayoutDirection {
        assert(Thread.isMainThread)
        return UIView.userInterfaceLayoutDirection(for: semanticContentAttribute)
    }

}


//
//  PromptSettings.swift
//  PromptSettings
//
//  Created by Omar Abdelhafith on 02/11/2015.
//  Copyright © 2015 Omar Abdelhafith. All rights reserved.
//

import Foundation

class PromptSettings {

    static var reader: PromptReader!
    static var printer: PromptPrinter!

    class func getReader() -> PromptReader {
        if let reader = PromptSettings.reader {
            return reader
        } else {
            return ConsolePromptReader()
        }
    }

    class func getPrinter() -> PromptPrinter {
        if let printer = PromptSettings.printer {
            return printer
        } else {
            return ConsolePromptPrinter()
        }
    }

    class func read() -> String? {
        return getReader().read()
    }

    class func print(string: String, terminator: String = "\n") {
        return getPrinter().printString(string, terminator: terminator)
    }
}

Use swift lazy vars magic

//
//  PromptSettings.swift
//  PromptSettings
//
//  Created by Omar Abdelhafith on 02/11/2015.
//  Copyright © 2015 Omar Abdelhafith. All rights reserved.
//

import Foundation

class PromptSettings {

    static var reader: PromptReader = ConsolePromptReader()
    static var printer: PromptPrinter = ConsolePromptPrinter()

    class func read() -> String? {
        return reader.read()
    }

    class func print(string: String, terminator: String = "\n") {
        return printer.printString(string, terminator: terminator)
    }
}


// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out
// RUN: %{python} %S/../Inputs/not.py "%target-run %t/a.out" 2>&1 | %{lldb-python} %utils/symbolicate-linux-fatal %t/a.out - | %{python} %utils/backtrace-check -u
// REQUIRES: executable_test
// REQUIRES: OS=linux-gnu
// REQUIRES: lldb
// XFAIL: CPU=s390x

// NOTE: not.py is used above instead of "not --crash" because %target-run
// doesn't pass through the crash, and `not` may not be available when running
// on a remote host.

// Backtraces are not emitted when optimizations are enabled. This test can not
// run when optimizations are enabled.
// REQUIRES: swift_test_mode_optimize_none

func funcB() {
    fatalError("linux-fatal-backtrace");
}

func funcA() {
    funcB();
}

print("bla")
funcA()

Disable linux backtrace test since it is failing now to unblock the bots.

// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out
// RUN: %{python} %S/../Inputs/not.py "%target-run %t/a.out" 2>&1 | %{lldb-python} %utils/symbolicate-linux-fatal %t/a.out - | %{python} %utils/backtrace-check -u
// REQUIRES: executable_test
// REQUIRES: OS=linux-gnu
// REQUIRES: lldb
// REQUIRES: rdar87867848
// XFAIL: CPU=s390x

// NOTE: not.py is used above instead of "not --crash" because %target-run
// doesn't pass through the crash, and `not` may not be available when running
// on a remote host.

// Backtraces are not emitted when optimizations are enabled. This test can not
// run when optimizations are enabled.
// REQUIRES: swift_test_mode_optimize_none

func funcB() {
    fatalError("linux-fatal-backtrace");
}

func funcA() {
    funcB();
}

print("bla")
funcA()


import XCTest

class TMRequest:XCTestCase
{
}

Add tests for url map

import XCTest
@testable import gattaca

class TMRequest:XCTestCase
{
    //MARK: private

    private func allRootKeys() -> [String]
    {
        let keys:[String] = [
            "app",
            "gif",
            "giphy"]

        return keys
    }

    //MARK: internal

    func testFactoryUrlMap()
    {
        let urlMap:[String:AnyObject]? = MRequest.factoryUrlMap()

        XCTAssertNotNil(
            urlMap,
            "failed loading url map")
    }

    func testUrlMapKeys()
    {
        let urlMap:[String:AnyObject]? = MRequest.factoryUrlMap()
        let allKeys:[String] = allRootKeys()

        for key:String in allKeys
        {
            XCTAssertNotNil(
                urlMap?[key],
                "key not found in map")
        }
    }
}