//
//  UILabel+Rx.swift
//  RxAppState
//
//  Created by Jörn Schoppe on 06.03.16.
//  Copyright © 2016 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import RxAppState

extension UILabel {
    public var rx_appState: AnyObserver<AppState> {
        return UIBindingObserver(UIElement: self) { label, appState in
            print(appState)
            switch appState {
            case .Active:
                label.backgroundColor = UIColor.greenColor()
                label.text = "ACTIVE"
            case .Inactive:
                label.backgroundColor = UIColor.yellowColor()
                label.text = "INACTIVE"
            case .Background:
                label.backgroundColor = UIColor.redColor()
                label.text = "BACKGROUND"
            case .Terminated:
                label.backgroundColor = UIColor.lightGrayColor()
                label.text = "TERMINATED"
            }
            }.asObserver()
    }
}

Add UILabel Rx extension for firstLaunch feedback

//
//  UILabel+Rx.swift
//  RxAppState
//
//  Created by Jörn Schoppe on 06.03.16.
//  Copyright © 2016 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import RxAppState

extension UILabel {
    public var rx_appState: AnyObserver<AppState> {
        return UIBindingObserver(UIElement: self) { label, appState in
            switch appState {
            case .Active:
                label.backgroundColor = UIColor.greenColor()
                label.text = "ACTIVE"
            case .Inactive:
                label.backgroundColor = UIColor.yellowColor()
                label.text = "INACTIVE"
            case .Background:
                label.backgroundColor = UIColor.redColor()
                label.text = "BACKGROUND"
            case .Terminated:
                label.backgroundColor = UIColor.lightGrayColor()
                label.text = "TERMINATED"
            }
        }
        .asObserver()
    }

    public var rx_firstLaunch: AnyObserver<Bool> {
        return UIBindingObserver(UIElement: self) { label, isFirstLaunch in
            if isFirstLaunch {
                label.backgroundColor = UIColor.greenColor()
                label.text = "YES"
            } else {
                label.backgroundColor = UIColor.redColor()
                label.text = "NO"
            }
        }
        .asObserver()
    }
}


import UIKit

@objc
final class NotificationsCenterViewController: ViewController {

	// MARK: - Properties

	var notificationsView: NotificationsCenterView {
		return view as! NotificationsCenterView
	}

	let viewModel: NotificationsCenterViewModel

	// MARK: - Lifecycle

	@objc
	init(theme: Theme, viewModel: NotificationsCenterViewModel) {
		self.viewModel = viewModel
		super.init(theme: theme)
	}

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

	override func loadView() {
		super.loadView()
		self.view = NotificationsCenterView(frame: .zero)
	}

	override func viewDidLoad() {
		super.viewDidLoad()

		notificationsView.apply(theme: theme)

		title = CommonStrings.notificationsCenterTitle
		setupBarButtons()
	}

	// MARK: - Configuration

	fileprivate func setupBarButtons() {
		enableToolbar()
		setToolbarHidden(false, animated: false)

		let editButton = UIBarButtonItem(title: WMFLocalizedString("notifications-center-edit-button", value: "Edit", comment: "Title for navigation bar button to toggle mode for editing notification read status"), style: .plain, target: nil, action: nil)
		navigationItem.rightBarButtonItem = editButton
	}

	// MARK: - Public

}

Remove unneeded call to super.

import UIKit

@objc
final class NotificationsCenterViewController: ViewController {

	// MARK: - Properties

	var notificationsView: NotificationsCenterView {
		return view as! NotificationsCenterView
	}

	let viewModel: NotificationsCenterViewModel

	// MARK: - Lifecycle

	@objc
	init(theme: Theme, viewModel: NotificationsCenterViewModel) {
		self.viewModel = viewModel
		super.init(theme: theme)
	}

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

	override func loadView() {
		self.view = NotificationsCenterView(frame: .zero)
	}

	override func viewDidLoad() {
		super.viewDidLoad()

		notificationsView.apply(theme: theme)

		title = CommonStrings.notificationsCenterTitle
		setupBarButtons()
	}

	// MARK: - Configuration

	fileprivate func setupBarButtons() {
		enableToolbar()
		setToolbarHidden(false, animated: false)

		let editButton = UIBarButtonItem(title: WMFLocalizedString("notifications-center-edit-button", value: "Edit", comment: "Title for navigation bar button to toggle mode for editing notification read status"), style: .plain, target: nil, action: nil)
		navigationItem.rightBarButtonItem = editButton
	}

	// MARK: - Public

}


// Copyright 2018 The TensorFlow Authors. All Rights Reserved.
//
// 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.

#if !COMPILING_TENSORFLOW_MODULE
import TensorFlow
#endif

// `round` Tensor Float or Double values to the to closest integral values with greater magnitude
// This is a manual definition.
func round<T : BinaryFloatingPoint>(_ t: Tensor<T>) -> Tensor<T> {
    return Raw.round(t)
}

Add identity function and update doc comments.

// Copyright 2018 The TensorFlow Authors. All Rights Reserved.
//
// 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.

#if !COMPILING_TENSORFLOW_MODULE
import TensorFlow
#endif

// Rounds the values of a tensor to the nearest integer, element-wise.
func round<Scalar: BinaryFloatingPoint>(_ x: Tensor<Scalar>) -> Tensor<Scalar> {
    return Raw.round(x)
}

// Return a tensor with the same shape and contents as input.
func identity<Scalar>(_ x: Tensor<Scalar>) -> Tensor<Scalar> {
    return x
}


//
//  Swift3Typealiases.swift
//  PSOperations
//
//  Created by Dev Team on 9/20/16.
//  Copyright © 2016 Pluralsight. All rights reserved.
//

public typealias PSOperation = Operation
public typealias PSOperationQueue = OperationQueue

Add typealiases for BlockOperation and OperationQueueDelegate

//
//  Swift3Typealiases.swift
//  PSOperations
//
//  Created by Dev Team on 9/20/16.
//  Copyright © 2016 Pluralsight. All rights reserved.
//

public typealias PSOperation = Operation
public typealias PSOperationQueue = OperationQueue
public typealias PSOperationQueueDelegate = OperationQueueDelegate
public typealias PSBlockOperation = BlockOperation


//
//  Cache.swift
//  Reactor
//
//  Created by Rui Peres on 14/03/2016.
//  Copyright © 2016 Mail Online. All rights reserved.
//

import Foundation

final class Cache<T where T: Hashable> {

    private var cache = [Int: T]()
    private let lock = dispatch_queue_create("cache.queue", DISPATCH_QUEUE_SERIAL)

    var count: Int { return cache.count }

    subscript(key: Int) -> T? {

        get {
            var value: T?
            dispatch_sync(lock) {
                value = self.cache[key]
            }
            return value
        }

        set(newValue) {
            dispatch_sync(lock) {
                self.cache[key] = newValue
            }
        }
    }

    func removeAll() {
        dispatch_sync(lock) {
            self.cache.removeAll()
        }
    }

    func all() -> [T] {

        var all: [T] = []

        dispatch_sync(lock) {
            for key in self.cache.keys {
                all.append(self.cache[key]!)
            }
        }
        return all
    }
}

Fix unsafe access to cache's count

//
//  Cache.swift
//  Reactor
//
//  Created by Rui Peres on 14/03/2016.
//  Copyright © 2016 Mail Online. All rights reserved.
//

import Foundation

final class Cache<T where T: Hashable> {

    private var cache = [Int: T]()
    private let lock = dispatch_queue_create("cache.queue", DISPATCH_QUEUE_SERIAL)

    var count: Int {
        var count: Int = 0
        dispatch_sync(lock) {
            count = self.cache.count
        }
        return count
    }

    subscript(key: Int) -> T? {

        get {
            var value: T?
            dispatch_sync(lock) {
                value = self.cache[key]
            }
            return value
        }

        set(newValue) {
            dispatch_sync(lock) {
                self.cache[key] = newValue
            }
        }
    }

    func removeAll() {
        dispatch_sync(lock) {
            self.cache.removeAll()
        }
    }

    func all() -> [T] {

        var all: [T] = []

        dispatch_sync(lock) {
            for key in self.cache.keys {
                all.append(self.cache[key]!)
            }
        }
        return all
    }
}


import XCTest
@testable import Decodable

class DecodableTests: XCTestCase {
    func testDecodesPerson() throws {
        let person = try Person(json: [
            "name": [
                "first": "John",
                "second": "Doe"
            ],
            "age": 25,
            "email": "johndoe@gmail.com"
        ])

        XCTAssertEqual(person.name.first, "John")
        XCTAssertEqual(person.name.second, "Doe")
        XCTAssertEqual(person.age, 25)
        XCTAssertEqual(person.email, "johndoe@gmail.com")
    }
}

Add optional test to decodable

import XCTest
@testable import Decodable

class DecodableTests: XCTestCase {
    func testDecodesPerson() throws {
        let person = try Person(json: [
            "name": [
                "first": "John",
                "second": "Doe"
            ],
            "age": 25,
            "email": "johndoe@gmail.com"
        ])

        XCTAssertEqual(person.name.first, "John")
        XCTAssertEqual(person.name.second, "Doe")
        XCTAssertEqual(person.age, 25)
        XCTAssertEqual(person.email, "johndoe@gmail.com")
    }

    func testDecodesPersonMissingEmail() throws {
        let person = try Person(json: [
            "name": [
                "first": "John",
                "second": "Doe"
            ],
            "age": 25,
        ])

        XCTAssertEqual(person.name.first, "John")
        XCTAssertEqual(person.name.second, "Doe")
        XCTAssertEqual(person.age, 25)
        XCTAssertNil(person.email)
    }
}


//
//  LevelModeGameScene.swift
//  SOPA
//
//  Created by Raphael Schilling on 23.04.18.
//  Copyright © 2018 David Schilling. All rights reserved.
//

