import XCTest
@testable import OutlawTests

XCTMain([
    testCase(ArrayTests.allTests),
    testCase(BoolTests.allTests),
    testCase(CharacterTests.allTests),
    testCase(DateTests.allTests),
    testCase(DeserializableTests.allTests),
    testCase(DeserializableWithContextTests.allTests),
    testCase(DictionaryTests.allTests),
    testCase(DoubleTests.allTests),
    testCase(EnumTests.allTests),
    testCase(FloatTests.allTests),
    testCase(IntTests.allTests),
    testCase(Int8Tests.allTests),
    testCase(Int16Tests.allTests),
    testCase(Int32Tests.allTests),
    testCase(Int64Tests.allTests),
    testCase(SerializableTests.allTests),
    testCase(SerializableWithContextTests.allTests),
    testCase(SetTests.allTests),
    testCase(StringTests.allTests),
    testCase(UIntTests.allTests),
    testCase(UInt8Tests.allTests),
    testCase(UInt16Tests.allTests),
    testCase(UInt32Tests.allTests),
    testCase(UInt64Tests.allTests),
    testCase(UpdatableTests.allTests),
    testCase(UpdatableWithContextTests.allTests),
    testCase(URLTests.allTests),
    testCase(ValueWithContextTests.allTests)
])

Comment out tests for linux as the Bundle(for:) api has not been implemented.

import XCTest
@testable import OutlawTests

XCTMain([
//    testCase(ArrayTests.allTests),
//    testCase(BoolTests.allTests),
//    testCase(CharacterTests.allTests),
//    testCase(DateTests.allTests),
//    testCase(DeserializableTests.allTests),
//    testCase(DeserializableWithContextTests.allTests),
//    testCase(DictionaryTests.allTests),
//    testCase(DoubleTests.allTests),
//    testCase(EnumTests.allTests),
//    testCase(FloatTests.allTests),
//    testCase(IntTests.allTests),
//    testCase(Int8Tests.allTests),
//    testCase(Int16Tests.allTests),
//    testCase(Int32Tests.allTests),
//    testCase(Int64Tests.allTests),
//    testCase(SerializableTests.allTests),
//    testCase(SerializableWithContextTests.allTests),
//    testCase(SetTests.allTests),
//    testCase(StringTests.allTests),
//    testCase(UIntTests.allTests),
//    testCase(UInt8Tests.allTests),
//    testCase(UInt16Tests.allTests),
//    testCase(UInt32Tests.allTests),
//    testCase(UInt64Tests.allTests),
//    testCase(UpdatableTests.allTests),
//    testCase(UpdatableWithContextTests.allTests),
//    testCase(URLTests.allTests),
//    testCase(ValueWithContextTests.allTests)
])


// swift-tools-version:5.1
import PackageDescription

let package = Package(
    name: "TrustKit",
    platforms: [
        .iOS(.v12),
        .macOS(.v10_13),
        .tvOS(.v12),
        .watchOS(.v4)
    ],
    products: [
        .library(
            name: "TrustKit",
            targets: ["TrustKit"]
        ),
        .library(
            name: "TrustKitDynamic",
            type: .dynamic,
            targets: ["TrustKit"]
        ),
        .library(
            name: "TrustKitStatic",
            type: .static,
            targets: ["TrustKit"]
        ),
    ],
    dependencies: [
    ],
    targets: [
        .target(
            name: "TrustKit",
            dependencies: [],
            path: "TrustKit",
            publicHeadersPath: "public"
        ),
    ]
)

Use NS_BLOCK_ASSERTIONS for SwiftPM release builds

// swift-tools-version:5.1
import PackageDescription

let package = Package(
    name: "TrustKit",
    platforms: [
        .iOS(.v12),
        .macOS(.v10_13),
        .tvOS(.v12),
        .watchOS(.v4)
    ],
    products: [
        .library(
            name: "TrustKit",
            targets: ["TrustKit"]
        ),
        .library(
            name: "TrustKitDynamic",
            type: .dynamic,
            targets: ["TrustKit"]
        ),
        .library(
            name: "TrustKitStatic",
            type: .static,
            targets: ["TrustKit"]
        ),
    ],
    dependencies: [
    ],
    targets: [
        .target(
            name: "TrustKit",
            dependencies: [],
            path: "TrustKit",
            publicHeadersPath: "public",
            cSettings: [.define("NS_BLOCK_ASSERTIONS", to: "1", .when(configuration: .release))]
        ),
    ]
)


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

let package = Package(
    name: "Charts",
    platforms: [
        .iOS(.v11),
        .tvOS(.v11),
        .macOS(.v10_11),
    ],
    products: [
        .library(
            name: "Charts",
            targets: ["Charts"]
        ),
        .library(
            name: "ChartsDynamic",
            type: .dynamic,
            targets: ["Charts"]
        ),
    ],
    dependencies: [
        .package(url: "https://github.com/apple/swift-algorithms", .branch("main")),
        .package(name: "SnapshotTesting", url: "https://github.com/pointfreeco/swift-snapshot-testing.git", from: "1.8.1"),
    ],
    targets: [
        .target(
            name: "Charts",
            dependencies: [.product(name: "Algorithms", package: "swift-algorithms")]
        ),
        .testTarget(
            name: "ChartsTests",
            dependencies: ["Charts", "SnapshotTesting"],
            exclude: ["__Snapshots__"],
            resources: [
                .process("Resources")
            ]
        )
    ],
    swiftLanguageVersions: [.v5]
)

Exclude snapshot directories from test target

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

let package = Package(
    name: "Charts",
    platforms: [
        .iOS(.v11),
        .tvOS(.v11),
        .macOS(.v10_11),
    ],
    products: [
        .library(
            name: "Charts",
            targets: ["Charts"]
        ),
        .library(
            name: "ChartsDynamic",
            type: .dynamic,
            targets: ["Charts"]
        ),
    ],
    dependencies: [
        .package(url: "https://github.com/apple/swift-algorithms", .branch("main")),
        .package(name: "SnapshotTesting", url: "https://github.com/pointfreeco/swift-snapshot-testing.git", from: "1.8.1"),
    ],
    targets: [
        .target(
            name: "Charts",
            dependencies: [.product(name: "Algorithms", package: "swift-algorithms")]
        ),
        .testTarget(
            name: "ChartsTests",
            dependencies: ["Charts", "SnapshotTesting"],
            exclude: ["__Snapshots__Silicon__", "__Snapshots__x86__"],
            resources: [
                .process("Resources")
            ]
        )
    ],
    swiftLanguageVersions: [.v5]
)


import PackageDescription

let package = Package(
  name: "JWT",
  dependencies: [
    .Package(url: "https://github.com/krzyzanowskim/CryptoSwift", versions: Version(0, 6, 1) ..< Version(0, 7, 0)),
  ],
  exclude: ["Sources/HMACCommonCrypto.swift"]
)

Use CommonCrypto on Apple platforms for SwiftPM

import PackageDescription

#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
let package = Package(
  name: "JWT",
  dependencies: [
    .Package(url: "https://github.com/kylef-archive/CommonCrypto.git", majorVersion: 1),
  ],
  exclude: [
    "Sources/HMACCryptoSwift.swift",
  ]
)
#else
let package = Package(
  name: "JWT",
  dependencies: [
    .Package(url: "https://github.com/krzyzanowskim/CryptoSwift", majorVersion: 0, minor: 6),
  ],
  exclude: [
    "Sources/HMACCommonCrypto.swift",
  ]
)
#endif


//
//  Copyright © 2018 Ingresse. All rights reserved.
//

extension Request {
    public struct Shop: Encodable {
        public struct Create: Encodable {
            public var userId: String = ""
            public var eventId: String = ""
            public var passkey: String?
            public var tickets: [PaymentTicket] = []

            public init() {}
        }

        public struct CreditCard: Encodable {
            public var number: String = ""
            public var holderName: String = ""
            public var expiracyMonth: String = ""
            public var expiracyYear: String = ""
            public var cvv: String = ""
            public var birthDate: String = ""

            public init() {}
        }

        public struct Free: Encodable {
            public var userId: String = ""
            public var eventId: String = ""
            public var transactionId: String = ""
            public var document: String = ""
            public var postback: String = ""
            public var ingeprefsPayload: String = ""

            public init() {}
        }

        public struct Payment: Encodable {
            public var userId: String = ""
            public var eventId: String = ""
            public var transactionId: String = ""
            public var creditcard: CreditCard?
            public var installments: Int = 0
            public var paymentMethod: String = ""
            public var document: String = ""
            public var postback: String = ""
            public var ingeprefsPayload: String = ""
            public var source: String = "mobile"
            public var hdim: String = ""

            public init() {}
        }
    }
}

Add save on payment request

//
//  Copyright © 2018 Ingresse. All rights reserved.
//

extension Request {
    public struct Shop: Encodable {
        public struct Create: Encodable {
            public var userId: String = ""
            public var eventId: String = ""
            public var passkey: String?
            public var tickets: [PaymentTicket] = []

            public init() {}
        }

        public struct CreditCard: Encodable {
            public var number: String = ""
            public var holderName: String = ""
            public var expiracyMonth: String = ""
            public var expiracyYear: String = ""
            public var cvv: String = ""
            public var birthDate: String = ""

            public init() {}
        }

        public struct Free: Encodable {
            public var userId: String = ""
            public var eventId: String = ""
            public var transactionId: String = ""
            public var document: String = ""
            public var postback: String = ""
            public var ingeprefsPayload: String = ""

            public init() {}
        }

        public struct Payment: Encodable {
            public var userId: String = ""
            public var eventId: String = ""
            public var transactionId: String = ""
            public var creditcard: CreditCard?
            public var installments: Int = 0
            public var paymentMethod: String = ""
            public var document: String = ""
            public var postback: String = ""
            public var ingeprefsPayload: String = ""
            public var source: String = "mobile"
            public var hdim: String = ""
            public var save: Bool = false

            public init() {}
        }
    }
}


public func >>-<A, B>(a: A?, f: A -> B?) -> B? {
  if let x = a {
    return f(x)
  } else {
    return .None
  }
}

public func <^><A, B>(f: A -> B, a: A?) -> B? {
  if let x = a {
    return f(x)
  } else {
    return .None
  }
}