import Foundation
import SpriteKit
class LevelModeGameScene: GameScene {
    let levelCopy: Level
    override init(size: CGSize, level: Level) {
        levelCopy = Level(level: level)
        super.init(size: size, level: level)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func addButtons() {
        let restartButton = SpriteButton(imageNamed: "restart", onClick: restartLevel)
        restartButton.size.height = BUTTON_SIZE * size.width
        restartButton.size.width = BUTTON_SIZE *  size.width
        restartButton.position.y = BUTTON_SIZE *  size.width / 2
        restartButton.position.x = size.width - BUTTON_SIZE *  size.width / 2
        addChild(restartButton)
    }
    func restartLevel() {
        level = Level(level: levelCopy)
        levelSolved = false
        gameFieldNode?.update()
        currentMoves = 0
    }
}

Reset current moves on level restart

//
//  LevelModeGameScene.swift
//  SOPA
//
//  Created by Raphael Schilling on 23.04.18.
//  Copyright © 2018 David Schilling. All rights reserved.
//

import Foundation
import SpriteKit
class LevelModeGameScene: GameScene {
    let levelCopy: Level
    override init(size: CGSize, level: Level) {
        levelCopy = Level(level: level)
        super.init(size: size, level: level)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func addButtons() {
        let restartButton = SpriteButton(imageNamed: "restart", onClick: restartLevel)
        restartButton.size.height = BUTTON_SIZE * size.width
        restartButton.size.width = BUTTON_SIZE *  size.width
        restartButton.position.y = BUTTON_SIZE *  size.width / 2
        restartButton.position.x = size.width - BUTTON_SIZE *  size.width / 2
        addChild(restartButton)
    }
    func restartLevel() {
        level = Level(level: levelCopy)
        levelSolved = false
        gameFieldNode?.update()
        currentMoves = 0
        currentMovesNode.text = String(currentMoves)
    }
}


import Commander
import SimCtl

Group {
  $0.command("list") {
    let simctl = try SimCtl()
    let _ = simctl.devices.map { print($0) }
  }

  $0.command("delete") {
  	let simctl = try SimCtl()
  	let _ = simctl.devices.map { simctl.delete($0) }
  }

  $0.command("create_defaults") {
  	let simctl = try SimCtl()
  	simctl.createDefaults()
  }
}.run()

Use forEach rather than map

import Commander
import SimCtl

Group {
  $0.command("list") {
    let simctl = try SimCtl()
    simctl.devices.forEach { print($0) }
  }

  $0.command("delete") {
  	let simctl = try SimCtl()
  	let _ = simctl.devices.map { simctl.delete($0) }
  }

  $0.command("create_defaults") {
  	let simctl = try SimCtl()
  	simctl.createDefaults()
  }
}.run()


//
//  ELJSBridge_osxTests.swift
//  ELJSBridge_osxTests
//
//  Created by Brandon Sneed on 9/30/15.
//  Copyright © 2015 WalmartLabs. All rights reserved.
//

import XCTest
@testable import ELJSBridge_osx

class ELJSBridge_osxTests: XCTestCase {

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

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

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

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

}

Update osx tests to build and run.

//
//  ELJSBridge_osxTests.swift
//  ELJSBridge_osxTests
//
//  Created by Brandon Sneed on 9/30/15.
//  Copyright © 2015 WalmartLabs. All rights reserved.
//

import XCTest
@testable import ELJSBridge

class ELJSBridge_osxTests: XCTestCase {

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

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

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

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

}


//
//  Created by Jake Lin on 8/18/15.
//  Copyright © 2015 Jake Lin. All rights reserved.
//

import XCTest
import Quick
import Nimble

class SwiftWeatherUITests: QuickSpec {

    override func spec() {
        let app = XCUIApplication()

        beforeSuite {
            self.continueAfterFailure = false
            XCUIDevice.shared().orientation = .portrait
            app.launch()
        }

        describe("a wheather viewcontroller") {
            it("shows city") {
                expect(app.staticTexts["a11y_current_city"].exists).to(beTruthy())
            }

            it("shows wheather icon") {
                expect(app.staticTexts["a11y_wheather_icon"].exists).to(beTruthy())
            }

            it("shows wheather temperature") {
                expect(app.staticTexts["a11y_wheather_temperature"].exists).to(beTruthy())
            }
        }
    }

}

Add different contexts to test app orientation

//
//  Created by Jake Lin on 8/18/15.
//  Copyright © 2015 Jake Lin. All rights reserved.
//

import XCTest
import Quick
import Nimble

class SwiftWeatherUITests: QuickSpec {

    override func spec() {
        let app = XCUIApplication()

        beforeSuite {
            self.continueAfterFailure = false

            app.launch()
        }

        describe("a wheather viewcontroller") {
            context("when the app orientation is portrait") {
                beforeEach {
                    XCUIDevice.shared().orientation = .portrait
                }
                itBehavesLike("a regular wheather viewcontroller")
            }

            context("when the app orientation is landscape") {
                beforeEach {
                    XCUIDevice.shared().orientation = .landscapeLeft
                }
                itBehavesLike("a regular wheather viewcontroller")
            }
        }
    }
}

class RegularWheatherViewControllerConfiguration: QuickConfiguration {
    override class func configure(_ configuration: Configuration) {
        let app = XCUIApplication()

        sharedExamples("a regular wheather viewcontroller") { (context: SharedExampleContext) in
            it("shows city") {
                expect(app.staticTexts["a11y_current_city"].exists).to(beTruthy())
            }

            it("shows wheather icon") {
                expect(app.staticTexts["a11y_wheather_icon"].exists).to(beTruthy())
            }

            it("shows wheather temperature") {
                expect(app.staticTexts["a11y_wheather_temperature"].exists).to(beTruthy())
            }
        }
    }
}


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

import Prelude
import XCTest

final class ApplicationTests: XCTestCase {
	// MARK: Forward function application

	func testForwardUnaryFunctionApplication() {
		let digits = 100 |> toString |> countElements
		XCTAssertEqual(digits, 3)
	}

	func testForwardBinaryFunctionApplication() {
		XCTAssertEqual((1, 2) |> (+), 3)
	}

	// MARK: Backward function application

	func testBackwardFunctionApplication() {
		let digits = countElements <| toString <| 100
		XCTAssertEqual(digits, 3)
	}
}

Test backward binary function application.

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

import Prelude
import XCTest

final class ApplicationTests: XCTestCase {
	// MARK: Forward function application

	func testForwardUnaryFunctionApplication() {
		let digits = 100 |> toString |> countElements
		XCTAssertEqual(digits, 3)
	}

	func testForwardBinaryFunctionApplication() {
		XCTAssertEqual((1, 2) |> (+), 3)
	}

	// MARK: Backward function application

	func testBackwardUnaryFunctionApplication() {
		let digits = countElements <| toString <| 100
		XCTAssertEqual(digits, 3)
	}

	func testBackwardBinaryFunctionApplication() {
		XCTAssertEqual((+) <| (1, 2), 3)
	}
}


//
//  ViewController.swift
//  bug_repro
//
//  Created by satoshi on 8/23/16.
//  Copyright © 2016 Satoshi Nakajima. All rights reserved.
//

import UIKit
import AVFoundation

//
// I reported this bug to Apple on August 25, 2016. Bug# 27982201.
//
class ViewController: UIViewController {
    @IBOutlet var viewMain:UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let urlVideo = NSBundle.mainBundle().URLForResource("IMG_9401", withExtension: "mov") {
            let videoPlayer = AVPlayer(playerItem: AVPlayerItem(URL: urlVideo))
            let videoLayer = AVPlayerLayer(player: videoPlayer)
            videoLayer.frame = viewMain.bounds
            viewMain.layer.addSublayer(videoLayer)
            videoPlayer.play()
        }
    }

    @IBAction func test() {
        UIGraphicsBeginImageContext(view.frame.size)
        if let layer = viewMain.layer.presentationLayer() {
            layer.renderInContext(UIGraphicsGetCurrentContext()!)
        }
        UIGraphicsEndImageContext()
    }
}

Fix the problem that the project could not built for bug_repro target.

//
//  ViewController.swift
//  bug_repro
//
//  Created by satoshi on 8/23/16.
//  Copyright © 2016 Satoshi Nakajima. All rights reserved.
//

import UIKit
import AVFoundation

//
// I reported this bug to Apple on August 25, 2016. Bug# 27982201.
//
class ViewController: UIViewController {
    @IBOutlet var viewMain:UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let urlVideo = Bundle.main.url(forResource: "IMG_9401", withExtension: "mov") {
            let videoPlayer = AVPlayer(playerItem: AVPlayerItem(url: urlVideo))
            let videoLayer = AVPlayerLayer(player: videoPlayer)
            videoLayer.frame = viewMain.bounds
            viewMain.layer.addSublayer(videoLayer)
            videoPlayer.play()
        }
    }

    @IBAction func test() {
        UIGraphicsBeginImageContext(view.frame.size)
        if let layer = viewMain.layer.presentation() {
            layer.render(in: UIGraphicsGetCurrentContext()!)
        }
        UIGraphicsEndImageContext()
    }
}


import XCTest

class TestModelListParser:XCTestCase
{
}

Create test for factory url

import XCTest
@testable import worldcities

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


// This test specifically exercises the interpreter's top-level error handler.
// RUN: not --crash %target-jit-run %s
// REQUIRES: swift_interpreter

// rdar://20809122
enum Error : ErrorType { case Foo }
throw Error.Foo

Test that message throwing from main identifies error.

// This test specifically exercises the interpreter's top-level error handler.
// RUN: not --crash %target-jit-run %s 2>&1 | FileCheck %s
// REQUIRES: swift_interpreter

// rdar://20809122
// CHECK: Error raised at top level: return_from_main.Error.Foo
enum Error : ErrorType { case Foo }
throw Error.Foo


public class BaseProblem
{
    func run() -> Int
    {
        println("Base class implementation")
        return 0
    }
}

class Evaluator
{
    var map: [Int: () -> Int] = [:]

    init()
    {
        map[1] = { Problem1().run() }
        map[2] = { Problem2().run() }
    }

    func evaluate(n: Int)
    {
        if let problemBlock = map[n]
        {
            let foo = problemBlock()
            println("foo = \(foo)")
        }
    }
}

Fix a warning in the test.

public class BaseProblem
{
    func run() -> Int
    {
        println("Base class implementation")
        return 0
    }
}

class Evaluator
{
    var map: [Int: () -> Int] = [:]

    init()
    {
        map[1] = { Problem1().run() }
        map[2] = { Problem2().run() }
    }

    func evaluate(n: Int)
    {
        if let problemBlock? = map[n]
        {
            let foo = problemBlock()
            println("foo = \(foo)")
        }
    }
}


//
//  Test.swift
//  TestingStuff
//
//  Created by Rui Peres on 15/11/2015.
//  Copyright © 2015 Test. All rights reserved.
//

import LazyJSON

struct Person {
    let firstName: String
    let secondName: String?
    let age: Int
    let hobbies: [String]
    let description: String
}

extension Person: Decodable {
    static var decoder: Decoder<Person>.Function {
        return curry(self.init)
            <^> key(.Key("firstName"))
            <*> optKey(.Key("secondName"))
            <*> key(.Key("age"))
            <*> arrKey(.Key("hobbies"))
            <*> key(.Key("description"))
    }
}

private func curry<A, B, C, D, E, R>(f: (A, B, C, D, E) -> R) -> A -> B -> C -> D -> E -> R {
    return { a in { b in { c in { d in { e in f(a,b,c,d,e) } } } } }
}

Fix the Profiler-iOS model decoding

//
//  Test.swift
//  TestingStuff
//
//  Created by Rui Peres on 15/11/2015.
//  Copyright © 2015 Test. All rights reserved.
//

import LazyJSON

struct Person {
    let firstName: String
    let secondName: String?
    let age: Int
    let hobbies: [String]
    let description: String
}

extension Person: Decodable {
    static var decoder: Decoder<Person>.Function {
        return curry(self.init)
            <^> <~"firstName"
            <*> <~?"secondName"
            <*> <~"age"
            <*> <|"hobbies"
            <*> <~"description"
    }
}

private func curry<A, B, C, D, E, R>(f: (A, B, C, D, E) -> R) -> A -> B -> C -> D -> E -> R {
    return { a in { b in { c in { d in { e in f(a,b,c,d,e) } } } } }
}


import PackageDescription

let package = Package(
    name: "swtws",
    dependencies: [
        .Package(url: "https://github.com/swift-tweets/tweetup-kit.git", "0.1.0-beta")
    ]
)

Improve the version specification of TweetupKit

import PackageDescription

let package = Package(
    name: "swtws",
    dependencies: [
        .Package(url: "https://github.com/swift-tweets/tweetup-kit.git", majorVersion: 0)
    ]
)


// 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: "AudioKit",
    platforms: [.macOS(.v10_14), .iOS(.v13), .tvOS(.v13)],
    products: [.library(name: "AudioKit", targets: ["AudioKit", "AudioKitEX"])],
    targets: [
        .target(name: "AudioKit"),
        .target(name: "AudioKitEX", dependencies: ["AudioKit", "CAudioKitEX"]),
        .target(name: "CAudioKitEX"),
        .testTarget(name: "AudioKitTests", dependencies: ["AudioKit"], resources: [.copy("TestResources/")]),
        .testTarget(name: "AudioKitEXTests", dependencies: ["AudioKitEX"], resources: [.copy("TestResources/")])
    ],
    cxxLanguageStandard: .cxx14
)

Bring back public headers search path

// 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: "AudioKit",
    platforms: [.macOS(.v10_14), .iOS(.v13), .tvOS(.v13)],
    products: [.library(name: "AudioKit", targets: ["AudioKit", "AudioKitEX"])],
    targets: [
        .target(name: "AudioKit"),
        .target(name: "AudioKitEX", dependencies: ["AudioKit", "CAudioKitEX"]),
        .target(name: "CAudioKitEX", publicHeadersPath: "include"),
        .testTarget(name: "AudioKitTests", dependencies: ["AudioKit"], resources: [.copy("TestResources/")]),
        .testTarget(name: "AudioKitEXTests", dependencies: ["AudioKitEX"], resources: [.copy("TestResources/")])
    ],
    cxxLanguageStandard: .cxx14
)


import PackageDescription

let package = Package(
    name: "JWTKeychain",
    dependencies: [
        .Package(url: "https://github.com/vapor/vapor.git", Version(2,0,0, prereleaseIdentifiers: ["beta"])),
        .Package(url: "https://github.com/vapor/mysql-provider.git", Version(2,0,0, prereleaseIdentifiers: ["beta"])),
        .Package(url: "https://github.com/vapor/jwt-provider.git", Version(1,0,0, prereleaseIdentifiers: ["beta"])),
        .Package(url: "https://github.com/vapor/bcrypt.git", Version(1,0,0, prereleaseIdentifiers: ["beta"])),
        .Package(url: "https://github.com/nodes-vapor/sugar.git", Version(2,0,0, prereleaseIdentifiers: ["beta"])),
        .Package(url: "https://github.com/nodes-vapor/flash.git", Version(1,0,0, prereleaseIdentifiers: ["beta"]))
    ]
)

Update dependencies for Vapor 2

import PackageDescription

let package = Package(
    name: "JWTKeychain",
    dependencies: [
        .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 2),
        .Package(url: "https://github.com/vapor/mysql-provider.git", majorVersion: 2),
        // TODO: update url once PR is accepted
        .Package(url: "https://github.com/siemensikkema/jwt-provider.git", majorVersion: 1),
        .Package(url: "https://github.com/vapor/bcrypt.git", majorVersion: 1),
        .Package(url: "https://github.com/nodes-vapor/sugar.git", majorVersion: 2),
        .Package(url: "https://github.com/nodes-vapor/flash.git", majorVersion: 1)
    ]
)


// swift-tools-version:5.1
import PackageDescription

let package = Package(
    name: "OneTimePassword",
    platforms: [
        .iOS(.v9),
        .watchOS(.v2),
    ],
    products: [
        .library(
            name: "OneTimePassword",
            targets: ["OneTimePassword"]),
    ],
    dependencies: [
        .package(url: "https://github.com/mattrubin/Base32.git", .branch("1.1.2+spm")),
    ],
    targets: [
        .target(
            name: "OneTimePassword",
            dependencies: ["Base32"],
            path: "Sources"),
        .testTarget(
            name: "OneTimePasswordTests",
            dependencies: ["OneTimePassword"],
            path: "Tests",
            exclude: ["App"]),
    ]
)

Exclude KeychainTests from SPM tests

// swift-tools-version:5.1
import PackageDescription

let package = Package(
    name: "OneTimePassword",
    platforms: [
        .iOS(.v9),
        .watchOS(.v2),
    ],
    products: [
        .library(
            name: "OneTimePassword",
            targets: ["OneTimePassword"]),
    ],
    dependencies: [
        .package(url: "https://github.com/mattrubin/Base32.git", .branch("1.1.2+spm")),
    ],
    targets: [
        .target(
            name: "OneTimePassword",
            dependencies: ["Base32"],
            path: "Sources"),
        .testTarget(
            name: "OneTimePasswordTests",
            dependencies: ["OneTimePassword"],
            path: "Tests",
            exclude: ["App", "KeychainTests.swift"]),
    ]
)


import UIKit
import AVFoundation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // prevent device from going to sleep
        application.isIdleTimerDisabled = true

        // applies the included tint colour to UIAlertController (and presumably others)
        window?.tintColor = .tintColor

        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        #warning("Missing implementation for opening urls")
        return false
    }

    func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
        return true
    }

    func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
        return true
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        Engine.shared.isInBackground = true
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        Engine.shared.isInBackground = false
    }

}

Add untested implementation to open a file from outside of the app.

import UIKit
import AVFoundation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // prevent device from going to sleep
        application.isIdleTimerDisabled = true

        // applies the included tint colour to UIAlertController (and presumably others)
        window?.tintColor = .tintColor

        return true
    }

    #warning("Needs testing on device")
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        guard
            url.isFileURL,
            let showBrowser = window?.rootViewController as? ShowBrowserViewController
        else { return false }

        if let playbackVC = showBrowser.presentedViewController as? PlaybackViewController {
            playbackVC.closeShow()
        }

        showBrowser.openShow(at: url)

        return true
    }

    func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
        return true
    }

    func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
        return true
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        Engine.shared.isInBackground = true
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        Engine.shared.isInBackground = false
    }

}


//
//  Protocols.swift
//  SWCompression
//
//  Created by Timofey Solomko on 29.10.16.
//  Copyright © 2017 Timofey Solomko. All rights reserved.
//

import Foundation

/// Abstract archive class which supports unarchiving.
public protocol Archive {

    /// Abstract unarchive function.
    static func unarchive(archiveData: Data) throws -> Data

    /// Abstract archive function.
    static func archive(data: Data, options: [ArchiveOption]) throws -> Data

}

/// Abstract decompression algorithm class which supports decompression.
public protocol DecompressionAlgorithm {

    /// Abstract decompress function.
    static func decompress(compressedData: Data) throws -> Data

}

public protocol Container {

    static func open(containerData: Data) throws -> [ContainerEntry]

}

public protocol ContainerEntry {

    var name: String { get }
    var size: Int { get }
    var isDirectory: Bool { get }

    func data() throws -> Data

}

Revert "Added archive(...) function to Archive protocol with options argument."

//
//  Protocols.swift
//  SWCompression
//
//  Created by Timofey Solomko on 29.10.16.
//  Copyright © 2017 Timofey Solomko. All rights reserved.
//

import Foundation

/// Abstract archive class which supports unarchiving.
public protocol Archive {

    /// Abstract unarchive function.
    static func unarchive(archiveData: Data) throws -> Data

}

/// Abstract decompression algorithm class which supports decompression.
public protocol DecompressionAlgorithm {

    /// Abstract decompress function.
    static func decompress(compressedData: Data) throws -> Data

}

public protocol Container {

    static func open(containerData: Data) throws -> [ContainerEntry]

}

public protocol ContainerEntry {

    var name: String { get }
    var size: Int { get }
    var isDirectory: Bool { get }

    func data() throws -> Data

}


import Result
import Swish

private struct DeleteIdentityRequest: Request, AuthenticatedRequest {
    typealias ResponseType = Void

    let token: String
    let identity: Identity

    func build() -> NSURLRequest {
        return request(.GET, "user/identities/remove/\(identity.id)", token: token)
    }
}

public extension APIClient {
    /// Delete the provided `identity`.
    /// - parameter identity: The identity to be deleted.
    func deleteIdentity(identity: Identity, completionHandler: Result<Void, NSError> -> Void) {
        let request = DeleteIdentityRequest(token: token, identity: identity)
        client.performRequest(request, completionHandler: completionHandler)
    }
}

Use the EmptyResponse type from Swish.

import Result
import Swish

private struct DeleteIdentityRequest: Request, AuthenticatedRequest {
    typealias ResponseType = EmptyResponse

    let token: String
    let identity: Identity

    func build() -> NSURLRequest {
        return request(.GET, "user/identities/remove/\(identity.id)", token: token)
    }
}

public extension APIClient {
    /// Delete the provided `identity`.
    /// - parameter identity: The identity to be deleted.
    func deleteIdentity(identity: Identity, completionHandler: Result<EmptyResponse, NSError> -> Void) {
        let request = DeleteIdentityRequest(token: token, identity: identity)
        client.performRequest(request, completionHandler: completionHandler)
    }
}


//
//  PrintWorkingDirectory.swift
//  SwiftShell
//
//  Created by Justin Jia on 4/15/16.
//  Copyright © 2016 SwiftShell. The MIT License (MIT).
//

import Foundation

public func pwd(folding: Bool = false, unlessExceeds limit: Int? = nil) -> String {
    print(command: "pwd")
    let output = currentPath(folding: folding, unlessExceeds: limit)
    print(output)
    return output
}