public func <*><A, B>(f: (A -> B)?, a: A?) -> B? {
  if let fx = f {
    return fx <^> a
  }
  return .None
}

Use switch statements for functional operators

public func >>-<A, B>(a: A?, f: A -> B?) -> B? {
  switch a {
  case let .Some(x): return f(x)
  default: return .None
  }
}

public func <^><A, B>(f: A -> B, a: A?) -> B? {
  switch a {
  case let .Some(x): return f(x)
  default: return .None
  }
}

public func <*><A, B>(f: (A -> B)?, a: A?) -> B? {
  switch f {
  case let .Some(fx): return fx <^> a
  default: return .None
  }
}


//
//  102_BinaryTreeLevelOrderTraversal.swift
//  HRSwift
//
//  Created by yansong li on 2016-08-04.
//  Copyright © 2016 yansong li. All rights reserved.
//

import Foundation

/**
  Swift Knowledge:

  Queue, Array

  Algorithem Knowledge:

  BFS
 */

/**
  102. Binary Tree Level Order Traversal
  https://leetcode.com/problems/binary-tree-level-order-traversal/
 */

class BinaryTreeLevelOrderTraversal_Solution {
  func levelOrder(_ root: TreeNode?) -> [[Int]] {
    guard let root = root else {
      return []
    }
    var queue = Queue<(TreeNode, Int)>()
    var ans: [[Int]] = [[]]
    queue.enqueue((root, 1))
    while !queue.isEmpty() {
      let (currentNode, currentlevel) = queue.dequeue()!
      if ans.count == currentlevel {
        var lastLevelNodes = ans.removeLast()
        lastLevelNodes.append(currentNode.val)
        ans.append(lastLevelNodes)
      } else if ans.count < currentlevel {
        let newLevelNodes = [currentNode.val];
        ans.append(newLevelNodes)
      }
      if let left = currentNode.left {
        queue.enqueue((left, currentlevel + 1))
      }
      if let right = currentNode.right {
        queue.enqueue((right, currentlevel + 1))
      }
    }
    return ans
  }
}

Update 102 Binary Tree Level Order Traversal.

//
//  102_BinaryTreeLevelOrderTraversal.swift
//  HRSwift
//
//  Created by yansong li on 2016-08-04.
//  Copyright © 2016 yansong li. All rights reserved.
//

import Foundation

/**
  Swift Knowledge:

  Queue, Array

  Algorithem Knowledge:

  BFS
 */

/**
  102. Binary Tree Level Order Traversal
  https://leetcode.com/problems/binary-tree-level-order-traversal/
 */

class BinaryTreeLevelOrderTraversal_Solution {
  func levelOrder(_ root: TreeNode?) -> [[Int]] {
    guard let node = root else {
        return []
    }
    var result: [[Int]] = []
    var queue = Queue<(TreeNode, Int)>()
    queue.enqueue((node, 0))
    while !queue.isEmpty() {
        let (currentNode, currentLevel) = queue.dequeue()!
        if currentLevel >= result.count {
            result.append([])
        }
        result[currentLevel].append(currentNode.val)
        if let left = currentNode.left {
            queue.enqueue((left, currentLevel + 1))
        }
        if let right = currentNode.right {
            queue.enqueue((right, currentLevel + 1))
        }
    }
    return result
  }
}


import PackageDescription

let package = Package(
    name: "AppIcon",
    targets: [
        Target(
            name: "AppIcon",
            dependencies: ["AppIconCore"]
        ),
        Target(name: "AppIconCore")
    ],
    dependencies: [
        .Package(url: "https://github.com/kylef/Commander", majorVersion: 0),
        .Package(url: "https://github.com/kareman/SwiftShell.git", "3.0.0"),
        .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1,0,0)..<Version(3, .max, .max))
    ]
)

Fix comma-spacing on version string.

import PackageDescription

let package = Package(
    name: "AppIcon",
    targets: [
        Target(
            name: "AppIcon",
            dependencies: ["AppIconCore"]
        ),
        Target(name: "AppIconCore")
    ],
    dependencies: [
        .Package(url: "https://github.com/kylef/Commander", majorVersion: 0),
        .Package(url: "https://github.com/kareman/SwiftShell.git", "3.0.0"),
        .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1, 0, 0)..<Version(3, .max, .max))
    ]
)