func currentPath(folding: Bool = false, unlessExceeds limit: Int? = nil) -> String {
    var buffer: [Int8] = Array(repeating: 0, count: Int(PATH_MAX))
    getcwd(&buffer, buffer.count)
    var output = String(cString: buffer) ?? ""

    guard folding == true, limit == nil || limit > output.characters.count else { return output }

    let pathComponents = output.characters.split { $0 == "/" }.map(String.init)
    if let firstPathComponents = pathComponents.first, let lastPathComponents = pathComponents.last {
        output = firstPathComponents + "/.../" + lastPathComponents
    }

    return output
}

Fix output with too few components while folding is true

//
//  PrintWorkingDirectory.swift
//  SwiftShell
//
//  Created by Justin Jia on 4/15/16.
//  Copyright © 2016 SwiftShell. The MIT License (MIT).
//

import Foundation

public func pwd(folding: Bool = false, unlessExceeds limit: Int? = nil) -> String {
    print(command: "pwd")
    let output = currentPath(folding: folding, unlessExceeds: limit)
    print(output)
    return output
}

func currentPath(folding: Bool = false, unlessExceeds limit: Int? = nil) -> String {
    var buffer: [Int8] = Array(repeating: 0, count: Int(PATH_MAX))
    getcwd(&buffer, buffer.count)
    var output = String(cString: buffer) ?? ""

    guard folding == true, limit == nil || limit > output.characters.count else { return output }

    let pathComponents = output.characters.split { $0 == "/" }.map(String.init)
    guard pathComponents.count > 2 else { return output }

    if let firstPathComponents = pathComponents.first, let lastPathComponents = pathComponents.last {
        output = firstPathComponents + "/.../" + lastPathComponents
    }

    return output
}


//
//  UIColor+Images.swift
//  Pods
//
//  Created by Gregory Sholl e Santos on 05/06/17.
//
//

import UIKit

public extension UIColor {

    // MARK: - Generate Image

    class func imageWith(color: UIColor) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)

        UIGraphicsBeginImageContext(rect.size)

        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }

        context.setFillColor(color.cgColor)
        context.fill(rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return image
    }
}

Change MARK notation to fit to the project's pattern

//
//  UIColor+Images.swift
//  Pods
//
//  Created by Gregory Sholl e Santos on 05/06/17.
//
//

import UIKit

// MARK: - Generate Image

public extension UIColor {

    class func imageWith(color: UIColor) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)

        UIGraphicsBeginImageContext(rect.size)

        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }

        context.setFillColor(color.cgColor)
        context.fill(rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return image
    }
}


import Benchmark

benchmark("add string no capacity") {
    var x1: String = ""
    for _ in 1...1000 {
        x1 += "hi"
    }
}

benchmark("add string reserved capacity") {
    var x2: String = ""
    x2.reserveCapacity(1000)
    for _ in 1...1000 {
        x2 += "hi"
    }
}

Benchmark.main()

Fix capacity in example benchmark

import Benchmark

benchmark("add string no capacity") {
    var x1: String = ""
    for _ in 1...1000 {
        x1 += "hi"
    }
}

benchmark("add string reserved capacity") {
    var x2: String = ""
    x2.reserveCapacity(2000)
    for _ in 1...1000 {
        x2 += "hi"
    }
}

Benchmark.main()


//
//  User.swift
//  WhoToFollow
//
//  Created by Hideaki Ishii on 9/21/15.
//
//

import Foundation
import RxSwift

class User {

    // MARK: - Properties

    let name: String
    let url: String
    let avatarUrl: String

    static let apiClient = GithubAPIClient.sharedInstance

    // MARK: - Initializers

    init(name: String, url: String, avatarUrl: String) {
        self.name = name
        self.url = url
        self.avatarUrl = avatarUrl
    }

    // MARK: - Static methods

    static func fetch() -> Observable<[User]> {
        return self.apiClient.request(path: "users")
            .observeOn(self.apiClient.backgroundScheduler)
            .map { json in
                guard let json = json as? [AnyObject] else { throw commonError("Cast failed") }
                return try self.parseJSON(json)
            }
            .observeOn(self.apiClient.mainScheduler)
    }

    static func parseJSON(json: [AnyObject]) throws -> [User] {
        return try json.map { result in
            guard let name = result["login"] as? String else { throw commonError("Parse error") }
            guard let url = result["html_url"] as? String else { throw commonError("Parse error") }
            guard let avatarUrl = result["avatar_url"] as? String else { throw commonError("Parse error") }

            return User(name: name, url: url, avatarUrl: avatarUrl)
        }
    }

}

Fix to fetch with the random offset

//
//  User.swift
//  WhoToFollow
//
//  Created by Hideaki Ishii on 9/21/15.
//
//

import Foundation
import RxSwift

class User {

    // MARK: - Properties

    let name: String
    let url: String
    let avatarUrl: String

    static let apiClient = GithubAPIClient.sharedInstance

    // MARK: - Initializers

    init(name: String, url: String, avatarUrl: String) {
        self.name = name
        self.url = url
        self.avatarUrl = avatarUrl
    }

    // MARK: - Static methods

    static func fetch() -> Observable<[User]> {
        let randomOffset = String(arc4random() % 500)
        return self.apiClient.request(path: "users", params: ["since": randomOffset])
            .observeOn(self.apiClient.backgroundScheduler)
            .map { json in
                guard let json = json as? [AnyObject] else { throw commonError("Cast failed") }
                return try self.parseJSON(json)
            }
            .observeOn(self.apiClient.mainScheduler)
    }

    static func parseJSON(json: [AnyObject]) throws -> [User] {
        return try json.map { result in
            guard let name = result["login"] as? String else { throw commonError("Parse error") }
            guard let url = result["html_url"] as? String else { throw commonError("Parse error") }
            guard let avatarUrl = result["avatar_url"] as? String else { throw commonError("Parse error") }

            return User(name: name, url: url, avatarUrl: avatarUrl)
        }
    }

}


//
//  AppDelegate.swift
//  HomeControl
//
//  Created by Julian Grosshauser on 06/11/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    //MARK: Properties

    var window: UIWindow? = {
        let window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window.backgroundColor = .whiteColor()
        return window
    }()

    private let store = Store()

    //MARK: UIApplicationDelegate

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window?.rootViewController = UINavigationController(rootViewController: SetupController())
        window?.makeKeyAndVisible()
        return true
    }
}

Add helper methods to app delegate

//
//  AppDelegate.swift
//  HomeControl
//
//  Created by Julian Grosshauser on 06/11/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    //MARK: Properties

    var window: UIWindow? = {
        let window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window.backgroundColor = .whiteColor()
        return window
    }()

    private let store = Store()

    //MARK: UIApplicationDelegate

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window?.rootViewController = UINavigationController(rootViewController: SetupController())
        window?.makeKeyAndVisible()
        return true
    }

    //MARK: Helpers

    private func fetchRooms() -> [Room] {
        let request = ManagedRoom.sortedFetchRequest
        request.returnsObjectsAsFaults = false
        request.relationshipKeyPathsForPrefetching = ["lights", "blinds", "consumers"]

        do {
            guard let rooms = try store.context.executeFetchRequest(request) as? [ManagedRoom] else {
                fatalError("Fetched objects should be of type ManagedRoom")
            }

            return rooms.map {
                $0.immutable
            }
        } catch {
            fatalError("Executing fetch request failed")
        }
    }

    private func setupRootViewController(rooms: [Room]) -> UIViewController {
        if rooms.isEmpty {
            return SetupController(viewModel: SetupViewModel(store: store))
        }

        // TODO: Set up UI
        return UIViewController()
    }
}


#if os(iOS)
    import UIKit
#endif

public class NetworkActivityIndicator {

    /**
     The shared instance.
     */
    public static let sharedIndicator = NetworkActivityIndicator()

    /**
     The number of activities in progress.
     */
    internal var activitiesCount = 0

    /**
     A Boolean value that turns an indicator of network activity on or off.

     Specify true if the app should show network activity and false if it should not. The default value is false. A spinning indicator in the status bar shows network activity. Multiple calls to visible cause an internal counter to take care of persisting the number of times this method has being called.
     */
    public var visible: Bool = false {
        didSet {
            if visible {
                self.activitiesCount++
            } else {
                self.activitiesCount--
            }

            if self.activitiesCount < 0 {
                self.activitiesCount = 0
            }

            #if os(iOS)
                #if DEBUG
                    dispatch_async(dispatch_get_main_queue()) {
                        self.update()
                    }
                #else
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
                        self.update()
                    })
                #endif
            #endif
        }
    }

    private func update() {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = (self.activitiesCount > 0)
    }
}

Add iOS check for UIApplication

#if os(iOS)
    import UIKit
#endif

public class NetworkActivityIndicator {

    /**
     The shared instance.
     */
    public static let sharedIndicator = NetworkActivityIndicator()

    /**
     The number of activities in progress.
     */
    internal var activitiesCount = 0

    /**
     A Boolean value that turns an indicator of network activity on or off.

     Specify true if the app should show network activity and false if it should not. The default value is false. A spinning indicator in the status bar shows network activity. Multiple calls to visible cause an internal counter to take care of persisting the number of times this method has being called.
     */
    public var visible: Bool = false {
        didSet {
            if visible {
                self.activitiesCount++
            } else {
                self.activitiesCount--
            }

            if self.activitiesCount < 0 {
                self.activitiesCount = 0
            }

            #if DEBUG
                dispatch_async(dispatch_get_main_queue()) {
                    self.update()
                }
            #else
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
                    self.update()
                })
            #endif
        }
    }

    private func update() {
        #if os(iOS)
            UIApplication.sharedApplication().networkActivityIndicatorVisible = (self.activitiesCount > 0)
        #endif
    }
}


/*
The MIT License (MIT)

Copyright (c) 2015 CawBox

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 UIKit

@IBDesignable
class RoundedImageView: UIImageView {
    @IBInspectable var radius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = radius
            layer.masksToBounds = radius > 0
        }
    }

    @IBInspectable var border: CGFloat = 0 {
        didSet {
            layer.borderWidth = border
            layer.borderColor = tintColor.CGColor

            layer.shadowColor = tintColor.CGColor
            layer.shadowOffset = CGSize (width: 5, height: 5)
            layer.shadowOpacity = 1
        }
    }
}

Drop shadow has been moved to the cell

/*
The MIT License (MIT)

Copyright (c) 2015 CawBox

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 UIKit

@IBDesignable
class RoundedImageView: UIImageView {
    @IBInspectable var radius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = radius
            layer.masksToBounds = radius > 0
        }
    }

    @IBInspectable var border: CGFloat = 0 {
        didSet {
            layer.borderWidth = border
            layer.borderColor = tintColor.CGColor
        }
    }
}


//
//  PreviewViewController.swift
//  Utilities
//
//  Created by Caio Mello on August 22, 2017.
//  Copyright © 2017 Caio Mello. All rights reserved.
//

import UIKit

public protocol Previewable {
	func previewImageAspectRatio() -> CGSize
	func previewImageDownloadBlock(_ completion: (UIImage?) -> Void)
}

public class PreviewViewController: UIViewController {
	@IBOutlet private var imageView: UIImageView!

	public var item: Previewable?
	private var previewActions: [UIPreviewActionItem] = []

	override public var previewActionItems: [UIPreviewActionItem] {
		return previewActions
	}
}

// MARK: - View

extension PreviewViewController {
	override public func viewDidLoad() {
		super.viewDidLoad()
	}
}

// MARK: - Helpers

extension PreviewViewController {
	public class func controller(withItem item: Previewable, actions: [UIPreviewActionItem]) -> PreviewViewController? {
		let previewViewController = UIStoryboard(name: "Preview", bundle: Bundle(for: PreviewViewController.self)).instantiateInitialViewController() as? PreviewViewController
		previewViewController?.item = item
		previewViewController?.previewActions = actions
		previewViewController?.preferredContentSize = CGSize(width: item.previewImageAspectRatio().width, height: item.previewImageAspectRatio().height)

		item.previewImageDownloadBlock { (image) in
			previewViewController?.imageView.image = image
		}

		return previewViewController
	}
}

Fix block issue on previewable protocol

//
//  PreviewViewController.swift
//  Utilities
//
//  Created by Caio Mello on August 22, 2017.
//  Copyright © 2017 Caio Mello. All rights reserved.
//

import UIKit

public protocol Previewable {
	func previewImageAspectRatio() -> CGSize
	func previewImageDownloadBlock(_ completion: @escaping (UIImage?) -> Void)
}

public class PreviewViewController: UIViewController {
	@IBOutlet private var imageView: UIImageView!

	public var item: Previewable?
	private var previewActions: [UIPreviewActionItem] = []

	override public var previewActionItems: [UIPreviewActionItem] {
		return previewActions
	}
}

// MARK: - View

extension PreviewViewController {
	override public func viewDidLoad() {
		super.viewDidLoad()
	}
}

// MARK: - Helpers

extension PreviewViewController {
	public class func controller(withItem item: Previewable, actions: [UIPreviewActionItem]) -> PreviewViewController? {
		let previewViewController = UIStoryboard(name: "Preview", bundle: Bundle(for: PreviewViewController.self)).instantiateInitialViewController() as? PreviewViewController
		previewViewController?.item = item
		previewViewController?.previewActions = actions
		previewViewController?.preferredContentSize = CGSize(width: item.previewImageAspectRatio().width, height: item.previewImageAspectRatio().height)

		item.previewImageDownloadBlock { (image) in
			previewViewController?.imageView.image = image
		}

		return previewViewController
	}
}


import Argo
import Nimble
import Portal
import Quick

class UserSpec: QuickSpec {
    override func spec() {
        let avatarURL = "https://s.gravatar.com/avatar/6a12a226806bb77aa45dac4133d76227"
        let emailAddress = "bear@thegrid.io"
        let founderNumber = 0
        let id = "f03c6cf1-74ce-4c01-b8fe-cef0f2443e46"
        let name = "Grid Bear"
        let sitesQuota = 7

        let json: JSON = .Object([
            "avatar": .String(avatarURL),
            "email": .String(emailAddress),
            "founder": .Number(founderNumber),
            "id": .String(id),
            "name": .String(name),
            "quotaSites": .Number(sitesQuota)
        ])

        let user = User(
            avatarURL: NSURL(string: avatarURL),
            emailAddress: emailAddress,
            founderNumber: founderNumber,
            id: NSUUID(UUIDString: id)!,
            name: name,
            sitesQuota: sitesQuota
        )

        describe("decoding") {
            it("should produce a User") {
                guard let decoded = User.decode(json).value else {
                    return XCTFail("Unable to decode JSON: \(json)")
                }
                expect(decoded).to(equal(user))
            }
        }

        describe("encoding") {
            it("should produce JSON") {
                let encoded = user.encode()
                expect(encoded).to(equal(json))
            }
        }
    }
}

Add missing import to User model spec.

import Argo
import Nimble
import Ogra
import Portal
import Quick

class UserSpec: QuickSpec {
    override func spec() {
        let avatarURL = "https://s.gravatar.com/avatar/6a12a226806bb77aa45dac4133d76227"
        let emailAddress = "bear@thegrid.io"
        let founderNumber = 0
        let id = "f03c6cf1-74ce-4c01-b8fe-cef0f2443e46"
        let name = "Grid Bear"
        let sitesQuota = 7

        let json: JSON = .Object([
            "avatar": .String(avatarURL),
            "email": .String(emailAddress),
            "founder": .Number(founderNumber),
            "id": .String(id),
            "name": .String(name),
            "quotaSites": .Number(sitesQuota)
        ])

        let user = User(
            avatarURL: NSURL(string: avatarURL),
            emailAddress: emailAddress,
            founderNumber: founderNumber,
            id: NSUUID(UUIDString: id)!,
            name: name,
            sitesQuota: sitesQuota
        )

        describe("decoding") {
            it("should produce a User") {
                guard let decoded = User.decode(json).value else {
                    return XCTFail("Unable to decode JSON: \(json)")
                }
                expect(decoded).to(equal(user))
            }
        }

        describe("encoding") {
            it("should produce JSON") {
                let encoded = user.encode()
                expect(encoded).to(equal(json))
            }
        }
    }
}


//
//  ChapterPageCollectionViewController.swift
//  Yomu
//
//  Created by Sendy Halim on 7/20/16.
//  Copyright © 2016 Sendy Halim. All rights reserved.
//

import Cocoa

class ChapterPageCollectionViewController: NSViewController {
  let vm: ChapterPageCollectionViewModel

  init(viewModel: ChapterPageCollectionViewModel) {
    vm = viewModel

    super.init(nibName: "ChapterPageCollection", bundle: nil)!
  }

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

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do view setup here.
  }
}

Implement data source protocol for chapter page collection

//
//  ChapterPageCollectionViewController.swift
//  Yomu
//
//  Created by Sendy Halim on 7/20/16.
//  Copyright © 2016 Sendy Halim. All rights reserved.
//

import Cocoa
import RxSwift

class ChapterPageCollectionViewController: NSViewController {
  @IBOutlet weak var collectionView: NSCollectionView!

  let vm: ChapterPageCollectionViewModel
  let disposeBag = DisposeBag()

  init(viewModel: ChapterPageCollectionViewModel) {
    vm = viewModel

    super.init(nibName: "ChapterPageCollection", bundle: nil)!
  }

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

  override func viewDidLoad() {
    super.viewDidLoad()

    collectionView.dataSource = self

    vm.chapterPages
      .driveNext { [weak self] _ in
        self?.collectionView.reloadData()
      } >>> disposeBag

    vm.fetch() >>> disposeBag
  }
}

extension ChapterPageCollectionViewController: NSCollectionViewDataSource {
  func numberOfSectionsInCollectionView(collectionView: NSCollectionView) -> Int {
    return 1
  }

  func collectionView(
    collectionView: NSCollectionView,
    numberOfItemsInSection section: Int
  ) -> Int {
    return vm.count
  }

  func collectionView(
    collectionView: NSCollectionView,
    itemForRepresentedObjectAtIndexPath indexPath: NSIndexPath
  ) -> NSCollectionViewItem {
    let cell = collectionView.makeItemWithIdentifier(
      "ChapterPageItem",
      forIndexPath: indexPath
    ) as! ChapterPageItem

    let pageViewModel = vm[indexPath.item]

    pageViewModel.imageUrl.driveNext(cell.pageImageView.setImageWithUrl) >>> disposeBag

    return cell
  }
}


/**
 * Question Link: https://leetcode.com/problems/reverse-vowels-of-a-string/
 * Primary idea: Two pointers, iterate the string and swap two characters each time,
 *
 * Note: the input String is case sensitive; thus "aA" should be transferred to "Aa"
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 */

class ReverseVowelsOfAString {
    func reverseVowels(s: String) -> String {
        var left = 0
        var right = s.characters.count - 1
        var chars = [Character](s.characters)

        while left < right {
            while left < right && !_isVowel(chars[left]) {
                left += 1
            }
            while left < right && !_isVowel(chars[right]) {
                right -= 1
            }
            guard left < right else {
                break
            }
            _swap(&chars, left, right)
            left += 1
            right -= 1
        }

        return String(chars)
    }

    private func _isVowel(char: Character) -> Bool {
        var char = String(char).lowercaseString
        if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
            return true
        }

        return false
    }

    private func _swap(inout chars: [Character], _ p: Int, _ q: Int) {
        var temp = chars[p]
        chars[p] = chars[q]
        chars[q] = temp
    }
}

Change swap function to generic type

/**
 * Question Link: https://leetcode.com/problems/reverse-vowels-of-a-string/
 * Primary idea: Two pointers, iterate the string and swap two characters each time,
 *
 * Note: the input String is case sensitive; thus "aA" should be transferred to "Aa"
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 */

class ReverseVowelsOfAString {
    func reverseVowels(s: String) -> String {
        var left = 0
        var right = s.characters.count - 1
        var chars = [Character](s.characters)

        while left < right {
            while left < right && !_isVowel(chars[left]) {
                left += 1
            }
            while left < right && !_isVowel(chars[right]) {
                right -= 1
            }
            guard left < right else {
                break
            }
            _swap(&chars, left, right)
            left += 1
            right -= 1
        }

        return String(chars)
    }

    private func _isVowel(char: Character) -> Bool {
        var char = String(char).lowercaseString
        if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
            return true
        }

        return false
    }

    private func _swap<T>(inout chars: Array<T>, _ p: Int, _ q: Int) {
        var temp = chars[p]
        chars[p] = chars[q]
        chars[q] = temp
    }
}


//
//  CSV+init.swift
//  CSV
//
//  Created by Yasuhiro Hatta on 2016/06/13.
//  Copyright © 2016 yaslab. All rights reserved.
//

import Foundation

extension CSV {

    public init(
        path: String,
        encoding: String.Encoding = defaultEncoding,
        hasHeaderRow: Bool = defaultHasHeaderRow,
        delimiter: UnicodeScalar = defaultDelimiter)
        throws
    {
        guard let stream = InputStream(fileAtPath: path) else {
            throw CSVError.StreamError
        }
        try self.init(stream: stream, encoding: encoding, hasHeaderRow: hasHeaderRow, delimiter: delimiter)
    }