/**
 * Copyright IBM Corporation 2016
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

import PackageDescription

let package = Package(
    name: "Kitura",
    dependencies: [
        .Package(url: "https://github.com/IBM-Swift/Kitura-net.git", majorVersion: 0, minor: 25),
        .Package(url: "https://github.com/IBM-Swift/SwiftyJSON.git", majorVersion: 10, minor: 1),
        .Package(url: "https://github.com/IBM-Swift/Kitura-TemplateEngine.git", majorVersion: 0, minor: 16)
    ],
    exclude: ["Configuration", "Scripts"]
)

Use version 11 of SwiftyJSON

/**
 * Copyright IBM Corporation 2016
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

import PackageDescription

let package = Package(
    name: "Kitura",
    dependencies: [
        .Package(url: "https://github.com/IBM-Swift/Kitura-net.git", majorVersion: 0, minor: 25),
        .Package(url: "https://github.com/IBM-Swift/SwiftyJSON.git", majorVersion: 11),
        .Package(url: "https://github.com/IBM-Swift/Kitura-TemplateEngine.git", majorVersion: 0, minor: 16)
    ],
    exclude: ["Configuration", "Scripts"]
)


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

import PackageDescription

let package = Package(
    name: "Criollo",
    platforms: [
        .iOS(.v12),
        .macOS(.v10_10),
        .tvOS(.v12)
    ],
    products: [
        .library(
            name: "Criollo",
            type: .dynamic,
            targets: ["Criollo"]),
    ],
    dependencies: [
        .package(name:"CocoaAsyncSocket", url: "https://github.com/robbiehanson/CocoaAsyncSocket", from: "7.6.5"),
    ],
    targets: [
        .target(
            name: "Criollo",
            dependencies: [
                "CocoaAsyncSocket"
            ],
            path: "Criollo",
            exclude: [
                "../Libraries",
                "../Apps",
                "../Criollo.podspec"
            ],
            publicHeadersPath: "includes",
            cSettings: [
                .headerSearchPath("Source"),
                .headerSearchPath("Source/Extensions"),
                .headerSearchPath("Source/FCGI"),
                .headerSearchPath("Source/HTTP"),
                .headerSearchPath("Source/Routing"),
            ]
        ),

        .testTarget(name: "CriolloTests",
                    dependencies: ["Criollo"],
                    path: "CriolloTests"),
    ]
)

Remove explicit type of generated library in Swift package

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

import PackageDescription

let package = Package(
    name: "Criollo",
    platforms: [
        .iOS(.v12),
        .macOS(.v10_10),
        .tvOS(.v12)
    ],
    products: [
        .library(name: "Criollo",
                 targets: ["Criollo"]),
    ],
    dependencies: [
        .package(name:"CocoaAsyncSocket", url: "https://github.com/robbiehanson/CocoaAsyncSocket", from: "7.6.5"),
    ],
    targets: [
        .target(
            name: "Criollo",
            dependencies: [
                "CocoaAsyncSocket"
            ],
            path: "Criollo",
            exclude: [
                "../Libraries",
                "../Apps",
                "../Criollo.podspec"
            ],
            publicHeadersPath: "includes",
            cSettings: [
                .headerSearchPath("Source"),
                .headerSearchPath("Source/Extensions"),
                .headerSearchPath("Source/FCGI"),
                .headerSearchPath("Source/HTTP"),
                .headerSearchPath("Source/Routing"),
            ]
        ),

        .testTarget(name: "CriolloTests",
                    dependencies: ["Criollo"],
                    path: "CriolloTests"),
    ]
)


import Foundation

final class TalkPageViewModel {

    // MARK: - Properties

    private let pageTitle: String
    private let siteURL: URL

    // MARK: - Lifecycle

    init(pageTitle: String, siteURL: URL) {
        self.pageTitle = pageTitle
        self.siteURL = siteURL
    }

    convenience init?(siteURL: URL) {
        guard let pageTitle = siteURL.wmf_title, let siteURL = siteURL.wmf_site else {
            return nil
        }

        self.init(pageTitle: pageTitle, siteURL: siteURL)
    }

    // MARK: - Public

}

Update view model with sample data to populate header.

import Foundation

final class TalkPageViewModel {

    // MARK: - Nested Types

    enum PageType {
        case article
        case user
    }

    // MARK: - Properties

    private let pageTitle: String
    private let siteURL: URL

    // TODO: - Populate from data controller
    var pageType = PageType.user
    let talkPageTitle: String = "Page title"
    var description: String? = "This is the page description"
    var leadImage: UIImage? = UIImage(systemName: "text.bubble.fill")
    var coffeeRollText: NSAttributedString? = NSAttributedString(string: "This is the coffee roll")
    var projectSourceImage: UIImage? = UIImage(named: "notifications-project-mediawiki")
    var projectLanguage: String? = "EN"

    // MARK: - Lifecycle

    init(pageTitle: String, siteURL: URL) {
        self.pageTitle = pageTitle
        self.siteURL = siteURL
    }

    convenience init?(siteURL: URL) {
        guard let pageTitle = siteURL.wmf_title, let siteURL = siteURL.wmf_site else {
            return nil
        }

        self.init(pageTitle: pageTitle, siteURL: siteURL)
    }

    // MARK: - Public

}


import UIKit
import XCTest
import Aldo

class Tests: XCTestCase {

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

        Aldo.setHostAddress(address: "https://expeditionmundus.herokuapp.com")
    }

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

    func testRequestAuthToken() {
//        let exp: XCTestExpectation = expectation(description: "First Time Auth Token Request")
//
//        let callback: MockCallback = MockCallback(expectation: exp)
//        Aldo.requestAuthToken(callback: callback)
//
//        self.waitForExpectations(timeout: 10) { error in
//            XCTAssertNil(error, "Something went horribly wrong")
//            XCTAssertEqual(callback.getResponseCode(), 401)
//            XCTAssertEqual(callback.getResponse(), [:])
//        }
    }

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

}

public class MockCallback: Callback {

    private var expectation: XCTestExpectation

    private var responseCode: Int
    private var response: NSDictionary

    public init(expectation: XCTestExpectation) {
        self.expectation = expectation
        self.responseCode = 401
        self.response = [:]
    }

    public func onResponse(responseCode: Int, response: NSDictionary) {
        self.responseCode = responseCode
        self.response = response

        expectation.fulfill()
    }

    public func getResponseCode() -> Int {
        return responseCode
    }

    public func getResponse() -> NSDictionary {
        return response
    }

}

Add first 2 tests in the test suite.

import UIKit
import XCTest

class Tests: XCTestCase {

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

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

    func testAldoHostSetup() {
        let address: String = "127.0.0.1"
        let port: Int = 8000
        MockAldo.setHostAddress(address: address, port: port)

        XCTAssertEqual(MockAldo.getHostAddress(), address)
        XCTAssertEqual(MockAldo.getPort(), port)
    }

    func testAldoHostSetupWithoutPort() {
        let address: String = "127.0.0.1"
        let port: Int = 4567
        MockAldo.setHostAddress(address: address)

        XCTAssertEqual(MockAldo.getHostAddress(), address)
        XCTAssertEqual(MockAldo.getPort(), port)
    }
}


//
//  StringExtensionTests.swift
//  Base32
//
//  Created by 野村 憲男 on 2/7/15.
//  Copyright (c) 2015 Norio Nomura. All rights reserved.
//

import Cocoa
import XCTest

class StringExtensionTests: XCTestCase {

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

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

    func test_dataUsingUTF8StringEncoding() {
        let emptyString = ""
        XCTAssertEqual(emptyString.dataUsingUTF8StringEncoding, emptyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)

        let string = "0112233445566778899AABBCCDDEEFFaabbccddeefff"
        XCTAssertEqual(string.dataUsingUTF8StringEncoding, string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
    }
}

Fix iOS Simulator test failing.

//
//  StringExtensionTests.swift
//  Base32
//
//  Created by 野村 憲男 on 2/7/15.
//  Copyright (c) 2015 Norio Nomura. All rights reserved.
//

import Foundation
import XCTest

class StringExtensionTests: XCTestCase {

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

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

    func test_dataUsingUTF8StringEncoding() {
        let emptyString = ""
        XCTAssertEqual(emptyString.dataUsingUTF8StringEncoding, emptyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)

        let string = "0112233445566778899AABBCCDDEEFFaabbccddeefff"
        XCTAssertEqual(string.dataUsingUTF8StringEncoding, string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
    }
}


//
//  FullRXRViewController.swift
//  RexxarDemo
//
//  Created by GUO Lin on 8/19/16.
//  Copyright © 2016 Douban.Inc. All rights reserved.
//

import UIKit

class FullRXRViewController: RXRViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.white

    // Widgets
    let pullRefreshWidget = RXRPullRefreshWidget()
    let titleWidget = RXRNavTitleWidget()
    let alertDialogWidget = RXRAlertDialogWidget()
    let toastWidget = RXRToastWidget()
    let navMenuWidget = RXRNavMenuWidget()
    widgets = [titleWidget, alertDialogWidget, pullRefreshWidget, toastWidget, navMenuWidget]

    // ContainerAPIs
    let geoContainerAPI = RXRGeoContainerAPI()
    let logContainerAPI = RXRLogContainerAPI()
    RXRContainerInterceptor.setContainerAPIs([geoContainerAPI, logContainerAPI])
    //URLProtocol.registerClass(RXRContainerInterceptor.self)
    let _  = RXRContainerInterceptor.register()

    // Decorators
    let headers = ["Customer-Authorization": "Bearer token"]
    let parameters = ["apikey": "apikey value"]
    let requestDecorator = RXRRequestDecorator(headers: headers, parameters: parameters)
    RXRRequestInterceptor.setDecorators([requestDecorator])
    URLProtocol.registerClass(RXRRequestInterceptor.self)
  }

  deinit {
    //URLProtocol.unregisterClass(RXRContainerInterceptor.self)
    RXRContainerInterceptor.unregisterInterceptor()

    URLProtocol.unregisterClass(RXRRequestInterceptor.self)
  }
}

Update demo to use the interceptor's new interface

//
//  FullRXRViewController.swift
//  RexxarDemo
//
//  Created by GUO Lin on 8/19/16.
//  Copyright © 2016 Douban.Inc. All rights reserved.
//

import UIKit

class FullRXRViewController: RXRViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.white

    // Widgets
    let pullRefreshWidget = RXRPullRefreshWidget()
    let titleWidget = RXRNavTitleWidget()
    let alertDialogWidget = RXRAlertDialogWidget()
    let toastWidget = RXRToastWidget()
    let navMenuWidget = RXRNavMenuWidget()
    widgets = [titleWidget, alertDialogWidget, pullRefreshWidget, toastWidget, navMenuWidget]

    // ContainerAPIs
    let geoContainerAPI = RXRGeoContainerAPI()
    let logContainerAPI = RXRLogContainerAPI()
    RXRContainerInterceptor.setContainerAPIs([geoContainerAPI, logContainerAPI])
    let _  = RXRContainerInterceptor.register()

    // Decorators
    let headers = ["Customer-Authorization": "Bearer token"]
    let parameters = ["apikey": "apikey value"]
    let requestDecorator = RXRRequestDecorator(headers: headers, parameters: parameters)
    RXRRequestInterceptor.setDecorators([requestDecorator])
    URLProtocol.registerClass(RXRRequestInterceptor.self)
    let _ = RXRRequestInterceptor.register()
  }

  deinit {
    RXRContainerInterceptor.unregisterInterceptor()
    RXRRequestInterceptor.unregisterInterceptor()
  }
}


import Foundation

class StringInterpolator {

    private static let regularExpression = try! NSRegularExpression(pattern: "\\%\\{[^\\}]*\\}", options: []) // swiftlint:disable:this force_try

    /// Input string is in format: "You have %{count} unread messages".
    /// The function finds all placeholders and replaces them with a value specified in interpolations dictionary
    func interpolate(_ rawString: String, with interpolations: [String: Any]) -> String {
        var result = rawString

        let matches = StringInterpolator.regularExpression.matches(in: rawString, options: [], range: NSRange.init(location: 0, length: rawString.characters.count))

        for match in matches {
            let range: NSRange = match.rangeAt(0)

            // Extract whole capture group string. Will contain string like: "%{count}"
            let startIndex = rawString.index(rawString.startIndex, offsetBy: range.location)
            let endIndex = rawString.index(startIndex, offsetBy: range.length)
            let matchedString = rawString.substring(with: Range(uncheckedBounds: (lower: startIndex, upper: endIndex)))

            // Extract the key from `matchedString`. Will contain string like: "count"
            let keyStartIndex = matchedString.index(matchedString.startIndex, offsetBy: 2)
            let keyEndIndex = matchedString.index(before: matchedString.endIndex)
            let key = matchedString.substring(with: Range(uncheckedBounds: (lower: keyStartIndex, upper: keyEndIndex)))

            if let interpolation = interpolations[key] {
                result = result.replacingOccurrences(of: matchedString, with: "\(interpolation)")
            }
        }

        return result
    }

}

Use NSRange.range instead of rangeAt() as it is not available on linux

import Foundation

class StringInterpolator {

    private static let regularExpression = try! NSRegularExpression(pattern: "\\%\\{[^\\}]*\\}", options: []) // swiftlint:disable:this force_try

    /// Input string is in format: "You have %{count} unread messages".
    /// The function finds all placeholders and replaces them with a value specified in interpolations dictionary
    func interpolate(_ rawString: String, with interpolations: [String: Any]) -> String {
        var result = rawString

        let matches = StringInterpolator.regularExpression.matches(in: rawString, options: [], range: NSRange.init(location: 0, length: rawString.characters.count))

        for match in matches {
            let range: NSRange = match.range

            // Extract whole capture group string. Will contain string like: "%{count}"
            let startIndex = rawString.index(rawString.startIndex, offsetBy: range.location)
            let endIndex = rawString.index(startIndex, offsetBy: range.length)
            let matchedString = rawString.substring(with: Range(uncheckedBounds: (lower: startIndex, upper: endIndex)))

            // Extract the key from `matchedString`. Will contain string like: "count"
            let keyStartIndex = matchedString.index(matchedString.startIndex, offsetBy: 2)
            let keyEndIndex = matchedString.index(before: matchedString.endIndex)
            let key = matchedString.substring(with: Range(uncheckedBounds: (lower: keyStartIndex, upper: keyEndIndex)))

            if let interpolation = interpolations[key] {
                result = result.replacingOccurrences(of: matchedString, with: "\(interpolation)")
            }
        }

        return result
    }

}


import UIKit
import XCTest
import ViewAnimator

class Tests: XCTestCase {

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

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

    func testPreservesTransform() {
        let view = UIView()
        let preTransform = CGAffineTransform(rotationAngle: 3.14)
        view.transform = preTransform

        let zoom = AnimationType.zoom(scale: 2.5)
        let translate = AnimationType.from(direction: .bottom, offset: 50)

        let animationCompleteExpectation = expectation(description: "Animate with multiple transforms")

        view.animate(animations: [zoom, translate]) {
            animationCompleteExpectation.fulfill()
            XCTAssert(view.transform == preTransform)
        }

        waitForExpectations(timeout: 1.0, handler: nil)
    }

}

Test the end transform is set correctly on a reversed animation

import UIKit
import XCTest
import ViewAnimator

class Tests: XCTestCase {

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

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

    func testPreservesTransform() {
        let view = UIView()
        let preTransform = CGAffineTransform(rotationAngle: 3.14)
        view.transform = preTransform

        let zoom = AnimationType.zoom(scale: 2.5)
        let translate = AnimationType.from(direction: .bottom, offset: 50)

        let animationCompleteExpectation = expectation(description: "Animate with multiple transforms")

        view.animate(animations: [zoom, translate]) {
            animationCompleteExpectation.fulfill()
            XCTAssert(view.transform == preTransform)
        }

        waitForExpectations(timeout: 1.0, handler: nil)
    }

    func testTransformOnReverse() {
        let view = UIView()

        let rotate = AnimationType.rotate(angle: CGFloat.pi)
        let translate = AnimationType.from(direction: .right, offset: 20)
        let animations = [rotate, translate]

        var expectedTransform = view.transform
        animations.forEach { expectedTransform = expectedTransform.concatenating($0.initialTransform) }

        let animationCompleteExpectation = expectation(description: "Animate with multiple transforms")

        view.animate(animations: animations, reversed: true) {
            animationCompleteExpectation.fulfill()
            XCTAssert(view.transform == expectedTransform)
        }

        waitForExpectations(timeout: 1.0, handler: nil)
    }

}


//
// StringExtensions.swift
// Iconizer
// https://github.com/raphaelhanneken/iconizer
//

import Cocoa

extension String {

    /// The substring containing the characters between the supplied start and
    /// the supplied end strings. Excluding both.
    ///
    /// - Parameters:
    ///   - start: The starting point.
    ///   - end: The ending point.
    /// - Returns: The substring from the start to the end string or nil when either string weren't found.
    func substringFrom(start: String, to end: String) -> String? {
        // Return nil in case either the given start or end string doesn't exist.
        guard let startIndex = self.range(of: start), let endIndex = self.range(of: end) else {
            return nil
        }

        return substring(with: Range(startIndex.upperBound ..< endIndex.lowerBound))
    }
}

Replace substring with new slice subscript

//
// StringExtensions.swift
// Iconizer
// https://github.com/raphaelhanneken/iconizer
//

import Cocoa

extension String {

    /// The substring containing the characters between the supplied start and
    /// the supplied end strings. Excluding both.
    ///
    /// - Parameters:
    ///   - start: The starting point.
    ///   - end: The ending point.
    /// - Returns: The substring from the start to the end string or nil when either string weren't found.
    func substringFrom(start: String, to end: String) -> String? {
        // Return nil in case either the given start or end string doesn't exist.
        guard let startIndex = self.range(of: start), let endIndex = self.range(of: end) else {
            return nil
        }

        return String(self[startIndex.upperBound ..< endIndex.lowerBound])
    }
}


// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "Predicate",
    products: [
        .library(
            name: "Predicate",
            targets: [
                "Predicate"
            ]
        )
    ],
    targets: [
        .target(
            name: "Predicate",
            path: "./Sources"
        ),
        .testTarget(
            name: "PredicateTests",
            dependencies: [
                "Predicate"
            ]
        )
    ]
)

Build as dynamic library on Linux

// swift-tools-version:5.0
import PackageDescription

#if os(Linux)
let libraryType: PackageDescription.Product.Library.LibraryType = .dynamic
#else
let libraryType: PackageDescription.Product.Library.LibraryType = .static
#endif

let package = Package(
    name: "Predicate",
    products: [
        .library(
            name: "Predicate",
            type: libraryType,
            targets: [
                "Predicate"
            ]
        )
    ],
    targets: [
        .target(
            name: "Predicate",
            path: "./Sources"
        ),
        .testTarget(
            name: "PredicateTests",
            dependencies: [
                "Predicate"
            ]
        )
    ]
)


import PackageDescription

let package = Package(
    name: "ToDoRedux"
)

Add TDRedux as a dependency

import PackageDescription

let package = Package(
    name: "ToDoRedux",
    dependencies: [
        .Package(url: "https://github.com/NicholasTD07/TDRedux.swift.git",
                 majorVersion: 2),
    ]
)


import Foundation
import WMF

extension PictureOfTheDayWidget {

	enum LocalizedStrings {
		static let widgetTitle = WMFLocalizedString("potd-widget-title", value:"Picture of the day", comment: "Text for title of Picture of the day widget.")
		static let widgetDescription = WMFLocalizedString("potd-widget-description", value:"Enjoy a beautiful daily photo selected by our community.", comment: "Text for description of Picture of the day widget displayed when adding to home screen.")
		static let sampleEntryDescription = WMFLocalizedString("potd-widget-description", value:"Two bulls running while the jockey holds on to them in pacu jawi (from Minangkabau, \"bull race\"), a traditional bull race in Tanah Datar, West Sumatra, Indonesia. 2015, Final-45.", comment: "Text for sample entry image caption. It is displayed when we we are unable to fetch Picture of the Day data.")
	}

}

Rename localized string key for sample entry description.

import Foundation
import WMF

extension PictureOfTheDayWidget {

	enum LocalizedStrings {
		static let widgetTitle = WMFLocalizedString("potd-widget-title", value:"Picture of the day", comment: "Text for title of Picture of the day widget.")
		static let widgetDescription = WMFLocalizedString("potd-widget-description", value:"Enjoy a beautiful daily photo selected by our community.", comment: "Text for description of Picture of the day widget displayed when adding to home screen.")
		static let sampleEntryDescription = WMFLocalizedString("potd-sample-entry-description", value:"Two bulls running while the jockey holds on to them in pacu jawi (from Minangkabau, \"bull race\"), a traditional bull race in Tanah Datar, West Sumatra, Indonesia. 2015, Final-45.", comment: "Text for sample entry image caption. It is displayed when we we are unable to fetch Picture of the day data.")
	}

}


import Darwin

struct InvocationError : ErrorType {
  init(command:String, arguments:[String], code:Int32) {

  }
}

/// Invoke a subprocess
func invoke(command:String, _ arguments:[String]) throws {
  // TODO - Properly invoke subprocess with exec, arguments are not escaped
  let args = arguments.joinWithSeparator(" ")

  let code = system("\(command) \(args)")

  if code != 0 {
    throw InvocationError(command: command, arguments: arguments, code: code)
  }
}

func swiftc(arguments: [String]) throws {
  try invoke("swiftc", arguments)
}

Allow setting SWIFTC env variable

import Darwin

struct InvocationError : ErrorType {
  init(command:String, arguments:[String], code:Int32) {

  }
}

/// Invoke a subprocess
func invoke(command:String, _ arguments:[String]) throws {
  // TODO - Properly invoke subprocess with exec, arguments are not escaped
  let args = arguments.joinWithSeparator(" ")

  let code = system("\(command) \(args)")

  if code != 0 {
    throw InvocationError(command: command, arguments: arguments, code: code)
  }
}

func swiftc(arguments: [String]) throws {
  let swiftc = String.fromCString(getenv("SWIFTC")) ?? "swiftc"
  try invoke(swiftc, arguments)
}


import Foundation

public extension Date {
    public static func startOfMonth() -> Date? {
        return Date().startOfMonth()
    }

    public static func endOfMonth() -> Date? {
        return Date().endOfMonth()
    }

    public func startOfMonth() -> Date? {
        return Calendar.current.date(
            from: Calendar.current.dateComponents([.year, .month],
            from: Calendar.current.startOfDay(for: self))
        )
    }

    public func endOfMonth() -> Date? {
        guard let startOfMonth = self.startOfMonth() else { return nil }
        return Calendar.current.date(
            byAdding: DateComponents(month: 1, day: -1),
            to: startOfMonth
        )
    }

    public func add(days: Int) -> Date? {
        return Calendar.current.date(
            byAdding: DateComponents(day: days),
            to: self
        )
    }

    public func sub(days: Int) -> Date? {
        return Calendar.current.date(
            byAdding: DateComponents(day: -days),
            to: self
        )
    }
}

Add dateBySetting(hour,min,sec) to sugar 3

import Foundation

public extension Date {

    static let hourInSec = 3600
    static let minInSec = 60

    public static func startOfMonth() -> Date? {
        return Date().startOfMonth()
    }

    public static func endOfMonth() -> Date? {
        return Date().endOfMonth()
    }

    public func startOfMonth() -> Date? {
        return Calendar.current.date(
            from: Calendar.current.dateComponents([.year, .month],
            from: Calendar.current.startOfDay(for: self))
        )
    }

    public func endOfMonth() -> Date? {
        guard let startOfMonth = self.startOfMonth() else { return nil }
        return Calendar.current.date(
            byAdding: DateComponents(month: 1, day: -1),
            to: startOfMonth
        )
    }

    public func add(days: Int) -> Date? {
        return Calendar.current.date(
            byAdding: DateComponents(day: days),
            to: self
        )
    }

    public func sub(days: Int) -> Date? {
        return Calendar.current.date(
            byAdding: DateComponents(day: -days),
            to: self
        )
    }

    /// Set hour/min/sec of a date
    ///
    /// Replaces `Calendar().date(bySettingHour hour: Int, minute: Int, ...)` which is not
    /// running on Linux yet.
    ///
    /// - Parameters:
    ///   - hour: Int
    ///   - minute: Int
    ///   - second: Int
    /// - Returns: Date?
    public func dateBySetting(hour: Int, minute: Int, second: Int) -> Date? {

        let dateComponents = Calendar.current.dateComponents([.year, .month, .day], from: self)
        guard let date = Calendar.current.date(from: dateComponents) else { return nil }
        return date.addingTimeInterval(TimeInterval(hour * Date.hourInSec + minute * Date.minInSec + second))
    }
}


//
//  WebViewCell.swift
//  Rover
//
//  Created by Sean Rucker on 2017-08-17.
//  Copyright © 2017 Rover Labs Inc. All rights reserved.
//

import WebKit

class WebViewCell: BlockCell {
    let webView = WKWebView()

    override var content: UIView? {
        return webView
    }

    override func configure(with block: Block) {
        super.configure(with: block)

        guard let webViewBlock = block as? WebViewBlock else {
            self.webView.isHidden = true
            return
        }

        self.webView.isHidden = false

        let webView = webViewBlock.webView
        self.webView.isOpaque = false
        self.webView.backgroundColor = .clear
        self.webView.scrollView.backgroundColor = .clear
        self.webView.scrollView.isScrollEnabled = webView.isScrollingEnabled
        self.webView.scrollView.bounces = webView.isScrollingEnabled
        let request = URLRequest(url: webView.url)
        self.webView.load(request)
    }
}

Enable inline video in WebViews

//
//  WebViewCell.swift
//  Rover
//
//  Created by Sean Rucker on 2017-08-17.
//  Copyright © 2017 Rover Labs Inc. All rights reserved.
//

import WebKit

class WebViewCell: BlockCell {
    let webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration.roverDefault)

    override var content: UIView? {
        return webView
    }

    override func configure(with block: Block) {
        super.configure(with: block)

        guard let webViewBlock = block as? WebViewBlock else {
            self.webView.isHidden = true
            return
        }

        self.webView.isHidden = false

        let webView = webViewBlock.webView
        self.webView.isOpaque = false
        self.webView.backgroundColor = .clear
        self.webView.scrollView.backgroundColor = .clear
        self.webView.scrollView.isScrollEnabled = webView.isScrollingEnabled
        self.webView.scrollView.bounces = webView.isScrollingEnabled
        let request = URLRequest(url: webView.url)
        self.webView.load(request)
    }
}

extension WKWebViewConfiguration {
    static var roverDefault: WKWebViewConfiguration {
        let config = WKWebViewConfiguration()
        config.allowsInlineMediaPlayback = true
        config.mediaTypesRequiringUserActionForPlayback = []
        return config
    }
}


import AVFoundation

public class AudioPlayer {

  enum Error: ErrorType {
    case SoundNotFound
  }

  public let theme: Theme
  var player: AVAudioPlayer?

  var session: AVAudioSession {
    return AVAudioSession.sharedInstance()
  }

  // MARK: - Initialization

  public init(theme: Theme) {
    self.theme = theme
  }

  // MARK: - Start playback

  public func play(sound: Sound) throws {
    try session.setCategory(AVAudioSessionCategoryPlayback)
    try session.setActive(true)

    let bundle = NSBundle.mainBundle()

    guard let path = bundle.pathForResource(sound.rawValue, ofType: "aiff") else {
      throw Error.SoundNotFound
    }

    let URL = NSURL(fileURLWithPath: path)

    if player?.playing == true {
      stop()
    }

    player = try AVAudioPlayer(contentsOfURL: URL)
    player?.prepareToPlay()
    player?.play()
  }

  public func playSafely(sound: Sound) {
    do {
      try play(sound)
    } catch {}
  }

  public func resume() {
    guard let player = player where !player.playing else {
      return
    }

    player.play()
  }

  // MARK: - Stop playback

  public func stop() {
    player?.stop()
    player?.currentTime = 0
    player = nil
  }

  public func pause() {
    guard let player = player where player.playing else {
      return
    }

    player.pause()
  }
}

Use theme bundle to load a sound

import AVFoundation

public class AudioPlayer {

  enum Error: ErrorType {
    case SoundNotFound
    case ThemeBundleNotFound
  }

  public let theme: Theme
  var player: AVAudioPlayer?

  var session: AVAudioSession {
    return AVAudioSession.sharedInstance()
  }

  // MARK: - Initialization

  public init(theme: Theme) {
    self.theme = theme
  }

  // MARK: - Start playback

  public func play(sound: Sound) throws {
    try session.setCategory(AVAudioSessionCategoryPlayback)
    try session.setActive(true)

    let mainBundle = NSBundle.mainBundle()

    guard let bundleURL = mainBundle.URLForResource(theme.rawValue, withExtension: "bundle"),
      bundle = NSBundle(URL: bundleURL) else {
        throw Error.ThemeBundleNotFound
    }

    guard let path = bundle.pathForResource(sound.rawValue, ofType: "aiff") else {
      throw Error.SoundNotFound
    }

    let URL = NSURL(fileURLWithPath: path)

    if player?.playing == true {
      stop()
    }

    player = try AVAudioPlayer(contentsOfURL: URL)
    player?.prepareToPlay()
    player?.play()
  }

  public func playSafely(sound: Sound) {
    do {
      try play(sound)
    } catch {}
  }

  public func resume() {
    guard let player = player where !player.playing else {
      return
    }

    player.play()
  }

  // MARK: - Stop playback

  public func stop() {
    player?.stop()
    player?.currentTime = 0
    player = nil
  }

  public func pause() {
    guard let player = player where player.playing else {
      return
    }

    player.pause()
  }
}


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

import Foundation

public extension NSURL {
    public func buildURL(path pathOrNil: String?, parameters: [String:String]? = nil) -> NSURL? {
        if let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: true) {
            components.path = String.pathWithComponents([components.path ?? "", path ?? ""])
            components.parameters = parameters
            return components.URL
        } else {
            return nil
        }
    }
}

Stop using internal/external name as property name overrides it and prevents the code from working. Make components a var so that it can be modified (isn't it a reference type?).

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

import Foundation

public extension NSURL {
    public func buildURL(# path: String?, parameters: [String:String]? = nil) -> NSURL? {
        if var components = NSURLComponents(URL: self, resolvingAgainstBaseURL: true) {
            components.path = String.pathWithComponents([components.path ?? "", path ?? ""])
            components.parameters = parameters
            return components.URL
        } else {
            return nil
        }
    }
}


//
//  Created by Tom Baranes on 18/01/2017.
//  Copyright © 2017 Tom Baranes. All rights reserved.
//

import UIKit

public extension UITextField {

    public func setClearButton(with image: UIImage) {
        let clearButton = UIButton(type: .custom)
        clearButton.setImage(image, for: .normal)
        clearButton.frame = CGRect(origin: .zero, size: image.size)
        clearButton.contentMode = .left
        clearButton.addTarget(self, action: #selector(clear), for: .touchUpInside)
        clearButtonMode = .never

        rightView = clearButton
        rightViewMode = .whileEditing
    }

    func clear() {
        self.text = ""
    }

}

Send editingChanged when using UITextField setClearButton

//
//  Created by Tom Baranes on 18/01/2017.
//  Copyright © 2017 Tom Baranes. All rights reserved.
//

import UIKit

public extension UITextField {

    public func setClearButton(with image: UIImage) {
        let clearButton = UIButton(type: .custom)
        clearButton.setImage(image, for: .normal)
        clearButton.frame = CGRect(origin: .zero, size: image.size)
        clearButton.contentMode = .left
        clearButton.addTarget(self, action: #selector(clear), for: .touchUpInside)
        clearButtonMode = .never

        rightView = clearButton
        rightViewMode = .whileEditing
    }

    func clear() {
        self.text = ""
        self.sendActions(for: .editingChanged)
    }

}


//
//  S3+Delete.swift
//  S3
//
//  Created by Ondrej Rafaj on 11/05/2018.
//

import Foundation
import Vapor

// Helper S3 extension for deleting files by their URL/path
public extension S3 {

    // MARK: Delete

    /// Delete file from S3
    public func delete(file: LocationConvertible, headers: [String: String], on container: Container) throws -> Future<Void> {
        let builder = urlBuilder(for: container)
        let url = try builder.url(file: file)

        let headers = try signer.headers(for: .DELETE, urlString: url.absoluteString, headers: headers, payload: .none)
        return try make(request: url, method: .DELETE, headers: headers, data: emptyData(), on: container).map(to: Void.self) { response in
            try self.check(response)

            return Void()
        }
    }

    /// Delete file from S3
    public func delete(file: LocationConvertible, on container: Container) throws -> Future<Void> {
        return try delete(file: file, headers: [:], on: container)
    }

}

Disable cache for DELETE request

//
//  S3+Delete.swift
//  S3
//
//  Created by Ondrej Rafaj on 11/05/2018.
//

import Foundation
import Vapor

// Helper S3 extension for deleting files by their URL/path
public extension S3 {

    // MARK: Delete

    /// Delete file from S3
    public func delete(file: LocationConvertible, headers: [String: String], on container: Container) throws -> Future<Void> {
        let builder = urlBuilder(for: container)
        let url = try builder.url(file: file)

        let headers = try signer.headers(for: .DELETE, urlString: url.absoluteString, headers: headers, payload: .none)
        return try make(request: url, method: .DELETE, headers: headers, data: emptyData(), cachePolicy: .reloadIgnoringLocalCacheData, on: container).map(to: Void.self) { response in
            try self.check(response)

            return Void()
        }
    }

    /// Delete file from S3
    public func delete(file: LocationConvertible, on container: Container) throws -> Future<Void> {
        return try delete(file: file, headers: [:], on: container)
    }

}


//
//  NSBundle.swift
//  ZamzamKit
//
//  Created by Basem Emara on 3/4/16.
//  Copyright © 2016 Zamzam. All rights reserved.
//

import Foundation

public extension Bundle {

    /**
     Gets the contents of the specified file.

     - parameter file: Name of file to retrieve contents from.
     - parameter bundle: Bundle where defaults reside.
     - parameter encoding: Encoding of string from file.

     - returns: Contents of file.
     */
    func string(file: String, inDirectory: String? = nil, encoding: String.Encoding = .utf8) -> String? {
        guard let resourcePath = path(forResource: file, ofType: nil, inDirectory: inDirectory) else { return nil }
        return try? String(contentsOfFile: resourcePath, encoding: encoding)
    }

    /**
     Gets the contents of the specified plist file.

     - parameter plist: property list where defaults are declared
     - parameter bundle: bundle where defaults reside

     - returns: dictionary of values
     */
    func contents(plist: String, inDirectory: String? = nil) -> [String: Any] {
        guard let resourcePath = path(forResource: plist, ofType: nil, inDirectory: inDirectory),
            let contents = NSDictionary(contentsOfFile: resourcePath) as? [String: Any]
            else { return [:] }

        return contents
    }
}