    public init(
        url: URL,
        encoding: String.Encoding = defaultEncoding,
        hasHeaderRow: Bool = defaultHasHeaderRow,
        delimiter: UnicodeScalar = defaultDelimiter)
        throws
    {
        guard let stream = InputStream(url: url) else {
            throw CSVError.StreamError
        }
        try self.init(stream: stream, encoding: encoding, hasHeaderRow: hasHeaderRow, delimiter: delimiter)
    }

    public init(
        string: String,
        hasHeaderRow: Bool = defaultHasHeaderRow,
        delimiter: UnicodeScalar = defaultDelimiter)
        throws
    {
        var iterator = string.unicodeScalars.makeIterator()
        try self.init(iterator: &iterator, hasHeaderRow: hasHeaderRow, delimiter: delimiter)
    }

}

Rename CSV(path: ...) with CSV(fileAtPath: ...)

//
//  CSV+init.swift
//  CSV
//
//  Created by Yasuhiro Hatta on 2016/06/13.
//  Copyright © 2016 yaslab. All rights reserved.
//

import Foundation

extension CSV {

    public init(
        fileAtPath path: String,
        encoding: String.Encoding = defaultEncoding,
        hasHeaderRow: Bool = defaultHasHeaderRow,
        delimiter: UnicodeScalar = defaultDelimiter)
        throws
    {
        guard let stream = InputStream(fileAtPath: path) else {
            throw CSVError.StreamError
        }
        try self.init(stream: stream, encoding: encoding, hasHeaderRow: hasHeaderRow, delimiter: delimiter)
    }

    public init(
        url: URL,
        encoding: String.Encoding = defaultEncoding,
        hasHeaderRow: Bool = defaultHasHeaderRow,
        delimiter: UnicodeScalar = defaultDelimiter)
        throws
    {
        guard let stream = InputStream(url: url) else {
            throw CSVError.StreamError
        }
        try self.init(stream: stream, encoding: encoding, hasHeaderRow: hasHeaderRow, delimiter: delimiter)
    }

    public init(
        string: String,
        hasHeaderRow: Bool = defaultHasHeaderRow,
        delimiter: UnicodeScalar = defaultDelimiter)
        throws
    {
        var iterator = string.unicodeScalars.makeIterator()
        try self.init(iterator: &iterator, hasHeaderRow: hasHeaderRow, delimiter: delimiter)
    }

}


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

/// Returns a parser which maps parse trees into another type.
public func --> <C: CollectionType, T, U>(parser: Parser<C, T>.Function, f: (C, Range<C.Index>, T) -> U) -> Parser<C, U>.Function {
	return { input, sourcePos in
		parser(input, sourcePos).map { (f(input, sourcePos.index..<$1.index, $0), $1) }
	}
}

/// Returns a parser which maps parse results.
///
/// This enables e.g. adding identifiers for error handling.
public func --> <C: CollectionType, T, U> (parser: Parser<C, T>.Function, transform: Parser<C, T>.Result -> Parser<C, U>.Result) -> Parser<C, U>.Function {
	return parser >>> transform
}

import Prelude

Add an override for -->

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

/// Returns a parser which maps parse trees into another type.
public func --> <C: CollectionType, T, U>(parser: Parser<C, T>.Function, f: (C, SourcePos<C.Index>, Range<C.Index>, T) -> U) -> Parser<C, U>.Function {
	return { input, inputPos in
		parser(input, inputPos).map { output, outputPos in
			(f(input, outputPos, inputPos.index..<outputPos.index, output), outputPos)
		}
	}
}

public func --> <C: CollectionType, T, U>(parser: Parser<C, T>.Function, f: (SourcePos<C.Index>, Range<C.Index>, T) -> U) -> Parser<C, U>.Function {
	return parser --> { f($1, $2, $3) }
}

/// Returns a parser which maps parse results.
///
/// This enables e.g. adding identifiers for error handling.
public func --> <C: CollectionType, T, U> (parser: Parser<C, T>.Function, transform: Parser<C, T>.Result -> Parser<C, U>.Result) -> Parser<C, U>.Function {
	return parser >>> transform
}

import Prelude


import Foundation
import XCTest

class MockFunc<Input, Output> {
    typealias MockedFunc = (Input) -> (Output)
    typealias Callback = (Input) -> (Output)

    var capturedArguments: [(Input)] = []
    var callback: Callback!

    func call(input: Input) -> (Output) {
        capturedArguments.append(input)
        return callback(input)
    }

    func when(callback: Callback) {
        self.callback = callback
    }

    var timesCalled: Int {
        get {
            return self.capturedArguments.count
        }
    }
}

func when<Input, Output>(mockFunc: MockFunc<Input, Output>, callback: MockFunc<Input, Output>.Callback) -> () {
    mockFunc.when(callback)
}

func mock<Input, Output>(realFunc: (Input) -> (Output)) -> MockFunc<Input, Output> {
    return MockFunc<Input, Output>()
}

prefix operator * {}
prefix func *<Input, Output>(mockFunc: MockFunc<Input, Output>) -> (MockFunc<Input, Output>.MockedFunc) {
    return mockFunc.call
}

extension XCTestCase {
    func verifyAtLeastOnce<Input, Output>(mockFunc: MockFunc<Input, Output>,
        inFile filePath: String = __FILE__,
        atLine lineNumber: UInt = __LINE__) -> () {
            if (mockFunc.timesCalled < 1) {
                self.recordFailureWithDescription("Mocked function was not called at least once", inFile: filePath, atLine: lineNumber, expected: true)
            }
    }
}

Move when() and mock() into XCTestCase extension

import Foundation
import XCTest

class MockFunc<Input, Output> {
    typealias MockedFunc = (Input) -> (Output)
    typealias Callback = (Input) -> (Output)

    var capturedArguments: [(Input)] = []
    var callback: Callback!

    func call(input: Input) -> (Output) {
        capturedArguments.append(input)
        return callback(input)
    }

    func when(callback: Callback) {
        self.callback = callback
    }

    var timesCalled: Int {
        get {
            return self.capturedArguments.count
        }
    }
}

extension XCTestCase {
    func verifyAtLeastOnce<Input, Output>(mockFunc: MockFunc<Input, Output>,
        inFile filePath: String = __FILE__,
        atLine lineNumber: UInt = __LINE__) -> () {
            if (mockFunc.timesCalled < 1) {
                self.recordFailureWithDescription("Mocked function was not called at least once", inFile: filePath, atLine: lineNumber, expected: true)
            }
    }

    func when<Input, Output>(mockFunc: MockFunc<Input, Output>, callback: MockFunc<Input, Output>.Callback) -> () {
        mockFunc.when(callback)
    }

    func mock<Input, Output>(realFunc: (Input) -> (Output)) -> MockFunc<Input, Output> {
        return MockFunc<Input, Output>()
    }
}

prefix operator * {}
prefix func *<Input, Output>(mockFunc: MockFunc<Input, Output>) -> (MockFunc<Input, Output>.MockedFunc) {
    return mockFunc.call
}


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

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

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

import BinaryTree
import XCTest

Test that leaves are not branches.

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

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

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

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

import BinaryTree
import XCTest


// RUN: %target-build-swift -target arm64-apple-ios8.0 -target-cpu cyclone \
// RUN:   -O -S %s -parse-as-library | \
// RUN:   FileCheck --check-prefix=TBI %s

// RUN: %target-build-swift -target arm64-apple-ios7.0 -target-cpu cyclone \
// RUN:     -O -S %s -parse-as-library | \
// RUN:   FileCheck --check-prefix=NO_TBI %s

// REQUIRES: CPU=arm64, OS=ios

// Verify that TBI is on by default in Swift on targets that support it. For our
// purposes this means iOS8.0 or later.

func f(i: Int) -> Int8 {
  let j = i & 0xff_ffff_ffff_ffff
// TBI-NOT: and
// NO_TBI: and
  let p = UnsafeMutablePointer<Int8>(bitPattern: j)
  return p[0]
}

Fix TBI test for SE-0055 (optional pointers).

// RUN: %target-build-swift -target arm64-apple-ios8.0 -target-cpu cyclone \
// RUN:   -O -S %s -parse-as-library -parse-stdlib | \
// RUN:   FileCheck --check-prefix=TBI %s

// RUN: %target-build-swift -target arm64-apple-ios7.0 -target-cpu cyclone \
// RUN:     -O -S %s -parse-as-library -parse-stdlib | \
// RUN:   FileCheck --check-prefix=NO_TBI %s

// REQUIRES: CPU=arm64, OS=ios

// Verify that TBI is on by default in Swift on targets that support it. For our
// purposes this means iOS8.0 or later.

import Swift

func f(i: Int) -> Int8 {
  let j = i & 0xff_ffff_ffff_ffff
// TBI-NOT: and
// NO_TBI: and
  guard let p = UnsafeMutablePointer<Int8>(bitPattern: j) else {
    // Make sure we optimize away this branch.
    Builtin.unreachable()
  }
  return p[0]
}


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

 Copyright 2015 - 2016 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

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

import struct Utility.Version

// FIXME: workaround for inability to constrain the extension to `Bound == Version`.
protocol _VersionProtocol : Comparable {}
extension Version : _VersionProtocol {}

extension Range where Bound : _VersionProtocol {

    /**
     - Returns: A new Range with startIndex and endIndex constrained such that
     the returned range is entirely within this Range and the provided Range.
     If the two ranges do not overlap at all returns `nil`.
     */
    func constrain(to constraint: Range) -> Range? {
        let start = Swift.max(self.lowerBound, constraint.lowerBound)
        let end = Swift.min(self.upperBound, constraint.upperBound)
        if start < end {
            return start..<end
        } else {
            return nil
        }
    }
}

Use concrete constrained extensions to get rid of protocol conformance trick.

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

 Copyright 2015 - 2016 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

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

import struct Utility.Version

extension Range where Bound == Version {

    /**
     - Returns: A new Range with startIndex and endIndex constrained such that
     the returned range is entirely within this Range and the provided Range.
     If the two ranges do not overlap at all returns `nil`.
     */
    func constrain(to constraint: Range) -> Range? {
        let start = Swift.max(self.lowerBound, constraint.lowerBound)
        let end = Swift.min(self.upperBound, constraint.upperBound)
        if start < end {
            return start..<end
        } else {
            return nil
        }
    }
}


import XCTest
@testable import Ed25519

class Ed25519Tests: XCTestCase {
    func testSeed() throws {
        let seed = try Seed()
        XCTAssertNotEqual([UInt8](repeating: 0, count: 32), seed.buffer)
    }

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

Add sign/verify and key exchange tests

import XCTest
@testable import Ed25519

class Ed25519Tests: XCTestCase {
    func testSeed() throws {
        let seed = try Seed()
        XCTAssertEqual(32, seed.bytes.count)
        XCTAssertNotEqual([UInt8](repeating: 0, count: 32), seed.bytes)
    }

    func testSignAndVerify() throws {
        let seed = try Seed()
        let keyPair = KeyPair(seed: seed)
        let message = [UInt8]("Hello World!".utf8)
        let otherMessage = [UInt8]("Bonan tagon!".utf8)
        let signature = keyPair.sign(message)
        var tamperedSignature = signature

        tamperedSignature[3] = tamperedSignature[3] &+ 1
        XCTAssertTrue(try keyPair.verify(signature: signature, message: message))
        XCTAssertFalse(try keyPair.verify(signature: signature, message: otherMessage))
        XCTAssertFalse(try keyPair.verify(signature: tamperedSignature, message: message))
        XCTAssertFalse(try keyPair.verify(signature: signature, message: []))
        XCTAssertThrowsError(try keyPair.verify(signature: [1,2,3], message: message))
    }

    func testKeyExchange() throws {
        let keyPair = KeyPair(seed: try Seed())
        let otherKeyPair = KeyPair(seed: try Seed())

        XCTAssertNotEqual(keyPair.privateKey.bytes, otherKeyPair.privateKey.bytes)
        XCTAssertNotEqual(keyPair.publicKey.bytes, otherKeyPair.publicKey.bytes)

        let secret1 = try KeyPair.keyExchange(publicKey: keyPair.publicKey.bytes,
                                              privateKey: otherKeyPair.privateKey.bytes)
        let secret2 = try KeyPair.keyExchange(publicKey: otherKeyPair.publicKey.bytes,
                                              privateKey: keyPair.privateKey.bytes)
        XCTAssertEqual(secret1, secret2)
    }

    static var allTests = [
        ("testSeed", testSeed),
        ("testSignAndVerify", testSignAndVerify),
        ("testKeyExchange", testKeyExchange)
    ]
}


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

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

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

	func testEmptyTreesAreNotBranches() {
		XCTAssertFalse(BinaryTree<Int>().isBranch)
	}

	func testLeavesAreLeaves() {
		XCTAssert(leaf.isLeaf)
	}

	func testLeavesAreNonEmpty() {
		XCTAssertFalse(leaf.isEmpty)
	}

	func testLeavesAreNotBranches() {
		XCTAssertFalse(leaf.isBranch)
	}

	let branches: [BinaryTree<Int>] = [
		BinaryTree(BinaryTree(0), 0, nil),
		BinaryTree(nil, 0, BinaryTree(0)),
		BinaryTree(BinaryTree(0), 0, BinaryTree(0)),
	]

	func testBranchesAreBranches() {
		map(branches) { XCTAssert($0.isBranch) }
	}
}

// MARK: - Fixtures

private let leaf = BinaryTree(0)

import BinaryTree
import XCTest

Move the branches fixtures outside the class.

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

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

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

	func testEmptyTreesAreNotBranches() {
		XCTAssertFalse(BinaryTree<Int>().isBranch)
	}

	func testLeavesAreLeaves() {
		XCTAssert(leaf.isLeaf)
	}

	func testLeavesAreNonEmpty() {
		XCTAssertFalse(leaf.isEmpty)
	}

	func testLeavesAreNotBranches() {
		XCTAssertFalse(leaf.isBranch)
	}

	func testBranchesAreBranches() {
		map(branches) { XCTAssert($0.isBranch) }
	}
}

// MARK: - Fixtures

private let leaf = BinaryTree(0)

private let branches: [BinaryTree<Int>] = [
	BinaryTree(leaf, 0, nil),
	BinaryTree(nil, 0, leaf),
	BinaryTree(leaf, 0, leaf),
]

import BinaryTree
import XCTest


import UIKit

final class VHomeListCell:UICollectionViewCell
{
    override init(frame:CGRect)
    {
        super.init(frame:frame)
        clipsToBounds = true
        backgroundColor = UIColor.clear
    }

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

    override var isSelected:Bool
    {
        didSet
        {
            hover()
        }
    }

    override var isHighlighted:Bool
    {
        didSet
        {
            hover()
        }
    }

    //MARK: private

    private func hover()
    {
        if isSelected || isHighlighted
        {

        }
        else
        {
        }
    }

    //MARK: internal

    func config(model:MHomeSaveDataItem)
    {
        hover()
    }
}

Add image view to cell

import UIKit

final class VHomeListCell:UICollectionViewCell
{
    private weak var imageView:UIImageView!
    private weak var layoutImageWidth:NSLayoutConstraint!

    override init(frame:CGRect)
    {
        super.init(frame:frame)
        clipsToBounds = true
        backgroundColor = UIColor.clear

        let imageView:UIImageView = UIImageView()
        imageView.isUserInteractionEnabled = false
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.contentMode = UIViewContentMode.center
        self.imageView = imageView

        addSubview(imageView)

        NSLayoutConstraint.equalsVertical(
            view:imageView,
            toView:self)
        NSLayoutConstraint.leftToLeft(
            view:imageView,
            toView:self)
        layoutImageWidth = NSLayoutConstraint.width(
            view:imageView)
    }

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

    override func layoutSubviews()
    {
        let height:CGFloat = bounds.height
        layoutImageWidth.constant = height

        super.layoutSubviews()
    }

    override var isSelected:Bool
    {
        didSet
        {
            hover()
        }
    }

    override var isHighlighted:Bool
    {
        didSet
        {
            hover()
        }
    }

    //MARK: private

    private func hover()
    {
        if isSelected || isHighlighted
        {

        }
        else
        {
        }
    }

    //MARK: internal

    func config(model:MHomeSaveDataItem)
    {
        hover()
    }
}


// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts

protocol P {
  associatedtype A
  static func fn(args: A)
}

class R<T> : P where T : P, T.A == T.Type {
  // expected-note@-1 {{'T' declared as parameter to type 'R'}}
  typealias A = T.Type
  static func fn(args: T.Type) {}
}

R.fn(args: R.self)
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}}

Update diagnostic after CS change

// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts

protocol P {
  associatedtype A
  static func fn(args: A)
}

class R<T> : P where T : P, T.A == T.Type {
  typealias A = T.Type
  static func fn(args: T.Type) {}
}

R.fn(args: R.self)
// expected-error@-1 {{type of expression is ambiguous without more context}}


import Foundation
import LoggerAPI
@testable import LicensePlistCore

class TestUtil {
    static func setGitHubToken() {
        // Specify your `github_token.txt` location
        let url = URL(fileURLWithPath: "/Users/mono/Git/Private/LicensePlist/Tests/LicensePlistTests/Resources/github_token.txt")
        do {
            GitHubAuthorization.shared.token = try String(contentsOf: url,
                                                           encoding: String.Encoding.utf8)
        } catch {
            Log.warning("\(url) not found. You can execute without github_token, but API limit will exceed sometimes.")
        }
    }
}

Fix github_token.txt path for test

import Foundation
import LoggerAPI
@testable import LicensePlistCore

class TestUtil {
    static func setGitHubToken() {
        // Specify your `github_token.txt` location
        let url = URL(fileURLWithPath: "/Users/mono/Git/LicensePlist/Tests/LicensePlistTests/Resources/github_token.txt")
        do {
            GitHubAuthorization.shared.token = try String(contentsOf: url,
                                                           encoding: String.Encoding.utf8)
        } catch {
            Log.warning("\(url) not found. You can execute without github_token, but API limit will exceed sometimes.")
        }
    }
}


//
//  GradedSectionMessageView.swift
//  edX
//
//  Created by Akiva Leffert on 6/6/15.
//  Copyright (c) 2015 edX. All rights reserved.
//

import UIKit

class GradedSectionMessageView: UIView {
    let messageLabel = UILabel()

    init() {
        super.init(frame: CGRectZero)
        messageLabel.numberOfLines = 0
        messageLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
        addSubview(messageLabel)
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self).offset(textInset)
            make.trailing.equalTo(self).offset(-textInset)
            make.top.equalTo(self).offset(textInset)
            make.bottom.equalTo(self).offset(-textInset)
        }
        messageLabel.attributedText = textStyle.attributedStringWithText(Strings.gradedContentWarning)
    }

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

    private var textInset : CGFloat {
        return StandardHorizontalMargin
    }

    private var textStyle : OEXTextStyle {
        return OEXTextStyle(weight: .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark())
    }
}

Add separator for graded header

//
//  GradedSectionMessageView.swift
//  edX
//
//  Created by Akiva Leffert on 6/6/15.
//  Copyright (c) 2015 edX. All rights reserved.
//

import UIKit

class GradedSectionMessageView: UIView {
    let messageLabel = UILabel()
    let separator = UIView()

    init() {
        super.init(frame: CGRectZero)
        messageLabel.numberOfLines = 0
        messageLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
        addSubview(messageLabel)

        separator.backgroundColor = textStyle.color
        addSubview(separator)

        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self).offset(textInset)
            make.trailing.equalTo(self).offset(-textInset)
            make.top.equalTo(self).offset(textInset)
            make.bottom.equalTo(self).offset(-textInset)
        }
        messageLabel.attributedText = textStyle.attributedStringWithText(Strings.gradedContentWarning)

        separator.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(self)
            make.height.equalTo(OEXStyles.dividerSize())
        }
    }

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

    private var textInset : CGFloat {
        return StandardHorizontalMargin
    }

    private var textStyle : OEXTextStyle {
        return OEXTextStyle(weight: .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark())
    }
}


import XCTest

class ScreenshotGenerator: XCTestCase {

    var app: XCUIApplication!
    let automationController = AutomationController()

    override func setUp() {
        super.setUp()

        app = automationController.app
        setupSnapshot(app)

        enforceCorrectDeviceOrientation()

        app.launch()
    }

    private func enforceCorrectDeviceOrientation() {
        let isTablet = UIDevice.current.userInterfaceIdiom == .pad

        let device = XCUIDevice.shared
        if isTablet {
            device.orientation = .landscapeLeft
        } else {
            device.orientation = .portrait
        }
    }

    private func hideKeyboard() {
        let hideKeyboardButton = app.buttons["Hide keyboard"]
        if hideKeyboardButton.exists {
            hideKeyboardButton.tap()
        }
    }