Add static bundle for conveniently retrieving packaged resources

//
//  NSBundle.swift
//  ZamzamKit
//
//  Created by Basem Emara on 3/4/16.
//  Copyright © 2016 Zamzam. All rights reserved.
//

import Foundation

public extension Bundle {
    private class TempClassForBundle {}

    /// A representation of the code and resources stored in ZamzamKit bundle directory on disk.
    static var zamzamKit: Bundle {
        return Bundle(for: TempClassForBundle.self)
    }
}

public extension Bundle {

    /**
     Gets the contents of the specified file.

     - parameter file: Name of file to retrieve contents from.
     - parameter bundle: Bundle where defaults reside.
     - parameter encoding: Encoding of string from file.

     - returns: Contents of file.
     */
    func string(file: String, inDirectory: String? = nil, encoding: String.Encoding = .utf8) -> String? {
        guard let resourcePath = path(forResource: file, ofType: nil, inDirectory: inDirectory) else { return nil }
        return try? String(contentsOfFile: resourcePath, encoding: encoding)
    }

    /**
     Gets the contents of the specified plist file.

     - parameter plist: property list where defaults are declared
     - parameter bundle: bundle where defaults reside

     - returns: dictionary of values
     */
    func contents(plist: String, inDirectory: String? = nil) -> [String: Any] {
        guard let resourcePath = path(forResource: plist, ofType: nil, inDirectory: inDirectory),
            let contents = NSDictionary(contentsOfFile: resourcePath) as? [String: Any]
            else { return [:] }

        return contents
    }
}


class Async {
    private var _done: (() -> ())?

    class func map<U, T>(u: [U], f: U -> T) -> Async {
        var proc = Async()
        let queue = AsyncQueue(name: "PoppinsSyncQueue", maxOperations: 10)

        u.map { x in
            queue.addOperationWithBlock { _ = f(x) }
        }

        queue.finally { _ = proc._done?() }

        return proc
    }

    func done(f: () -> ()) {
        _done = f
    }
}

Move queue to global constant

private let queue = AsyncQueue(name: "PoppinsSyncQueue", maxOperations: 10)

class Async {
    private var _done: (() -> ())?

    class func map<U, T>(u: [U], f: U -> T) -> Async {
        var proc = Async()

        u.map { x in
            queue.addOperationWithBlock { _ = f(x) }
        }

        queue.finally { _ = proc._done?() }

        return proc
    }

    func done(f: () -> ()) {
        _done = f
    }
}


#!/usr/bin/env swift

#if os(Linux) || os(FreeBSD)
	import Glibc
#else
	import Darwin
#endif

var num_steps: Int = 1000000000

// Set up stuff for timing from Glibc.
// timeval is a Glibc structure.
var rettime:timeval = timeval(tv_sec: 0, tv_usec: 0)

if CommandLine.arguments.count == 2 {
    num_steps = Int(CommandLine.arguments[1])!;
}