    func testScreenshots() {
        automationController.transitionToContent()

        snapshot("01_News")

        automationController.tapTab(.schedule)
        app.tables.firstMatch.swipeDown()

        snapshot("02_Schedule")

        let searchField = app.searchFields["Search"]
        searchField.tap()
        searchField.typeText("comic")
        app.tables["Search results"].staticTexts["ECC Room 4"].tap()

        if app.tables.buttons["Add to Favourites"].exists {
            app.tables.buttons["Add to Favourites"].tap()
        }

        snapshot("03_EventDetail")

        hideKeyboard()
        automationController.tapTab(.dealers)

        snapshot("04_Dealers")

        app.tables.staticTexts["Eurofurence Shop"].tap()

        snapshot("05_DealerDetail")

        automationController.tapTab(.information)

        snapshot("06_Information")
    }

}

Fix test failure on iPad

import XCTest

class ScreenshotGenerator: XCTestCase {

    var app: XCUIApplication!
    let automationController = AutomationController()

    override func setUp() {
        super.setUp()

        app = automationController.app
        setupSnapshot(app)

        enforceCorrectDeviceOrientation()

        app.launch()
    }

    private func enforceCorrectDeviceOrientation() {
        let isTablet = UIDevice.current.userInterfaceIdiom == .pad

        let device = XCUIDevice.shared
        if isTablet {
            device.orientation = .landscapeLeft
        } else {
            device.orientation = .portrait
        }
    }

    func testScreenshots() {
        automationController.transitionToContent()

        snapshot("01_News")

        automationController.tapTab(.schedule)

        app.tables.firstMatch.swipeDown()

        snapshot("02_Schedule")

        app.tables.staticTexts["Artists' Lounge"].tap()

        snapshot("03_EventDetail")

        automationController.tapTab(.dealers)

        snapshot("04_Dealers")

        app.tables.staticTexts["Eurofurence Shop"].tap()

        snapshot("05_DealerDetail")

        automationController.tapTab(.information)

        snapshot("06_Information")
    }

}


//
//  Glob.swift
//  Swiftline
//
//  Created by Omar Abdelhafith on 30/11/2015.
//  Copyright © 2015 Omar Abdelhafith. All rights reserved.
//

import Foundation
import Darwin

class Glob {

  static func expand(pattern: String) -> [String] {
    var files = [String]()
    var gt: glob_t = glob_t()

    if (glob(pattern.cStringUsingEncoding(NSUTF8StringEncoding)!, 0, nil, &gt) == 0) {

      for (var i: Int32 = 0 ; i < gt.gl_matchc ; i++) {

        files.append(String(CString: gt.gl_pathv[Int(i)], encoding: NSUTF8StringEncoding)!)
      }

    }

    globfree(&gt);
    return files
  }

}

Refactor c-for to for range

//
//  Glob.swift
//  Swiftline
//
//  Created by Omar Abdelhafith on 30/11/2015.
//  Copyright © 2015 Omar Abdelhafith. All rights reserved.
//

import Foundation
import Darwin

class Glob {

  static func expand(pattern: String) -> [String] {
    var files = [String]()
    var gt: glob_t = glob_t()

    if (glob(pattern.cStringUsingEncoding(NSUTF8StringEncoding)!, 0, nil, &gt) == 0) {

      for i in (0..<gt.gl_matchc) {
        files.append(String(CString: gt.gl_pathv[Int(i)], encoding: NSUTF8StringEncoding)!)
      }

    }

    globfree(&gt);
    return files
  }

}


//
//  CircleBorderView.swift
//  SwiftlieriOS
//
//  Created by Andrew J Wagner on 4/30/17.
//  Copyright © 2017 Drewag. All rights reserved.
//

#if os(iOS)
import UIKit

open class CircleBorderView: UIView {
    @IBInspectable public var borderColor: UIColor = UIColor.black {
        didSet {
            self.setNeedsDisplay()
        }
    }

    var color: UIColor!

    override open func awakeFromNib() {
        super.awakeFromNib()

        self.color = self.backgroundColor ?? UIColor.clear
        self.backgroundColor = UIColor.clear
    }

    open override func draw(_ rect: CGRect) {
        let lineSize = 1 / UIScreen.main.scale
        guard let ctx = UIGraphicsGetCurrentContext() else {
            return
        }

        let radius = min(rect.width, rect.height) - lineSize
        let circleRect = CGRect(
            x: (rect.width - radius) / 2,
            y: (rect.height - radius) / 2,
            width: radius,
            height: radius
        )
        ctx.addEllipse(in: circleRect)
        ctx.setLineWidth(lineSize)
        ctx.setFillColor(self.color.cgColor)
        ctx.setStrokeColor(self.borderColor.cgColor)
        ctx.drawPath(using: .fillStroke)
    }
}
#endif

Allow circle border view to be used programatically

//
//  CircleBorderView.swift
//  SwiftlieriOS
//
//  Created by Andrew J Wagner on 4/30/17.
//  Copyright © 2017 Drewag. All rights reserved.
//

#if os(iOS)
import UIKit

open class CircleBorderView: UIView {
    @IBInspectable public var borderColor: UIColor = UIColor.black {
        didSet {
            self.setNeedsDisplay()
        }
    }

    var color: UIColor!

    open override func didMoveToSuperview() {
        guard self.color == nil else {
            return
        }

        self.color = self.backgroundColor ?? UIColor.clear
        self.backgroundColor = UIColor.clear
    }

    open override func draw(_ rect: CGRect) {
        let lineSize = 1 / UIScreen.main.scale
        guard let ctx = UIGraphicsGetCurrentContext() else {
            return
        }

        let radius = min(rect.width, rect.height) - lineSize
        let circleRect = CGRect(
            x: (rect.width - radius) / 2,
            y: (rect.height - radius) / 2,
            width: radius,
            height: radius
        )
        ctx.addEllipse(in: circleRect)
        ctx.setLineWidth(lineSize)
        ctx.setFillColor(self.color.cgColor)
        ctx.setStrokeColor(self.borderColor.cgColor)
        ctx.drawPath(using: .fillStroke)
    }
}
#endif


#!/usr/bin/env swift

import Foundation

let y:(Double) -> Double = {x in 1.0/(1.0+(x*x))}

func calcp(n: Int) -> Double { return ((1...n).map{Double($0)/Double(n)}.map(y).reduce(0,+))*(4.0/Double(n)) }

var num_steps: Int = 10000000

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

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

// Get time.
let start = Date()

var pi: Double = calcp(n:num_steps)

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

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

Fix the off by 0.5 problem.

#!/usr/bin/env swift

import Foundation

let y:(Double) -> Double = {x in 1.0/(1.0+(x*x))}

// We have to split this into two functions otherwise the Swift 3.x compiler
// complains:
//
// error: expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
//
// Looking at stackoverflow this is a... feature of the compiler:
//   http://stackoverflow.com/questions/29707622/bizarre-swift-compiler-error-expression-too-complex-on-a-string-concatenation
func gen(n: Int) -> [Double] { return (1...n).map{Double($0)-0.5} }
func calcp(n: Int) -> Double { return (gen(n:n).map{Double($0)/Double(n)}.map(y).reduce(0,+))*(4.0/Double(n)) }

var num_steps: Int = 10000000

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

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

// Get time.
let start = Date()

var pi: Double = calcp(n:num_steps)

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

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


//
//  TimeInterval+TimeUnits.swift
//
//  Created by Victor Hudson on 1/13/17.
//  Copyright © 2017 Victor Hudson. All rights reserved.
//

import Foundation

extension TimeInterval {
	/// Provides a representation of the TimeInterval in the form of hours, minutes, and seconds as integers.
	var timeUnits: (hours: Int, minutes: Int, seconds: Int) {
		let interval = Int(self)
		return (interval / 3600, (interval % 3600) / 60, (interval % 3600) % 60)
	}
}

Add More TimeInterval helper properties & methods.

//
//  TimeInterval+TimeUnits.swift
//
//  Created by Victor Hudson on 1/13/17.
//  Copyright © 2017 Victor Hudson. All rights reserved.
//

import Foundation

extension TimeInterval {
	/// Provides a representation of the TimeInterval in the form of hours, minutes, and seconds as integers.
	var timeUnits: (hours: Int, minutes: Int, seconds: Int) {
		let interval = Int(self)
		return (interval / 3600, (interval % 3600) / 60, (interval % 3600) % 60)
	}
}

extension TimeInterval {
	var second: TimeInterval {
		return self.seconds
	}

	var seconds: TimeInterval {
		return self
	}

	var minute: TimeInterval {
		return self.minutes
	}

	var minutes: TimeInterval {
		let secondsInAMinute = 60 as TimeInterval
		return self * secondsInAMinute
	}

	var day: TimeInterval {
		return self.days
	}

	var days: TimeInterval {
		let secondsInADay = 86_400 as TimeInterval
		return self * secondsInADay
	}

	var fromNow: Date {
		let timeInterval = self
		return Date().addingTimeInterval(timeInterval)
	}

	func from(_ date: Date) -> Date {
		let timeInterval = self
		return date.addingTimeInterval(timeInterval)
	}

	var ago: Date {
		let timeInterval = self
		return Date().addingTimeInterval(-timeInterval)
	}
}


//
//  BarMath.swift
//  Tabman
//
//  Created by Merrick Sapsford on 07/06/2018.
//  Copyright © 2018 UI At Six. All rights reserved.
//

import Foundation

class BarMath {

    static func localIndexRange(for position: CGFloat, minimum: Int, maximum: Int) -> Range<Int> {
        let lower = floor(position)
        let upper = ceil(position)
        let minimum = CGFloat(minimum)
        let maximum = CGFloat(maximum)

        return Int(max(minimum, min(maximum, lower))) ..< Int(min(maximum, max(minimum, upper)))
    }

    static func localProgress(for position: CGFloat) -> CGFloat {
        var integral: Float = 0.0
        return CGFloat(modff(Float(position), &integral))
    }
}

Fix issue with bar math range error

//
//  BarMath.swift
//  Tabman
//
//  Created by Merrick Sapsford on 07/06/2018.
//  Copyright © 2018 UI At Six. All rights reserved.
//

import Foundation

class BarMath {

    static func localIndexRange(for position: CGFloat, minimum: Int, maximum: Int) -> Range<Int> {
        guard maximum > minimum else {
            return 0 ..< 0
        }
        let lower = floor(position)
        let upper = ceil(position)
        let minimum = CGFloat(minimum)
        let maximum = CGFloat(maximum)

        return Int(max(minimum, min(maximum, lower))) ..< Int(min(maximum, max(minimum, upper)))
    }

    static func localProgress(for position: CGFloat) -> CGFloat {
        var integral: Float = 0.0
        return CGFloat(modff(Float(position), &integral))
    }
}