print("Calculating PI with:")
print("  " + String(num_steps) + " slices")
print("  1 process")

var total_sim: Double = 0.0
var step: Double = 1.0/Double(num_steps)

// gettimeofday is a Glibc function.
// Call it with the pointer to rettime so that it fills rettime.
gettimeofday(&rettime, nil)
var start: Double = Double(rettime.tv_sec) + (Double(rettime.tv_usec)/1000000)

for i in 1...num_steps {
    var x: Double = (Double(i) - 0.5) * step
    total_sim += 4.0/(1.0+(x*x))
}

var pi: Double = total_sim * step

// Get time of day again.
gettimeofday(&rettime, nil)
var stop: Double = Double(rettime.tv_sec) + (Double(rettime.tv_usec)/1000000)

print("Obtained value of PI: " + String(pi))
print("Time taken: " + String(stop - start) + " seconds")

Move from Darwin/Glibc timing to Foundation

#!/usr/bin/env swift

import Foundation

var num_steps: Int = 1000000000

if CommandLine.arguments.count == 2 {
    num_steps = Int(CommandLine.arguments[1])!;
}

print("Calculating PI with:")
print("  " + String(num_steps) + " slices")
print("  1 process")

var total_sim: Double = 0.0
var step: Double = 1.0/Double(num_steps)

// Get time.
let start = Date()

for i in 1...num_steps {
    var x: Double = (Double(i) - 0.5) * step
    total_sim += 4.0/(1.0+(x*x))
}

var pi: Double = total_sim * step

// Get time again.
let stop = Date()
let interval = stop.timeIntervalSince(start)

print("Obtained value of PI: " + String(pi))
print("Time taken: " + String(interval) + " seconds")


// RUN: %{python} %utils/line-directive
// RUN: %{python} %utils/line-directive -- %{python} -c "print('你好')"

Disable test to unblock CI

// REQUIRES: rdar92613094

// RUN: %{python} %utils/line-directive
// RUN: %{python} %utils/line-directive -- %{python} -c "print('你好')"


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

import Traversal
import XCTest

class StreamTests: XCTestCase {
	func testStreams() {
		let sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9]
		let reducible = ReducibleOf(sequence)
		let stream = Stream(reducible)

		XCTAssertEqual(first(stream)!, 1)
		XCTAssertEqual(first(stream)!, 1)
		XCTAssertEqual(first(dropFirst(stream))!, 2)
		XCTAssertEqual(first(dropFirst(stream))!, 2)
		XCTAssertEqual(first(dropFirst(dropFirst(dropFirst(stream))))!, 4)
	}
}

Test that Stream can be zipped.

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

import Traversal
import XCTest

class StreamTests: XCTestCase {
	func testStreams() {
		let sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9]
		let reducible = ReducibleOf(sequence)
		let stream = Stream(reducible)

		XCTAssertEqual(first(stream)!, 1)
		XCTAssertEqual(first(stream)!, 1)
		XCTAssertEqual(first(dropFirst(stream))!, 2)
		XCTAssertEqual(first(dropFirst(stream))!, 2)
		XCTAssertEqual(first(dropFirst(dropFirst(dropFirst(stream))))!, 4)

		var n = 0
		for (a, b) in Zip2(stream, sequence) {
			XCTAssertEqual(a, b)
			n++
		}
		XCTAssertEqual(n, sequence.count)
	}
}


//
//  Int+Timepiece.swift
//  Timepiece
//
//  Created by Naoto Kaneko on 2014/08/15.
//  Copyright (c) 2014年 Naoto Kaneko. All rights reserved.
//

import Foundation

public extension Int {
    var year: DateComponents {
        var dateComponents = DateComponents()
        dateComponents.year = self
        return dateComponents
    }

    var years: DateComponents {
        return year
    }

    var month: DateComponents {
        var dateComponents = DateComponents()
        dateComponents.month = self
        return dateComponents
    }

    var months: DateComponents {
        return month
    }

    var week: DateComponents {
        var dateComponents = DateComponents()
        dateComponents.day = 7 * self
        return dateComponents
    }

    var weeks: DateComponents {
        return week
    }

    var day: DateComponents {
        var dateComponents = DateComponents()
        dateComponents.day = self
        return dateComponents
    }

    var days: DateComponents {
        return day
    }

    var hour: DateComponents {
        var dateComponents = DateComponents()
        dateComponents.hour = self
        return dateComponents
    }

    var hours: DateComponents {
        return hour
    }

    var minute: DateComponents {
        var dateComponents = DateComponents()
        dateComponents.minute = self
        return dateComponents
    }

    var minutes: DateComponents {
        return minute
    }

    var second: DateComponents {
        var dateComponents = DateComponents()
        dateComponents.second = self
        return dateComponents
    }

    var seconds: DateComponents {
        return second
    }

    var nanosecond: DateComponents {
        var dateComponents = DateComponents()
        dateComponents.nanosecond = self
        return dateComponents
    }

    var nanoseconds: DateComponents {
        return nanosecond
    }
}

Create instance of date components instead of mutable variable.

//
//  Int+Timepiece.swift
//  Timepiece
//
//  Created by Naoto Kaneko on 2014/08/15.
//  Copyright (c) 2014年 Naoto Kaneko. All rights reserved.
//

import Foundation

public extension Int {
    var year: DateComponents {
        return DateComponents(year: self)
    }

    var years: DateComponents {
        return year
    }

    var month: DateComponents {
        return DateComponents(month: self)
    }

    var months: DateComponents {
        return month
    }

    var week: DateComponents {
        return DateComponents(day: 7 * self)
    }

    var weeks: DateComponents {
        return week
    }

    var day: DateComponents {
        return DateComponents(day: self)
    }

    var days: DateComponents {
        return day
    }

    var hour: DateComponents {
        return DateComponents(hour: self)
    }

    var hours: DateComponents {
        return hour
    }

    var minute: DateComponents {
        return DateComponents(minute: self)
    }

    var minutes: DateComponents {
        return minute
    }

    var second: DateComponents {
        return DateComponents(second: self)
    }

    var seconds: DateComponents {
        return second
    }

    var nanosecond: DateComponents {
        return DateComponents(nanosecond: self)
    }

    var nanoseconds: DateComponents {
        return nanosecond
    }
}


import Foundation
import AutobahnDescription

// let autobahn = Autobahn()
// autoban.defaultTask = "release"

beforeAll { highway in
	print("Driving highway: \(highway)")
}

highway("build") {
	print("Building...")
	try sh("swift", "build")
}

highway("test") {
	try sh("swift", "test")
}

highway("deploy") {
	print("Deploying...")
}

highway("release", dependsOn: ["build", "deploy"]) {
	print("Releasing...")
}

afterAll { highway in
	print("Successfully ran task: \(highway)")
}

onError { highway, error in
	print("Error driving highway: \(highway)")
	print("Error: \(error.localizedDescription)")
}

Support both versions of Swift

import Foundation
import AutobahnDescription

// let autobahn = Autobahn()
// autoban.defaultTask = "release"

beforeAll { highway in
	print("Driving highway: \(highway)")
}

highway("build") {
	print("Building...")
	try sh("swift", "build")
}

highway("test") {
	try sh("swift", "test")
}

highway("deploy") {
	print("Deploying...")
}

highway("release", dependsOn: ["build", "deploy"]) {
	print("Releasing...")
}

afterAll { highway in
	print("Successfully drove highway: \(highway)")
}

onError { highway, error in
	print("Error driving highway: \(highway)")
	print("Error: \(error.localizedDescription)")
}


//
//  Once.swift
//  Eki
//
//  Created by Jeremy Marchand on 20/10/2014.
//  Copyright (c) 2014 Jérémy Marchand. All rights reserved.
//

import Foundation

/**
A token to be initilized and stored for use with once().
*/
public final class OnceToken {
    internal var dispatchToken = dispatch_once_t(0)
}

/**
Execute a block once and only once.
*/
public func once(token:OnceToken, block:() -> Void) {
    dispatch_once(&token.dispatchToken,block)
}

Add a public initializer for token

//
//  Once.swift
//  Eki
//
//  Created by Jeremy Marchand on 20/10/2014.
//  Copyright (c) 2014 Jérémy Marchand. All rights reserved.
//

import Foundation

/**
A token to be initilized and stored for use with once().
*/
public final class OnceToken {
    internal var dispatchToken = dispatch_once_t(0)
    public init() {

    }
}

/**
Execute a block once and only once.
*/
public func once(token:OnceToken, block:() -> Void) {
    dispatch_once(&token.dispatchToken,block)
}


import UIKit

extension MSettingsMemorySystem
{
    //MARK: private

    private static func factorySystemSize() -> CGFloat
    {
        let systemSize:UInt64 = FileManager.default.systemSize
        let floatSystemSize:CGFloat = CGFloat(systemSize)

        return floatSystemSize
    }

    private static func factorySystemFreeSize() -> CGFloat
    {
        let systemFreeSize:UInt64 = FileManager.default.systemFreeSize
        let floatSystemFreeSize:CGFloat = CGFloat(systemFreeSize)

        return floatSystemFreeSize
    }

    //MARK: internal

    static func factorySystem(columbusSize:CGFloat) -> MSettingsMemorySystem
    {
        let systemSize:CGFloat = factorySystemSize()
        let systemFreeSize:CGFloat = factorySystemFreeSize()
        let otherSize:CGFloat = systemSize - systemFreeSize
        let otherPercent:CGFloat = otherSize / systemSize
        let columbusPercent:CGFloat = columbusSize / systemSize

        let system:MSettingsMemorySystem = MSettingsMemorySystem(
            systemSize:systemSize,
            columbusSize:columbusSize,
            columbusPercent:columbusPercent,
            otherSize:otherSize,
            otherPercent:otherPercent)

        return system
    }
}

Remove columbus size from other size

import UIKit

extension MSettingsMemorySystem
{
    //MARK: private

    private static func factorySystemSize() -> CGFloat
    {
        let systemSize:UInt64 = FileManager.default.systemSize
        let floatSystemSize:CGFloat = CGFloat(systemSize)

        return floatSystemSize
    }

    private static func factorySystemFreeSize() -> CGFloat
    {
        let systemFreeSize:UInt64 = FileManager.default.systemFreeSize
        let floatSystemFreeSize:CGFloat = CGFloat(systemFreeSize)

        return floatSystemFreeSize
    }

    //MARK: internal

    static func factorySystem(columbusSize:CGFloat) -> MSettingsMemorySystem
    {
        let systemSize:CGFloat = factorySystemSize()
        let systemFreeSize:CGFloat = factorySystemFreeSize()
        let usedSize:CGFloat = systemSize - systemFreeSize
        let otherSize:CGFloat = usedSize - columbusSize
        let otherPercent:CGFloat = otherSize / systemSize
        let columbusPercent:CGFloat = columbusSize / systemSize

        let system:MSettingsMemorySystem = MSettingsMemorySystem(
            systemSize:systemSize,
            columbusSize:columbusSize,
            columbusPercent:columbusPercent,
            otherSize:otherSize,
            otherPercent:otherPercent)

        return system
    }
}


/*
 * Copyright 2015-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

import UIKit

@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.red
        let window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = vc

        self.window = window
        window.makeKeyAndVisible()

        return true
    }
}

Update UIApplicationLaunchOptionsKey to UIApplication.LaunchOptionsKey for xcode10

/*
 * Copyright 2015-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

import UIKit

@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.red
        let window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = vc

        self.window = window
        window.makeKeyAndVisible()

        return true
    }
}


//
//  JsonApiErrorMiddleware.swift
//  VaporJsonApi
//
//  Created by Koray Koska on 01/05/2017.
//
//

import Vapor
import HTTP

public final class JsonApiErrorMiddleware: Middleware {

    public func respond(to request: Request, chainingTo next: Responder) throws -> Response {
        do {
            return try next.respond(to: request)
        } catch let e as JsonApiError {
            let error = JsonApiErrorObject(status: String(e.status.statusCode), code: e.code, title: e.title, detail: e.detail)
            let document = JsonApiDocument(errors: [error])
            let response = JsonApiResponse(status: e.status, document: document)

            return try response.makeResponse()
        }
    }
}

Add public initializer to error middleware

//
//  JsonApiErrorMiddleware.swift
//  VaporJsonApi
//
//  Created by Koray Koska on 01/05/2017.
//
//

import Vapor
import HTTP

public final class JsonApiErrorMiddleware: Middleware {

    public init() {}

    public func respond(to request: Request, chainingTo next: Responder) throws -> Response {
        do {
            return try next.respond(to: request)
        } catch let e as JsonApiError {
            let error = JsonApiErrorObject(status: String(e.status.statusCode), code: e.code, title: e.title, detail: e.detail)
            let document = JsonApiDocument(errors: [error])
            let response = JsonApiResponse(status: e.status, document: document)

            return try response.makeResponse()
        }
    }
}


//
//  NSNotificationCenter+Rx.swift
//  RxCocoa
//
//  Created by Krunoslav Zaher on 5/2/15.
//  Copyright © 2015 Krunoslav Zaher. All rights reserved.
//

import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif

extension NSNotificationCenter {
    /**
    Transforms notifications posted to notification center to observable sequence of notifications.

    - parameter name: Filter notifications by name.
    - parameter object: Optional object used to filter notifications.
    - returns: Observable sequence of posted notifications.
    */
    @warn_unused_result(message="http://git.io/rxs.uo")
    public func rx_notification(name: String, object: AnyObject? = nil) -> Observable<NSNotification> {
        return Observable.create { [weak object] observer in
            let nsObserver = self.addObserverForName(name, object: object, queue: nil) { notification in
                observer.on(.Next(notification))
            }

            return AnonymousDisposable {
                self.removeObserver(nsObserver)
            }
        }
    }
}

Make name parameter of rx_notification optional.

//
//  NSNotificationCenter+Rx.swift
//  RxCocoa
//
//  Created by Krunoslav Zaher on 5/2/15.
//  Copyright © 2015 Krunoslav Zaher. All rights reserved.
//

import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif

extension NSNotificationCenter {
    /**
    Transforms notifications posted to notification center to observable sequence of notifications.

    - parameter name: Filter notifications by name.
    - parameter object: Optional object used to filter notifications.
    - returns: Observable sequence of posted notifications.
    */
    @warn_unused_result(message="http://git.io/rxs.uo")
    public func rx_notification(name: String?, object: AnyObject? = nil) -> Observable<NSNotification> {
        return Observable.create { [weak object] observer in
            let nsObserver = self.addObserverForName(name, object: object, queue: nil) { notification in
                observer.on(.Next(notification))
            }

            return AnonymousDisposable {
                self.removeObserver(nsObserver)
            }
        }
    }
}


// Playground - noun: a place where people can play

import Cocoa

class Person {
  var name: String
  var age: Int?
  var consideredDangerous = false

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

  convenience init(name: String) {
    self.init(name: name, age: nil)
  }

}

enum Weapon {
  case Katana, Tsuba, Shuriken, Kusarigama, Fukiya
}

class Ninja: Person {
  var weapons: Weapon[]?

  init(name: String, age: Int?, weapons: Weapon[]?) {
    self.weapons = weapons

    super.init(name: name, age: age)

    self.consideredDangerous = true
  }

  convenience init(name: String) {
    self.init(name: name, age: nil, weapons: nil)
  }
}

let tony = Person(name: "tony")
tony.consideredDangerous
tony.age
tony.age = 43
tony

let tara = Person(name: "tara", age: 27)
tara.consideredDangerous
tara.age

let trevor = Ninja(name: "trevor")
trevor.age
trevor.consideredDangerous

let tina = Ninja(name: "tina", age: 23, weapons: [.Fukiya, .Tsuba])
tina.consideredDangerous
tina.weapons
tina.age

Update to match the new array syntax

// Playground - noun: a place where people can play

import Cocoa

class Person {
  var name: String
  var age: Int?
  var consideredDangerous = false

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

  convenience init(name: String) {
    self.init(name: name, age: nil)
  }

}

enum Weapon {
  case Katana, Tsuba, Shuriken, Kusarigama, Fukiya
}

class Ninja: Person {
  var weapons: [Weapon]?

  init(name: String, age: Int?, weapons: [Weapon]?) {
    self.weapons = weapons

    super.init(name: name, age: age)

    self.consideredDangerous = true
  }

  convenience init(name: String) {
    self.init(name: name, age: nil, weapons: nil)
  }
}

let tony = Person(name: "tony")
tony.consideredDangerous
tony.age
tony.age = 43
tony

let tara = Person(name: "tara", age: 27)
tara.consideredDangerous
tara.age

let trevor = Ninja(name: "trevor")
trevor.age
trevor.consideredDangerous

let tina = Ninja(name: "tina", age: 23, weapons: [.Fukiya, .Tsuba])
tina.consideredDangerous
tina.weapons
tina.age


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

import Foundation

public extension NSMutableAttributedString {

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

}

Add helper for immutable attributed strings

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

import Foundation

public extension NSMutableAttributedString {

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

}

public extension NSAttributedString {

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

}


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

import UIKit
import PinpointKit

final class ViewController: UITableViewController {

    private let pinpointKit = PinpointKit(configuration: Configuration(sender: MySender(), feedbackRecipients: ["feedback@example.com"]))

    override func viewDidLoad() {
        super.viewDidLoad()

        // Hides the infinite cells footer.
        tableView.tableFooterView = UIView()
    }

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

        pinpointKit.show(fromViewController: self)
    }
}

final class MySender: MailSender {

    override func sendFeedback(feedback: Feedback, fromViewController viewController: UIViewController?) {
        var newFeedback = feedback
        newFeedback.title = "hello"
        newFeedback.body = "this is the body of the feedback"
        newFeedback.screenshotFileName = "my feedback"
        newFeedback.additionalInformation = ["user": "mliberatore"]
        newFeedback.logsFileName = "myLogs"

        super.sendFeedback(newFeedback, fromViewController: viewController)
    }
}

Revert "Adds test code for feedback customization"

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

import UIKit
import PinpointKit

final class ViewController: UITableViewController {

    private let pinpointKit = PinpointKit(feedbackRecipients: ["feedback@example.com"])

    override func viewDidLoad() {
        super.viewDidLoad()

        // Hides the infinite cells footer.
        tableView.tableFooterView = UIView()
    }

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

        pinpointKit.show(fromViewController: self)
    }
}


import UIKit

protocol Reusable { }

extension Reusable {

    static var reuseIdentifier: String {
        return NSStringFromClass(self as! AnyObject.Type)
    }

}

extension UITableViewCell: Reusable { }
extension UICollectionReusableView: Reusable { }

extension UITableView {
    public func dequeueCell<T>(for indexPath: IndexPath) -> T where T: UITableViewCell {
        register(T.classForCoder(), forCellReuseIdentifier: T.reuseIdentifier)
        return dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }
}

extension UICollectionView {
    public func dequeueCell<T>(for indexPath: IndexPath) -> T where T: UICollectionViewCell {
        register(T.classForCoder(), forCellWithReuseIdentifier: T.reuseIdentifier)
        return dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }
}

Set Reusable protocol to be public

import UIKit

public protocol Reusable { }

extension Reusable {

    public static var reuseIdentifier: String {
        return NSStringFromClass(self as! AnyObject.Type)
    }

}

extension UITableViewCell: Reusable { }
extension UICollectionReusableView: Reusable { }

extension UITableView {
    public func dequeueCell<T>(for indexPath: IndexPath) -> T where T: UITableViewCell {
        register(T.classForCoder(), forCellReuseIdentifier: T.reuseIdentifier)
        return dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }
}

extension UICollectionView {
    public func dequeueCell<T>(for indexPath: IndexPath) -> T where T: UICollectionViewCell {
        register(T.classForCoder(), forCellWithReuseIdentifier: T.reuseIdentifier)
        return dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }
}


//
//  Package.swift
//  twohundred
//
//  Created by Johannes Schriewer on 03/12/15.
//  Copyright © 2015 Johannes Schriewer. All rights reserved.
//

import PackageDescription

let package = Package(
    name: "TwoHundred",
	targets: [
	 	Target(name:"TwoHundredTests", dependencies: [.Target(name: "TwoHundred")]),
	 	Target(name:"TwoHundredDemo", dependencies: [.Target(name: "TwoHundred")]),
        Target(name:"TwoHundred")
	],
	dependencies: [
		.Package(url:"https://github.com/dunkelstern/Adler32.git", majorVersion: 0),
		.Package(url:"https://github.com/dunkelstern/UnchainedIPAddress.git", majorVersion: 0),
		.Package(url:"https://github.com/dunkelstern/UnchainedDate.git", majorVersion: 0),
		.Package(url:"https://github.com/dunkelstern/UnchainedLogger.git", majorVersion: 0),
		.Package(url:"https://github.com/dunkelstern/libUnchainedSocket.git", majorVersion: 0)
	]
)

Add BlocksRuntime for linux builds

//
//  Package.swift
//  twohundred
//
//  Created by Johannes Schriewer on 03/12/15.
//  Copyright © 2015 Johannes Schriewer. All rights reserved.
//

import PackageDescription

let package = Package(
    name: "TwoHundred",
	targets: [
	 	Target(name:"TwoHundredTests", dependencies: [.Target(name: "TwoHundred")]),
	 	Target(name:"TwoHundredDemo", dependencies: [.Target(name: "TwoHundred")]),
        Target(name:"TwoHundred")
	],
	dependencies: [
		.Package(url:"https://github.com/dunkelstern/Adler32.git", majorVersion: 0),
		.Package(url:"https://github.com/dunkelstern/UnchainedIPAddress.git", majorVersion: 0),
		.Package(url:"https://github.com/dunkelstern/UnchainedDate.git", majorVersion: 0),
		.Package(url:"https://github.com/dunkelstern/UnchainedLogger.git", majorVersion: 0),
		.Package(url:"https://github.com/dunkelstern/libUnchainedSocket.git", majorVersion: 0)
	]
)

#if os(Linux)
	package.dependencies.append(
		.Package(url:"https://github.com/dunkelstern/BlocksRuntime.git", majorVersion: 0)
	)
#endif


// swift-tools-version:5.1

import PackageDescription

let package = Package(
    name: "CleanroomLogger",
    products: [
        .library(
            name: "CleanroomLogger",
            targets: ["CleanroomLogger"]),
    ],
    targets: [
        .target(
            name: "CleanroomLogger",
            dependencies: [],
            path: "Sources"),
    ]
)

Use Xcode 10 compatible package tools version

// swift-tools-version:5.0

import PackageDescription

let package = Package(
    name: "CleanroomLogger",
    products: [
        .library(
            name: "CleanroomLogger",
            targets: ["CleanroomLogger"]),
    ],
    targets: [
        .target(
            name: "CleanroomLogger",
            dependencies: [],
            path: "Sources"),
    ]
)


import PackageDescription

let package = Package(
    name: "StencilSwiftKit",
    targets: [
        Target(name: "StencilSwiftKit", dependencies: [])
    ],
    dependencies: [
        .Package(url: "https://github.com/kylef/Stencil.git", majorVersion: 0, minor: 10),
    ]
)

Convert SPM package to version 4

// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "StencilSwiftKit",
    products: [
        .library(name: "StencilSwiftKit", targets: ["StencilSwiftKit"])
    ],
    dependencies: [
        .package(url: "https://github.com/kylef/Stencil.git", .upToNextMinor(from: "0.10.0"))
    ],
    targets: [
      .target(
        name: "StencilSwiftKit",
        dependencies: [
          "Stencil"
        ],
        path: "",
        sources: ["Sources"]
      ),
      .testTarget(
        name: "StencilSwiftKitTests",
        dependencies: [
          "StencilSwiftKit"
        ],
        path: "Tests"
      )
    ],
    swiftLanguageVersions: [4]
)


// swift-tools-version:5.3

import PackageDescription

let package = Package(
    name: "TvOSMoreButton",
    platforms: [
        .tvOS(.v10)
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "TvOSMoreButton",
            targets: ["TvOSMoreButton"])
    ],
    dependencies: [
        .package(name: "SnapshotTesting", url: "https://github.com/pointfreeco/swift-snapshot-testing.git", from: "1.8.1"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "TvOSMoreButton",
            dependencies: [
            ],
            path: "Source",
            exclude: ["Artwork", "Example", "Info.plist"],
            resources: [
                .process("Resources")
            ]
        ),
        .testTarget(
            name: "TvOSMoreButtonTests",
            dependencies: ["TvOSMoreButton", "SnapshotTesting"],
            path: "Tests",
            exclude: ["Info.plist"],
            resources: [
                .process("Public/Views/__Snapshots__/Tests_TvOSMoreButton"),
                .process("Resources/Localizable.strings")
            ]
        ),
    ]
)

Fix swiftlint warning by removing trailing comma

// swift-tools-version:5.3

import PackageDescription

let package = Package(
    name: "TvOSMoreButton",
    platforms: [
        .tvOS(.v10)
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "TvOSMoreButton",
            targets: ["TvOSMoreButton"])
    ],
    dependencies: [
        .package(name: "SnapshotTesting", url: "https://github.com/pointfreeco/swift-snapshot-testing.git", from: "1.8.1")
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "TvOSMoreButton",
            dependencies: [
            ],
            path: "Source",
            exclude: ["Artwork", "Example", "Info.plist"],
            resources: [
                .process("Resources")
            ]
        ),
        .testTarget(
            name: "TvOSMoreButtonTests",
            dependencies: ["TvOSMoreButton", "SnapshotTesting"],
            path: "Tests",
            exclude: ["Info.plist"],
            resources: [
                .process("Public/Views/__Snapshots__/Tests_TvOSMoreButton"),
                .process("Resources/Localizable.strings")
            ]
        )
    ]
)


// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "Stripe",
    products: [
        .library(name: "Stripe", targets: ["Stripe"])
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", from: "3.0.0"),
    ],
    targets: [
        .target(name: "Stripe", dependencies: ["Vapor"]),
        .testTarget(name: "StripeTests", dependencies: ["Vapor", "Stripe"])
    ]
)

Use latest Vapor and swift tools version.

// swift-tools-version:4.2
import PackageDescription

let package = Package(
    name: "Stripe",
    products: [
        .library(name: "Stripe", targets: ["Stripe"])
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", from: "3.2.2"),
    ],
    targets: [
        .target(name: "Stripe", dependencies: ["Vapor"]),
        .testTarget(name: "StripeTests", dependencies: ["Vapor", "Stripe"])
    ]
)


// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "Syft",
    targets: [
        .target(
            name: "Sample",
            dependencies: ["Syft"]),
        .target(
            name: "Syft"),
        .testTarget(
            name: "SyftTests",
            dependencies: ["Syft"])
    ]
)

Make the lib a product.

// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "Syft",
    products: [
        .library(name: "Syft", targets: ["Syft"])
    ],
    targets: [
        .target(
            name: "Sample",
            dependencies: ["Syft"]),
        .target(
            name: "Syft"),
        .testTarget(
            name: "SyftTests",
            dependencies: ["Syft"])
    ]
)


// swift-tools-version:5.0
import PackageDescription

// Note: SPM support is broken until we can add dependency on UIKit.

let package = Package(
    name: "Reusable",
    products: [
        .library(name: "Reusable", targets: ["Reusable"])
    ],
    targets: [
      .target(
        name: "Reusable",
        path: "",
        sources: ["Sources"]
      )
    ],
    swiftLanguageVersions: [3, 4, 5]
)

Update package manifest to work with Xcode 11

// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "Reusable",
    platforms: [.iOS(.v8), .tvOS(.v9)],
    products: [
        .library(name: "Reusable", targets: ["Reusable"])
    ],
    targets: [
      .target(
        name: "Reusable",
        path: "",
        sources: ["Sources"]
      )
    ],
    swiftLanguageVersions: [.v4, .v5]
)


// swift-tools-version:5.1
import PackageDescription

let package = Package(
  name: "FDWaveformView"
)

Change swift tools-version back to 4.0

// swift-tools-version:4.0
import PackageDescription

let package = Package(
  name: "FDWaveformView"
)


import Foundation;

println("Hello, World!")

enum CompassPoint {
    case North;
    case South;
    case East;
    case West;
};

protocol SomeProtocol {
    var fullName: String { get };
    func demo();
    func dummy(f: Int);
    func foo(bar: String, baz: Double);
};

extension SomeType {
    // new functionality to add to SomeType goes here
};

struct DemoStruct {
    var x: String;

    func test() {
        // while loop test
        while true
        {
        };

        // for loop
        for ; ; {

        };

        // repeat while
        repeat {

        } while true;
    };
};

// Class examples

class UpperCamelCase {
    var x: String = "hello";
    let b = 2;

    func demo()
    {
        for var x = 0; ; {
            print(x);
        };

        if temperatureInFahrenheit <= 32 {
            println("It's very cold. Consider wearing a scarf.");
        } else if temperatureInFahrenheit >= 86 {
            println("It's really warm. Don't forget to wear sunscreen.");
        } else {
            println("It's not that cold. Wear a t-shirt.");
        }
    };
};

Remove {} test from ; test


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

import Foundation

Implement the app delegate in Swift

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

import Foundation
import UIKit

class NATHiBeaconsDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    override init() { }

    func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool
    {
        return true
    }
}