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

/**
 A type for representing input/output operations.
 */
public struct IO<T> {

    private let action: () -> T

    /// Initialize an IO object with a closure that performs a side-effect.
    public init(_ action: () -> T) {
        self.action = action
    }
}

/**
 Lift a value into an `IO` object.

 This function is the equivalent of `return` (also called `unit`) in
 the Monad typeclass and `pure` in the Applicative typeclass.

 It takes a value of any type `T` and returns an `IO<T>`.

 - parameter value: The value that is to be lifted.
 - returns: The value wrapped in an `IO<T>` object.
 */

public func io<T>(value: T) -> IO<T> {
    return IO { _ in value }
}

Add the Main struct and the public <= operator

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

// MARK: The IO struct
/**
 A type for representing input/output actions.
 */
public struct IO<T> {

    private let action: () -> T

    /// Initialize an IO object with a closure that performs a side-effect.
    public init(_ action: () -> T) {
        self.action = action
    }
}

// MARK: The Main struct
/**
 A dummy type used to define the top level of execution for an IO type.

 An `IO<Main>` object is executed using the `<=` prefix operator.
 */
public struct Main { }

prefix operator <= { }

/**
 Execute the action stored in an `IO<Main>` object.

 - parameter io: The `IO<Main>` object to execute.
 - returns: A dummy `Main` object.
 */
public prefix func <= (io: IO<Main>) -> Main {
    return io.action()
}

// MARK: IO Monad functions

/**
 Lift a value into an `IO` object.

 This function is the equivalent of `return` (also called `unit`) in
 the Monad typeclass and `pure` in the Applicative typeclass.

 It takes a value of any type `T` and returns an `IO<T>`.

 - parameter value: The value that is to be lifted.
 - returns: The value wrapped in an `IO<T>` object.
 */

public func io<T>(value: T) -> IO<T> {
    return IO { _ in value }
}


//
//  EveryoneGetsToDJTests.swift
//  EveryoneGetsToDJTests
//
//  Created by Patrick O'Leary on 6/7/17.
//  Copyright © 2017 Patrick O'Leary. All rights reserved.
//

import XCTest
@testable import EveryoneGetsToDJ

class EveryoneGetsToDJTests: 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.
        }
    }

}

Add test for jukebox observing

//
//  EveryoneGetsToDJTests.swift
//  EveryoneGetsToDJTests
//
//  Created by Patrick O'Leary on 6/7/17.
//  Copyright © 2017 Patrick O'Leary. All rights reserved.
//

import XCTest
@testable import EveryoneGetsToDJ
import PromiseKit

class EveryoneGetsToDJTests: 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 testObserveTracks() {
        let firExpectation = expectation(description: "expect return from observe function")
        let firManager = FirebaseManager.sharedInstance
        firManager.observe(jukebox: "-KnZjudS6PoKyQFaQU5M").then { jukebox -> String in
            XCTAssertTrue(jukebox.tracks.count == 1, "Should observe one track within test jukebox")
            firExpectation.fulfill()
            return "Done"
        }.catch { error in

        }
        waitForExpectations(timeout: 20) { (error) in
            if let error = error {
                print("Error: \(error.localizedDescription)")
            }
        }
    }

}


//
//  QuotesServer.swift
//  QuotesKit
//
//  Created by Julian Grosshauser on 09/06/15.
//  Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//

public struct QuotesServer {

    //MARK: Properties

    public let serverURL: NSURL
    public let quotesEndpoint = "quotes"

    //MARK: Initialization

    public init(serverURL: NSURL) {
        self.serverURL = serverURL
    }
}

Add `+` operator to concatenate URL components

//
//  QuotesServer.swift
//  QuotesKit
//
//  Created by Julian Grosshauser on 09/06/15.
//  Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//

public struct QuotesServer {

    //MARK: Properties

    public let serverURL: NSURL
    public let quotesEndpoint = "quotes"

    //MARK: Initialization

    public init(serverURL: NSURL) {
        self.serverURL = serverURL
    }
}

public func + (lhs: NSURL, rhs: String) -> NSURL {
    return lhs.URLByAppendingPathComponent(rhs)
}


//
//  LayoutManager.swift
//  LayoutManager
//
//  Created by Altimir Antonov on 6/2/16.
//  Copyright © 2016 Altimir Antonov. All rights reserved.
//

#if os(iOS)
    import UIKit
    typealias View = UIView
#else
    import Cocoa
    typealias View = NSView
#endif

extension View: Frameable {
    public var superFrame: CGRect {
        guard let superview = superview else {
            return CGRectZero
        }

        return superview.frame
    }

    public func setDimensionAutomatically() {
        #if os(iOS)
            self.sizeToFit()
        #else
            self.autoresizesSubviews = true
            self.autoresizingMask = [.ViewWidthSizable, .ViewHeightSizable]
        #endif
    }
}

extension CALayer {
    public var superFrame: CGRect {
        guard let superlayer = superlayer else {
            return CGRectZero
        }

        return superlayer.frame
    }

    public func setDimensionAutomatically() { /* no-op here as this shouldn't apply to CALayers */ }
}

Connect the protocols with the View and Layer extensions.

//
//  LayoutManager.swift
//  LayoutManager
//
//  Created by Altimir Antonov on 6/2/16.
//  Copyright © 2016 Altimir Antonov. All rights reserved.
//

#if os(iOS)
    import UIKit
    typealias View = UIView
#else
    import Cocoa
    typealias View = NSView
#endif

extension View: Frameable, Anchorable, Alignable, Groupable {
    public var superFrame: CGRect {
        guard let superview = superview else {
            return CGRectZero
        }

        return superview.frame
    }

    public func setDimensionAutomatically() {
        #if os(iOS)
            self.sizeToFit()
        #else
            self.autoresizesSubviews = true
            self.autoresizingMask = [.ViewWidthSizable, .ViewHeightSizable]
        #endif
    }
}

extension CALayer: Frameable, Anchorable, Alignable, Groupable {
    public var superFrame: CGRect {
        guard let superlayer = superlayer else {
            return CGRectZero
        }

        return superlayer.frame
    }

    public func setDimensionAutomatically() { /* no-op here as this shouldn't apply to CALayers */ }
}


import XCTest
@testable import GABoardGameGeek

final class GABoardGameGeekTests: XCTestCase {
    func testExample() throws {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct
        // results.
        XCTAssertEqual(GABoardGameGeek().text, "Hello, World!")
    }
}

Add a rudimentary "Unit Test" that actually tests end-to-end functionality

import XCTest
@testable import GABoardGameGeek

final class GABoardGameGeekTests: XCTestCase {
    func testGetGame() throws {
        let exp = expectation(description: "Check Getting a Game Succeeds")
        var testGame: BoardGame?

        GABoardGameGeek().getGameById(36218) { result in
            switch(result) {
            case .success(let game):
                testGame = game
                exp.fulfill()
            case .failure(let error):
                print(error)
            }
        }

        waitForExpectations(timeout: 10) { error in
            if let error = error {
                XCTFail("waitForExpectationsWithTimeout errored: \(error)")
            }
            XCTAssertNotNil(testGame)
            XCTAssertEqual(testGame?.name, "Dominion")
        }
    }
}


import Foundation

extension AsyncConstraintSet {

    class AsyncOperation<T>: Operation {

        enum State {
            case ready
            case executing
            case finished

            var keyPath: String {
                switch self {
                case .ready: return "isReady"
                case .executing: return "isExecuting"
                case .finished: return "isFinished"
                }
            }
        }

        private let constraint: AnyAsyncConstraint<T>
        private let input: T
        var result: Result?

        init(input:T, constraint: AnyAsyncConstraint<T>) {

            self.input = input
            self.constraint = constraint
            super.init()
        }

        var state: State = .ready {
            willSet {
                willChangeValue(forKey: newValue.keyPath)
            }
            didSet {
                didChangeValue(forKey: state.keyPath)
            }
        }

        override var isReady: Bool {
            return state == .ready
        }

        override var isExecuting: Bool {
            return state == .executing
        }

        override var isFinished: Bool {
            return state == .finished
        }

        override var isAsynchronous: Bool {
            return true
        }

        override func start() {

            if (isCancelled) {
                state = .finished
            }
            else {
                state = .executing
                execute()
            }
        }

        func execute() {

            constraint.evaluate(with: input, queue: .main) { result in
                self.handle(evaluationResult: result)
            }
        }

        func handle(evaluationResult: Result) {
            state = .finished
            result = evaluationResult
        }
    }
}

Mark the operation finished after getting the evaluation result

import Foundation

extension AsyncConstraintSet {

    class AsyncOperation<T>: Operation {

        enum State {
            case ready
            case executing
            case finished

            var keyPath: String {
                switch self {
                case .ready: return "isReady"
                case .executing: return "isExecuting"
                case .finished: return "isFinished"
                }
            }
        }

        private let constraint: AnyAsyncConstraint<T>
        private let input: T
        private var workQueue: DispatchQueue {
            return DispatchQueue(label: "com.nsagora.validation-toolkit.async-operation", attributes: .concurrent)
        }

        var result: Result?

        init(input:T, constraint: AnyAsyncConstraint<T>) {

            self.input = input
            self.constraint = constraint

            super.init()
            self.qualityOfService = .userInitiated
        }

        var state: State = .ready {
            willSet {
                willChangeValue(forKey: newValue.keyPath)
            }
            didSet {
                didChangeValue(forKey: state.keyPath)
            }
        }

        override var isReady: Bool {
            return state == .ready
        }

        override var isExecuting: Bool {
            return state == .executing
        }

        override var isFinished: Bool {
            return state == .finished
        }

        override var isAsynchronous: Bool {
            return true
        }

        override func start() {
            super.start()

            if (isCancelled) {
                return finish()
            }

            state = .executing
            execute()
        }

        func execute() {

            constraint.evaluate(with: input, queue: workQueue) { result in
                self.result = result
                self.finish()
            }
        }

        internal func finish() {
            state = .finished
        }
    }
}


import XCTest
@testable import worldcities

class TestModelListSearch:XCTestCase
{
    private let kWaitExpectation:TimeInterval = 90

    func testSearchItems()
    {
        let itemsExpectation:XCTestExpectation = expectation(
            description:"items loaded")

        let modelList:ModelList = ModelList()
        modelList.loadItems
        {
            itemsExpectation.fulfill()
        }

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

Add test searching with empty string

import XCTest
@testable import worldcities

class TestModelListSearch:XCTestCase
{
    private let kStringEmpty:String = ""
    private let kWaitExpectation:TimeInterval = 90

    func testSearchItems()
    {
        let itemsExpectation:XCTestExpectation = expectation(
            description:"items loaded")

        let modelList:ModelList = ModelList()
        modelList.loadItems
        {
            itemsExpectation.fulfill()
        }

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

            self?.inputEmpty(modelList:modelList)
        }
    }

    //MARK: private

    private func inputEmpty(modelList:ModelList)
    {
        let foundItems:[ModelListItem] = modelList.searchItems(
            forInput:kStringEmpty)
        let foundCount:Int = foundItems.count
        let totalCount:Int = modelList.items.count

        XCTAssertEqual(
            foundCount,
            totalCount,
            "failed searching with empty string")
    }
}


import XCTest
import ToDoRedux

class ToDoTests: ToDoReduxTests {
    private var todo: ToDo!

    override func setUp() {
        super.setUp()

        store.dispatch(ToDoActions.add(title: "Buy milk", notes: "", tags: []))
        todo = store.state.todos.first!
    }

    func testAddedToDo() {
        XCTAssertEqual(store.state.todos.count, 1)

        let todo = store.state.todos.first!

        XCTAssertEqual(todo.title, "Buy milk")
        XCTAssertFalse(todo.done)
    }

    func testRemoveToDo() {
        store.dispatch(ToDoActions.remove(todo: todo))

        XCTAssertTrue(store.state.todos.isEmpty)
    }

    func testDoneToDo() {
        store.dispatch(ToDoActions.done(todo: self.todo))

        let todo = store.state.todos.first!

        XCTAssertTrue(todo.done)
    }
}

Add a ToDo to cover code path when ToDo does not match the one toggling

import XCTest
import ToDoRedux

class ToDoTests: ToDoReduxTests {
    private var todo: ToDo!

    override func setUp() {
        super.setUp()

        store.dispatch(ToDoActions.add(title: "Buy milk", notes: "", tags: []))
        todo = store.state.todos.first!
    }

    func testAddedToDo() {
        XCTAssertEqual(store.state.todos.count, 1)

        let todo = store.state.todos.first!

        XCTAssertEqual(todo.title, "Buy milk")
        XCTAssertFalse(todo.done)
    }

    func testRemoveToDo() {
        store.dispatch(ToDoActions.remove(todo: todo))

        XCTAssertTrue(store.state.todos.isEmpty)
    }

    func testDoneToDo() {
        store.dispatch(ToDoActions.add(title: "Buy CDs", notes: "", tags: []))
        store.dispatch(ToDoActions.done(todo: self.todo))

        let todo = store.state.todos.first!

        XCTAssertTrue(todo.done)
    }
}


public protocol Stream {
    func read(maxBytes: Int) throws -> [UInt8]
    func write(bytes: [UInt8]) throws -> Int
    func close() throws
}

public extension Stream {
    func readInt8() throws -> Int8 {
        return Int8(try read(1)[0])
    }

    func write(int8: Int8) throws {
        try write([UInt8(int8)])
    }

    func readUInt8() throws -> UInt8 {
        return try read(1)[0]
    }

    func write(uint8: UInt8) throws {
        try write([uint8])
    }
}

func >> (left: Stream, inout right: UInt8) throws {
    right = try left.readUInt8()
}

func >> (left: Stream, inout right: Int8) throws {
    right = try left.readInt8()
}

func << (left: Stream, right: UInt8) throws {
    try left.write(right)
}

func << (left: Stream, right: Int8) throws {
    try left.write(right)
}

Add public modifier to operator functions

public protocol Stream {
    func read(maxBytes: Int) throws -> [UInt8]
    func write(bytes: [UInt8]) throws -> Int
    func close() throws
}

public extension Stream {
    func readInt8() throws -> Int8 {
        return Int8(try read(1)[0])
    }

    func write(int8: Int8) throws {
        try write([UInt8(int8)])
    }

    func readUInt8() throws -> UInt8 {
        return try read(1)[0]
    }

    func write(uint8: UInt8) throws {
        try write([uint8])
    }
}

public func >> (left: Stream, inout right: UInt8) throws {
    right = try left.readUInt8()
}

public func >> (left: Stream, inout right: Int8) throws {
    right = try left.readInt8()
}

public func << (left: Stream, right: UInt8) throws {
    try left.write(right)
}

public func << (left: Stream, right: Int8) throws {
    try left.write(right)
}


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

// REQUIRES: asserts
// RUN: not --crash %target-swift-frontend %s -emit-ir
{func c(UInt=1 + 1 as?Int){b

Add REQUIRES: deterministic-behavior to a new crasher that does not always crash.

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

// REQUIRES: deterministic-behavior

// REQUIRES: asserts
// RUN: not --crash %target-swift-frontend %s -emit-ir
{func c(UInt=1 + 1 as?Int){b


//
//  RemoteFileTableCell.swift
//  Skugga
//
//  Created by Arnaud Barisain-Monrose on 10/02/2015.
//
//

import Foundation
import Cocoa

class RemoteFileTableCell: NSTableCellView
{
    @IBOutlet weak var filename: NSTextField!

    @IBOutlet weak var uploadDate: NSTextField!

    @IBOutlet weak var icon: NSImageView!

    func updateWithRemoteFile(file: RemoteFile)
    {
        var fileIcon = NSWorkspace.sharedWorkspace().iconForFileType("html");
        fileIcon.size = NSSize(width: 40, height: 40);
        icon.image = fileIcon;
        filename.stringValue = file.filename;
        uploadDate.stringValue = file.uploadDate.description;
    }
}

Add right icons for files

//
//  RemoteFileTableCell.swift
//  Skugga
//
//  Created by Arnaud Barisain-Monrose on 10/02/2015.
//
//

import Foundation
import Cocoa

private struct LocalConsts
{
    static let defaultFileType = "html";
}

class RemoteFileTableCell: NSTableCellView
{
    @IBOutlet weak var filename: NSTextField!

    @IBOutlet weak var uploadDate: NSTextField!

    @IBOutlet weak var icon: NSImageView!

    func updateWithRemoteFile(file: RemoteFile)
    {
        var fileType = file.filename.pathExtension;
        if (fileType.isEmpty)
        {
            fileType = LocalConsts.defaultFileType;
        }
        var fileIcon = NSWorkspace.sharedWorkspace().iconForFileType(fileType);
        fileIcon.size = NSSize(width: 40, height: 40);
        icon.image = fileIcon;
        filename.stringValue = file.filename;
        uploadDate.stringValue = file.uploadDate.description;
    }
}


//
//  FuelGaugeView.swift
//  FuelGaugeKit
//
//  Created by Ron Lisle on 3/19/15.
//  Copyright (c) 2015 Ron Lisle. All rights reserved.
//

import UIKit

class FuelGaugeView: UIView {

    var backgroundImage:UIImageView!

    override func layoutSubviews() {
        super.layoutSubviews()

        if backgroundImage == nil {
            backgroundImage = UIImageView()
            addSubview(backgroundImage)
        }
    }
}

Set frame to bounds to pass test. 4 tests, all passing.

//
//  FuelGaugeView.swift
//  FuelGaugeKit
//
//  Created by Ron Lisle on 3/19/15.
//  Copyright (c) 2015 Ron Lisle. All rights reserved.
//

import UIKit

class FuelGaugeView: UIView {

    var backgroundImage:UIImageView!

    override func layoutSubviews() {
        super.layoutSubviews()

        if backgroundImage == nil {
            backgroundImage = UIImageView()
            backgroundImage.frame = self.bounds
            addSubview(backgroundImage)
        }
    }
}


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

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

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

	func testChecksLambdasAgainstDependentFunctionTypes() {
		let type = .Type => { A in A --> A }
		let term = .Type => { A in A => { a in a } }
		let elaborated = assertNoThrow(try term.elaborateType(type, [:], [:]))
		assert(elaborated?.annotation, ==, type)
	}
}

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

import Assertions
import Manifold
import XCTest

Change the function type elaboration test to simply test the elaborated types for equality.

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

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

	func testChecksLambdasAgainstFunctionTypes() {
		let type = .Type --> .Type
		let term = .Type => { $0 }
		let elaborated = try? term.elaborateType(type, [:], [:])
		assert(elaborated?.annotation, ==, type)
	}

	func testChecksLambdasAgainstDependentFunctionTypes() {
		let type = .Type => { A in A --> A }
		let term = .Type => { A in A => { a in a } }
		let elaborated = assertNoThrow(try term.elaborateType(type, [:], [:]))
		assert(elaborated?.annotation, ==, type)
	}
}

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

import Assertions
import Manifold
import XCTest


//
//  DetailViewController.swift
//  SplitView
//
//  Created by Ben Chatelain on 8/25/15.
//  Copyright © 2015 phatblat. All rights reserved.
//

import UIKit

class DetailViewController: UIViewController {

    // MARK: - UIViewController

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

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

        navigationItem.rightBarButtonItem = splitViewController?.displayModeButtonItem()
    }

}

Configure displayModeButton to always be visible

//
//  DetailViewController.swift
//  SplitView
//
//  Created by Ben Chatelain on 8/25/15.
//  Copyright © 2015 phatblat. All rights reserved.
//

import UIKit

class DetailViewController: UIViewController {

    // MARK: - UIViewController

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

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

        navigationItem.leftItemsSupplementBackButton = true

        let displayModeButton = UIBarButtonItem(title: "Menu", style: .Plain,
            target: splitViewController!.displayModeButtonItem().target,
            action: splitViewController!.displayModeButtonItem().action)

        navigationItem.leftBarButtonItem = displayModeButton
        navigationItem.rightBarButtonItem = displayModeButton
    }

}


//
//  Observable+MapTo.swift
//  Meow
//
//  Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//

import RxSwift
import SwiftyJSON

enum MeowError: String {
    case badCast, badData
}

extension MeowError: Swift.Error { }

extension Observable {
    func mapTo <T: JSONConvertible>(type: T.Type) -> Observable<T> {
        return map {
            (element) -> T in

            guard let json = element as? JSON else {
                throw MeowError.badData
            }
            guard let model = T.fromJSON(json) else {
                throw MeowError.badCast
            }
            return model
        }
    }

    func mapTo<T: JSONConvertible>(arrayOf type: T.Type) -> Observable<[T]> {
        return self.map {
            (element) -> [T] in
            guard let array = element as? [AnyObject], let jsonArray = array as? [JSON] else {
                throw MeowError.badData
            }

            do {
                let models = try jsonArray.map {
                    (jsonElement) -> T in
                    guard let model = T.fromJSON(jsonElement) else {
                        throw MeowError.badCast
                    }
                    return model
                }

                return models
            }
        }
    }

}

Use flatMap for better nil filtering

//
//  Observable+MapTo.swift
//  Meow
//
//  Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//

import RxSwift
import SwiftyJSON

enum MeowError: String {
    case badCast, badData
}

extension MeowError: Swift.Error { }

extension Observable {
    func mapTo <T: JSONConvertible>(type: T.Type) -> Observable<T> {
        return map {
            (element) -> T in

            guard let json = element as? JSON else {
                throw MeowError.badData
            }
            guard let model = T.fromJSON(json) else {
                throw MeowError.badCast
            }
            return model
        }
    }

    func mapTo<T: JSONConvertible>(arrayOf type: T.Type) -> Observable<[T]> {
        return self.map {
            (element) -> [T] in
            guard let array = element as? [AnyObject], let jsonArray = array as? [JSON] else {
                throw MeowError.badData
            }

            return jsonArray.flatMap {
                (jsonElement) -> T? in
                T.fromJSON(jsonElement)
            }
        }
    }

}


//  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(BinaryTree(0).isLeaf)
	}

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

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

	func testLeftBranchesAreBranches() {
		XCTAssert(BinaryTree(BinaryTree(0), 0, nil).isBranch)
	}
}

import BinaryTree
import XCTest

Test that right branches are branches.

//  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(BinaryTree(0).isLeaf)
	}

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

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

	func testLeftBranchesAreBranches() {
		XCTAssert(BinaryTree(BinaryTree(0), 0, nil).isBranch)
	}

	func testRightBranchesAreBranches() {
		XCTAssert(BinaryTree(nil, 0, BinaryTree(0)).isBranch)
	}
}

import BinaryTree
import XCTest


//
//  main.swift
//  threadword
//
//  Created by Joshua Oldenburg on 6/18/14.
//  Copyright (c) 2014 Joshua Oldenburg. All rights reserved.
//

import Foundation

let puzzle = JOThreadWordsPuzzle(level: [
/*	"malgmrt",
	"corveos",
	"sunnisn",
	"trtdrng",
	"fausged",*/
	"toeing",
	"ritlws",
	"vabted",
	"sooiae",
	"hcrubs",
])

println(puzzle.solve().description)

Add another puzzle. CLI is next.

//
//  main.swift
//  threadword
//
//  Created by Joshua Oldenburg on 6/18/14.
//  Copyright (c) 2014 Joshua Oldenburg. All rights reserved.
//

import Foundation

/*let parser = GBCommandLineParser()
parser.registerOption("prefix", shortcut: 112 /* p */, requirement: GBValueRequired)
parser.registerOption("file", shortcut: 102 /* f */, requirement: GBValueRequired)

parser.parseOptionsUsingDefaultArgumentsWithBlock({ // (flags: GBParseFlags, argument: String, value: AnyObject, stop)
	return
}()) */

let puzzle = JOThreadWordsPuzzle(level: [
/*	"malgmrt",
	"corveos",
	"sunnisn",
	"trtdrng",
	"fausged",*/
/*	"toeing",
	"ritlws",
	"vabted",
	"sooiae",
	"hcrubs",*/
	"pepries",
	"dorohod",
	"tancsnt",
	"supaees",
	"ctrryrd",
])

let solution = puzzle.solve()
println(solution.description)
println(solution.count)


//
//  DVTSourceTextView.swift
//  XJump
//
//  Created by Victor Shamanov on 5/28/15.
//  Copyright (c) 2015 Victor Shamanov. All rights reserved.
//

import Foundation

extension DVTSourceTextView {

    var visibleTextRange: NSRange {

        if let clipView = superview as? NSClipView,
           let layoutManager = layoutManager,
           let textContainer = textContainer {

            let glyphRange = layoutManager.glyphRangeForBoundingRect(clipView.documentVisibleRect,
                                                                     inTextContainer: textContainer)

            return layoutManager.characterRangeForGlyphRange(glyphRange, actualGlyphRange: nil)

        } else {
            fatalError("Unhandled error")
        }
    }

    func rectsOfChar(char: Character) -> [NSRect] {
        return textStorage?.string.allRangesOfCharacters(char).map(rectFromRange) ?? []
    }

    private func rectFromRange(range: NSRange) -> NSRect {
        fatalError("Not implemented yet")
    }

}

Implement rectFromRange & rangeOfVisible methods

//
//  DVTSourceTextView.swift
//  XJump
//
//  Created by Victor Shamanov on 5/28/15.
//  Copyright (c) 2015 Victor Shamanov. All rights reserved.
//

import Foundation

extension DVTSourceTextView {

    var visibleTextRange: NSRange {

        if let clipView = superview as? NSClipView,
           let layoutManager = layoutManager,
           let textContainer = textContainer {

            let glyphRange = layoutManager.glyphRangeForBoundingRect(clipView.documentVisibleRect,
                                                                     inTextContainer: textContainer)

            return layoutManager.characterRangeForGlyphRange(glyphRange, actualGlyphRange: nil)

        } else {
            fatalError("Unhandled error")
        }
    }

    var sourceCode: String {
        return (textStorage() as! NSTextStorage).string
    }

    func rangesOfVisible(char: Character) -> [NSRange] {
        return sourceCode.allRangesOfCharacters(char, inRange: visibleTextRange)
    }

    func rectFromRange(range: NSRange) -> NSRect {
        let rect = firstRectForCharacterRange(range, actualRange: nil)
        let rectInWindow = window!.convertRectFromScreen(rect)
        var rectInView = self.convertRect(rectInWindow, fromView: nil)

        let expandSize: CGFloat = 2

        rectInView.size.width += expandSize
        rectInView.origin.x -= expandSize / 2

        return rectInView
    }

}


//
//  CliqNameCollectionViewController.swift
//  Cliq
//
//  Created by Anar Enhsaihan on 7/7/15.
//  Copyright (c) 2015 Arun Nagarajan. All rights reserved.
//

import UIKit

class CliqNameCollectionViewController: UIViewController {

    @IBOutlet weak var coverPhotoImageView: UIImageView!
    var imageForCoverPhoto : UIImage!

    override func viewDidLoad() {

        coverPhotoImageView.image = imageForCoverPhoto
    }
}

Configure create right bar button item

//
//  CliqNameCollectionViewController.swift
//  Cliq
//
//  Created by Anar Enhsaihan on 7/7/15.
//  Copyright (c) 2015 Arun Nagarajan. All rights reserved.
//

import UIKit

class CliqNameCollectionViewController: UIViewController {

    @IBOutlet weak var coverPhotoImageView: UIImageView!
    var imageForCoverPhoto : UIImage!

    override func viewDidLoad() {

        coverPhotoImageView.image = imageForCoverPhoto

        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "CREATE", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
    }
}


//
//  ContestFormatter.swift
//  JumuNordost
//
//  Created by Martin Richter on 24/02/16.
//  Copyright © 2016 Martin Richter. All rights reserved.
//

import Foundation

struct FormattedContest {
    let name: String
    let dates: String
}

class ContestFormatter {

    private static let dateFormatter: NSDateFormatter = {
        let formatter = NSDateFormatter()
        formatter.dateStyle = .LongStyle
        formatter.timeStyle = .NoStyle
        formatter.locale = NSLocale.autoupdatingCurrentLocale()
        return formatter
    }()

    // MARK: - Formatting

    static func formattedContest(contest: Contest) -> FormattedContest {

        dateFormatter.timeZone = contest.timeZone // TODO: Eliminate this state

        let (startDate, endDate) = (contest.startDate, contest.endDate)

        let dates: String = {
            if startDate == endDate {
                return dateFormatter.stringFromDate(startDate)
            } else {
                return [startDate, endDate].map(dateFormatter.stringFromDate).joinWithSeparator(" – ")
            }
        }()

        return FormattedContest(
            name: contest.name,
            dates: dates
        )
    }
}

Use awesome NSDateIntervalFormatter to format contest dates in list

//
//  ContestFormatter.swift
//  JumuNordost
//
//  Created by Martin Richter on 24/02/16.
//  Copyright © 2016 Martin Richter. All rights reserved.
//

import Foundation

struct FormattedContest {
    let name: String
    let dates: String
}

class ContestFormatter {

    private static let dateIntervalFormatter: NSDateIntervalFormatter = {
        let formatter = NSDateIntervalFormatter()
        formatter.dateStyle = .LongStyle
        formatter.timeStyle = .NoStyle
        formatter.locale = NSLocale.autoupdatingCurrentLocale()
        return formatter
    }()

    // MARK: - Formatting

    static func formattedContest(contest: Contest) -> FormattedContest {

        dateIntervalFormatter.timeZone = contest.timeZone // TODO: Eliminate this state

        return FormattedContest(
            name: contest.name,
            dates: dateIntervalFormatter.stringFromDate(contest.startDate, toDate: contest.endDate)
        )
    }
}


enum MVitaPtpEvent:UInt16
{
    case unknown
    case sendItemsCount                 = 49412
    case requestItemStatus              = 49423
    case requestSettings                = 49426
    case sendStorageSize                = 49433
    case requestItemTreat               = 49442
    case terminate                      = 49446
    case itemPropertyChanged            = 51201
}

Add send items meta data

enum MVitaPtpEvent:UInt16
{
    case unknown
    case sendItemsCount                 = 49412
    case sendItemsMetaData              = 49413
    case requestItemStatus              = 49423
    case requestSettings                = 49426
    case sendStorageSize                = 49433
    case requestItemTreat               = 49442
    case terminate                      = 49446
    case itemPropertyChanged            = 51201
}


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

import Prelude
import Tesseract
import XCTest

final class EnvironmentTests: XCTestCase {
	func testNodeReferencingConstantEvaluatesToConstant() {
		let a = Identifier()
		let graph = Graph(nodes: [ a: Node.Abstraction(Prelude["unit"]!.0) ])
		let evaluated = evaluate(graph, a)

		assertEqual(assertNotNil(assertRight(evaluated)?.constant()), ())
	}
}

Test against a slightly more interesting constant.

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

import Prelude
import Tesseract
import XCTest

final class EnvironmentTests: XCTestCase {
	func testNodeReferencingConstantEvaluatesToConstant() {
		let a = Identifier()
		let graph = Graph(nodes: [ a: Node.Abstraction(Prelude["true"]!.0) ])
		let evaluated = evaluate(graph, a)

		assertEqual(assertNotNil(assertRight(evaluated)?.constant()), true)
	}
}


precedencegroup MonadicPrecedenceRight {
    associativity: right
    lowerThan: LogicalDisjunctionPrecedence
    higherThan: AssignmentPrecedence
}

precedencegroup MonadicPrecedenceLeft {
    associativity: left
    lowerThan: LogicalDisjunctionPrecedence
    higherThan: AssignmentPrecedence
}

precedencegroup ApplicativePrecedence {
    associativity: left
    higherThan: LogicalConjunctionPrecedence
    lowerThan: NilCoalescingPrecedence
}

infix operator >>- : MonadicPrecedenceLeft
infix operator -<< : MonadicPrecedenceRight

infix operator <^> : ApplicativePrecedence
infix operator <*> : ApplicativePrecedence

infix operator >>-? : MonadicPrecedenceLeft
infix operator -<<? : MonadicPrecedenceRight

Add the `PromiseK` prefix to precedencegroup

precedencegroup PromiseKMonadicPrecedenceRight {
    associativity: right
    lowerThan: LogicalDisjunctionPrecedence
    higherThan: AssignmentPrecedence
}

precedencegroup PromiseKMonadicPrecedenceLeft {
    associativity: left
    lowerThan: LogicalDisjunctionPrecedence
    higherThan: AssignmentPrecedence
}

precedencegroup PromiseKApplicativePrecedence {
    associativity: left
    higherThan: LogicalConjunctionPrecedence
    lowerThan: NilCoalescingPrecedence
}

infix operator >>- : PromiseKMonadicPrecedenceLeft
infix operator -<< : PromiseKMonadicPrecedenceRight

infix operator <^> : PromiseKApplicativePrecedence
infix operator <*> : PromiseKApplicativePrecedence

infix operator >>-? : PromiseKMonadicPrecedenceLeft
infix operator -<<? : PromiseKMonadicPrecedenceRight


//
//  AppDelegate.swift
//  SubwayApp
//
//  Created by Owen Yamauchi on 2/12/18.
//  Copyright © 2018 Owen Yamauchi. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

  @IBOutlet weak var window: NSWindow!
  @IBOutlet weak var subway: SubwayMonView!
  @IBOutlet weak var menu: NSPopUpButton!

  let defaultsKey = "SelectedStation"

  @IBAction func menuSelected(sender: NSPopUpButton) {
    subway.selectedStationTag = menu.selectedTag()
    subway.needsDisplay = true

    UserDefaults.standard.set(menu.selectedTag(), forKey: defaultsKey)
  }

  func applicationDidFinishLaunching(_ aNotification: Notification) {
    let selectedTag = UserDefaults.standard.integer(forKey: defaultsKey)

    subway.initialize(selectedTag == 0 ? 631 : selectedTag)
    subway.populateMenu(menu)
  }

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

Update view in SubwayApp on a timer

//
//  AppDelegate.swift
//  SubwayApp
//
//  Created by Owen Yamauchi on 2/12/18.
//  Copyright © 2018 Owen Yamauchi. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

  @IBOutlet weak var window: NSWindow!
  @IBOutlet weak var subway: SubwayMonView!
  @IBOutlet weak var menu: NSPopUpButton!

  let defaultsKey = "SelectedStation"

  @IBAction func menuSelected(sender: NSPopUpButton) {
    subway.selectedStationTag = menu.selectedTag()
    subway.needsDisplay = true

    UserDefaults.standard.set(menu.selectedTag(), forKey: defaultsKey)
  }

  func timerFired() {
    subway.needsDisplay = true
  }

  func applicationDidFinishLaunching(_ aNotification: Notification) {
    let selectedTag = UserDefaults.standard.integer(forKey: defaultsKey)

    subway.initialize(selectedTag == 0 ? 631 : selectedTag)
    subway.populateMenu(menu)

    Timer.scheduledTimer(
      timeInterval: 5.0,
      target: self,
      selector: #selector(AppDelegate.timerFired),
      userInfo: nil,
      repeats: true
    )
  }

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


//
//  Invoice.swift
//  iTax
//
//  Created by Kamil Kowalski on 14.06.2016.
//  Copyright © 2016 Kamil Kowalski. All rights reserved.
//

import Foundation
import RealmSwift

class Invoice: Object {
  dynamic var number = ""
  dynamic var issueDate: NSDate?
  dynamic var paymentDeadline: NSDate?
  dynamic var paid = false
  dynamic var typeRaw = InvoiceType.CostInvoice.rawValue
  dynamic var customerFullName = ""
  dynamic var customerShortName = ""
  dynamic var customerAddressStreet = ""
  dynamic var customerAddressCity = ""
  dynamic var customerAddressPostalCode = ""

  let items = List<InvoiceItem>()

  var type: InvoiceType {
    get {
      return InvoiceType(rawValue: typeRaw)!
    }

    set {
      typeRaw = newValue.rawValue
    }
  }

  var netPrice: Double {
    get {
      return items.map { $0.netPrice }.reduce(0, combine: +)
    }
  }

  var grossPrice: Double {
    get {
      return items.map { $0.netPrice }.reduce(0, combine: +)
    }
  }
}

Fix gross invoice price calculation

//
//  Invoice.swift
//  iTax
//
//  Created by Kamil Kowalski on 14.06.2016.
//  Copyright © 2016 Kamil Kowalski. All rights reserved.
//

import Foundation
import RealmSwift

class Invoice: Object {
  dynamic var number = ""
  dynamic var issueDate: NSDate?
  dynamic var paymentDeadline: NSDate?
  dynamic var paid = false
  dynamic var typeRaw = InvoiceType.CostInvoice.rawValue
  dynamic var customerFullName = ""
  dynamic var customerShortName = ""
  dynamic var customerAddressStreet = ""
  dynamic var customerAddressCity = ""
  dynamic var customerAddressPostalCode = ""

  let items = List<InvoiceItem>()

  var type: InvoiceType {
    get {
      return InvoiceType(rawValue: typeRaw)!
    }

    set {
      typeRaw = newValue.rawValue
    }
  }

  var netPrice: Double {
    get {
      return items.map { $0.netPrice }.reduce(0, combine: +)
    }
  }

  var grossPrice: Double {
    get {
      return items.map { $0.grossPrice }.reduce(0, combine: +)
    }
  }
}


//
//  CollectionViewCell.swift
//  SwiftDemo
//
//  Created by James Tang on 16/7/15.
//  Copyright © 2015 James Tang. All rights reserved.
//

import UIKit

class CollectionViewCell: UICollectionViewCell {

    var text : String? {
        didSet {
            self.reloadData()
        }
    }

    private var textLabel : UILabel?

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

        self.backgroundColor = UIColor.whiteColor()

        let bounds = CGRectMake(0, 0, CGRectGetMaxX(frame), CGRectGetMaxY(frame))
        let label = UILabel(frame: bounds)
        label.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
        self.textLabel = label
        self.addSubview(label)
    }

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

    func reloadData() {
        self.textLabel?.text = self.text
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.textLabel?.frame = self.bounds
    }
}

Update syntax for CGFrame, UIColor and AutoresizingMask

//
//  CollectionViewCell.swift
//  SwiftDemo
//
//  Created by James Tang on 16/7/15.
//  Copyright © 2015 James Tang. All rights reserved.
//

import UIKit

class CollectionViewCell: UICollectionViewCell {

    var text : String? {
        didSet {
            self.reloadData()
        }
    }

    private var textLabel : UILabel?

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

        self.backgroundColor = UIColor.white

        let bounds = CGRect(x: 0, y: 0, width: frame.maxX, height: frame.maxY)
        let label = UILabel(frame: bounds)
        label.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight, UIView.AutoresizingMask.flexibleWidth]
        self.textLabel = label
        self.addSubview(label)
    }

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

    func reloadData() {
        self.textLabel?.text = self.text
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.textLabel?.frame = self.bounds
    }
}


//
//  OutputByteStream.swift
//  SwiftCLI
//
//  Created by Jake Heiser on 9/11/17.
//

import Foundation

public protocol OutputByteStream {
    func output(_ content: String)
}

public class StdoutStream: OutputByteStream {
    public init() {}
    public func output(_ content: String) {
        print(content)
    }
}

public class StderrStream: OutputByteStream {
    public init() {}
    public func output(_ content: String) {
        printError(content)
    }
}

public class NullStream: OutputByteStream {
    public init() {}
    public func output(_ content: String) {}
}

public class FileStream: OutputByteStream {
    let handle: FileHandle
    public init?(path: String) {
        guard let handle = FileHandle(forWritingAtPath: path) else {
            return nil
        }
        handle.seekToEndOfFile()
        self.handle = handle
    }
    public func output(_ content: String) {
        guard let data = (content + "\n").data(using: .utf8) else {
            fatalError("Couldn't output content: \(content)")
        }
        handle.write(data)
    }
    deinit {
        handle.closeFile()
    }
}

public class CaptureStream: OutputByteStream {
    private(set) var content: String = ""
    public init() {}
    public func output(_ content: String) {
        self.content += content + "\n"
    }
}

public func <<(stream: OutputByteStream, text: String) {
    stream.output(text)
}

Make the content of a captured stream public

//
//  OutputByteStream.swift
//  SwiftCLI
//
//  Created by Jake Heiser on 9/11/17.
//

import Foundation

public protocol OutputByteStream {
    func output(_ content: String)
}

public class StdoutStream: OutputByteStream {
    public init() {}
    public func output(_ content: String) {
        print(content)
    }
}

public class StderrStream: OutputByteStream {
    public init() {}
    public func output(_ content: String) {
        printError(content)
    }
}

public class NullStream: OutputByteStream {
    public init() {}
    public func output(_ content: String) {}
}

public class FileStream: OutputByteStream {
    let handle: FileHandle
    public init?(path: String) {
        guard let handle = FileHandle(forWritingAtPath: path) else {
            return nil
        }
        handle.seekToEndOfFile()
        self.handle = handle
    }
    public func output(_ content: String) {
        guard let data = (content + "\n").data(using: .utf8) else {
            fatalError("Couldn't output content: \(content)")
        }
        handle.write(data)
    }
    deinit {
        handle.closeFile()
    }
}

public class CaptureStream: OutputByteStream {
    public private(set) var content: String = ""
    public init() {}
    public func output(_ content: String) {
        self.content += content + "\n"
    }
}

public func <<(stream: OutputByteStream, text: String) {
    stream.output(text)
}


//
//  CatalogItem.swift
//  SwiftCatalog
//
//  Created by Ben Johnson on 11/12/15.
//  Copyright © 2015 Pretty Swift. All rights reserved.
//

import UIKit

struct CatalogItem {
    let title: String
    let image: UIImage
    let itemDescription: String
    let category: String
    let orderQuantity: Int
}

Make order quantity a variable

//
//  CatalogItem.swift
//  SwiftCatalog
//
//  Created by Ben Johnson on 11/12/15.
//  Copyright © 2015 Pretty Swift. All rights reserved.
//

import UIKit

struct CatalogItem {
    let title: String
    let image: UIImage
    let itemDescription: String
    let category: String
    var orderQuantity: Int = 0
}


//
//  String.swift
//  EbloVaporServer
//
//  Created by yansong li on 2017-05-25.
//
//

import Foundation

/// Regex
extension String {

  /// Match a pattern and return matched string.
  public func match(pattern: String) -> String {
    do {
      let regex = try NSRegularExpression(pattern: pattern,
                                          options: .caseInsensitive)
      let range = NSMakeRange(0, self.characters.count)
      let matchRange = regex.rangeOfFirstMatch(in: self, range: range)
      if matchRange.location != NSNotFound {
        let chars = Array(self.characters)
        return String(chars[matchRange.location..<matchRange.location+matchRange.length])
      } else {
        return ""
      }
    } catch {
      print("Can not initialize regex")
      return ""
    }
  }
}

Fix Linux complaining about regex match.

//
//  String.swift
//  EbloVaporServer
//
//  Created by yansong li on 2017-05-25.
//
//

import Foundation

/// Regex
extension String {

  /// Match a pattern and return matched string.
  public func match(pattern: String) -> String {
    do {
      let regex = try NSRegularExpression(pattern: pattern,
                                          options: .caseInsensitive)
      let range = NSMakeRange(0, self.characters.count)
      let matchRange = regex.rangeOfFirstMatch(in: self, options: [], range: range)
      if matchRange.location != NSNotFound {
        let chars = Array(self.characters)
        return String(chars[matchRange.location..<matchRange.location+matchRange.length])
      } else {
        return ""
      }
    } catch {
      print("Can not initialize regex")
      return ""
    }
  }
}


// RUN: %target-typecheck-verify-swift

protocol P {}

struct S<T> {}

class A : P {}

extension S where T : P {
  typealias A = Int
  typealias B<U> = S<U>
}

_ = S<A>.A()           // Ok
_ = S<Int>.A()         // expected-error {{type 'Int' does not conform to protocol 'P'}}
_ = S<String>.B<Int>() // expected-error {{type 'String' does not conform to protocol 'P'}}

func foo<T>(_ s: S<T>.Type) {
  _ = s.A() // expected-error {{type 'T' does not conform to protocol 'P'}}
}

func bar<T: P>(_ s: S<T>.Type) {
  _ = s.A() // Ok
}

Add more test-cases for requirement checking in constrained extensions

// RUN: %target-typecheck-verify-swift

protocol P {}

struct S<T> {}

class C : P {}

extension S where T : P {
  typealias A = Int
  typealias B<U> = S<U>
}

extension S where T == Float {
  typealias C = Int
}

class A<T, U> {}

extension A where T == [U], U: P {
  typealias S1 = Int
}

extension A where T == [U], U == Int {
  typealias S2 = Int
}

class B<U> : A<[U], U> {}

_ = B<C>.S1()          // Ok
_ = B<Int>.S2()        // Ok
_ = B<Float>.S1()      // expected-error {{type 'Float' does not conform to protocol 'P'}}
_ = B<String>.S2()     // expected-error {{'B<String>.S2.Type' (aka 'Int.Type') requires the types '[String]' and '[Int]' be equivalent}}

_ = S<C>.A()           // Ok
_ = S<Int>.A()         // expected-error {{type 'Int' does not conform to protocol 'P'}}
_ = S<String>.B<Int>() // expected-error {{type 'String' does not conform to protocol 'P'}}
_ = S<Int>.C()         // expected-error {{'S<Int>.C.Type' (aka 'Int.Type') requires the types 'Int' and 'Float' be equivalent}}

func foo<T>(_ s: S<T>.Type) {
  _ = s.A() // expected-error {{type 'T' does not conform to protocol 'P'}}
}

func bar<T: P>(_ s: S<T>.Type) {
  _ = s.A() // Ok
}


//
//  NSString+BP.swift
//  Node War
//
//  Created by Kevin Lohman on 1/1/15.
//  Copyright (c) 2015 Logic High. All rights reserved.
//

import Foundation

extension String {
    func URLEncodedString() -> String? {
        let customAllowedSet =  NSCharacterSet.URLQueryAllowedCharacterSet()
        let escapedString = self.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
        return escapedString
    }
    static func queryStringFromParameters(parameters: Dictionary<String,String>) -> String? {
        if (parameters.count == 0)
        {
            return nil
        }
        var queryString : String? = nil
        for (key, value) in parameters {
            if let encodedKey = key.URLEncodedString() {
                if let encodedValue = value.URLEncodedString() {
                    if queryString == nil
                    {
                        queryString = "?"
                    }
                    else
                    {
                        queryString! += "&"
                    }
                    queryString! += encodedKey + "=" + encodedValue
                }
            }
        }
        return queryString
    }
}

Add method for retrieving double value from string

//
//  NSString+BP.swift
//  Node War
//
//  Created by Kevin Lohman on 1/1/15.
//  Copyright (c) 2015 Logic High. All rights reserved.
//

import Foundation

extension String {
    func URLEncodedString() -> String? {
        let customAllowedSet =  NSCharacterSet.URLQueryAllowedCharacterSet()
        let escapedString = self.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
        return escapedString
    }
    static func queryStringFromParameters(parameters: Dictionary<String,String>) -> String? {
        if (parameters.count == 0)
        {
            return nil
        }
        var queryString : String? = nil
        for (key, value) in parameters {
            if let encodedKey = key.URLEncodedString() {
                if let encodedValue = value.URLEncodedString() {
                    if queryString == nil
                    {
                        queryString = "?"
                    }
                    else
                    {
                        queryString! += "&"
                    }
                    queryString! += encodedKey + "=" + encodedValue
                }
            }
        }
        return queryString
    }

    var doubleValue: Double {
        if let number = NSNumberFormatter().numberFromString(self) {
            return number.doubleValue
        }
        return 0
    }
}


extension Node {
    public final class Text: Vector {
        /// Text contained within a text box.
        public let characters: String
        /// Style of text including font family and weight.
        public let style: TypeStyle
        /// Array with same number of elements as characeters in text box.
        ///
        /// Each element is a reference to the styleOverrideTable and maps to the
        /// corresponding character in the characters field.
        ///
        /// Elements with value 0 have the default type style.
        public let characterStyleOverrides: [Int]
        /// Map from ID to TypeStyle for looking up style overrides.
        public let styleOverrideTable: [Int: Style]

        private enum CodingKeys: String, CodingKey {
            case characters
            case style
            case characterStyleOverrides
            case styleOverrideTable
        }

        public required init(from decoder: Decoder) throws {
            let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)

            self.characters = try keyedDecoder.decode(String.self, forKey: .characters)
            self.style = try keyedDecoder.decode(TypeStyle.self, forKey: .style)
            self.characterStyleOverrides = try keyedDecoder.decode([Int].self, forKey: .characterStyleOverrides)
            self.styleOverrideTable = try keyedDecoder.decodeIfPresent([Int: Style].self, forKey: .styleOverrideTable) ?? [:]

            try super.init(from: decoder)
        }

        override var contentDescription: String {
            return super.contentDescription + """

                - characters: \(characters)
                - style: \(style)
                - characterStyleOverrides: \(characterStyleOverrides)
                - styleOverrideTable: \(styleOverrideTable)
                """
        }
    }
}

Use correct style in the text node.

extension Node {
    public final class Text: Vector {
        /// Text contained within a text box.
        public let characters: String
        /// Style of text including font family and weight.
        public let style: TypeStyle
        /// Array with same number of elements as characeters in text box.
        ///
        /// Each element is a reference to the styleOverrideTable and maps to the
        /// corresponding character in the characters field.
        ///
        /// Elements with value 0 have the default type style.
        public let characterStyleOverrides: [Int]
        /// Map from ID to TypeStyle for looking up style overrides.
        public let styleOverrideTable: [Int: TypeStyle]

        private enum CodingKeys: String, CodingKey {
            case characters
            case style
            case characterStyleOverrides
            case styleOverrideTable
        }

        public required init(from decoder: Decoder) throws {
            let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)

            self.characters = try keyedDecoder.decode(String.self, forKey: .characters)
            self.style = try keyedDecoder.decode(TypeStyle.self, forKey: .style)
            self.characterStyleOverrides = try keyedDecoder.decode([Int].self, forKey: .characterStyleOverrides)
            self.styleOverrideTable = try keyedDecoder.decodeIfPresent([Int: TypeStyle].self, forKey: .styleOverrideTable) ?? [:]

            try super.init(from: decoder)
        }

        override var contentDescription: String {
            return super.contentDescription + """

                - characters: \(characters)
                - style: \(style)
                - characterStyleOverrides: \(characterStyleOverrides)
                - styleOverrideTable: \(styleOverrideTable)
                """
        }
    }
}


// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

func b<b{class A:A{init(){a{enum B{case
func w

Annotate a crash test as crashing in the verifier

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
// REQUIRES: swift_ast_verifier

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

func b<b{class A:A{init(){a{enum B{case
func w


//
//  EnvironmentRepresentable.swift
//  EnvironmentSwitcher
//
//  Created by Ben Norris on 2/12/16.
//  Copyright © 2016 OC Tanner. All rights reserved.
//

import Foundation

public protocol EnvironmentRepresentable {
    typealias Environment: RawRepresentable
    var currentEnvironment: Environment { get set }
    var allEnvironments: [Environment] { get }
    var customPath: String? { get set }
}

Change protocol to use struct instead of enum

//
//  EnvironmentRepresentable.swift
//  EnvironmentSwitcher
//
//  Created by Ben Norris on 2/12/16.
//  Copyright © 2016 OC Tanner. All rights reserved.
//

import Foundation

public struct Environment {
    public let name: String
    public let path: String?
    public init(name: String, path: String?) {
        self.name = name
        self.path = path
    }
}

public protocol EnvironmentRepresentable {
    var currentEnvironment: Environment { get set }
    var allEnvironments: [Environment] { get }
    var customPath: String? { get set }
}


// RUN: %target-swiftc_driver -parse-as-library -module-name=test -target x86_64-apple-macosx10.15 -wmo -O -g -emit-ir %s  | %FileCheck %s
// REQUIRES: OS=macosx

// Check that the compiler does not emit any metadata for Mystruct and
// Teststruct, even with -g.
// This is also a driver issue, so we are testing with %target-swiftc_driver
// and not just with %target-swift-frontend.

// CHECK: ModuleID

// CHECK-NOT: Mystruct
// CHECK-NOT: Teststruct
// CHECK-NOT: define

// CHECK: DICompileUnit

protocol P {
}

struct Mystruct : P {
}

struct Teststruct {

  static var testvar: some P {
    return Mystruct()
  }
}

Make the test for lazy metadata emission a bit more complex

// RUN: %target-swiftc_driver -parse-as-library -module-name=test -target x86_64-apple-macosx10.15 -wmo -O -g -emit-ir %s  | %FileCheck %s
// REQUIRES: OS=macosx

// Check that the compiler does not emit any metadata for unused internal
// structs and enums, even with -g.
// This is also a driver issue, so we are testing with %target-swiftc_driver
// and not just with %target-swift-frontend.

// CHECK: ModuleID

// CHECK-NOT: Test
// CHECK-NOT: define

// CHECK: DICompileUnit

public protocol P {
  func foo() -> Int
}

struct Teststruct1 : P {
  func foo() -> Int { return 27 }
}

struct Teststruct : P {

  static var testvar: some P {
    switch getit().e {
      case .None:
        return Teststruct1()
      case .View(let v):
        return v
    }
  }

  @inline(never)
  static func getit() -> Teststruct2 {
    return Teststruct2(e: .View(Teststruct1()))
  }

  func foo() -> Int { return 27 }
}

struct Teststruct2 : P {
  enum Testenum {
    case None
    case View(Teststruct1)
  }

  var e: Testenum

  func foo() -> Int { return 27 }
}


//
// LinkedListNode.swift
// Collections
//
// Copyright (c) 2016 José Massada <jose.massada@gmail.com>
//
// 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.
//

/// A `LinkedList` node.
class LinkedListNode<Element> {
  /// Constructs a `LinkedListNode` that points to itself.
  init() {
    next_ = self
    previous_ = self
  }

  /// Constructs a `LinkedListNode`.
  init(value: Element?, next: LinkedListNode?, previous: LinkedListNode?) {
    value_ = value
    next_ = next
    previous_ = previous
  }

  /// Returns `true` if `self` is the root node.
  var isRoot: Bool {
    return next_ === self
  }

  /// The value.
  var value_: Element!

  /// The next node.
  var next_: LinkedListNode!

  /// The previous node.
  var previous_: LinkedListNode!
}

Remove not needed property from linked list node.

//
// LinkedListNode.swift
// Collections
//
// Copyright (c) 2016 José Massada <jose.massada@gmail.com>
//
// 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.
//

/// A `LinkedList` node.
class LinkedListNode<Element> {
  /// Constructs a `LinkedListNode` that points to itself.
  init() {
    next_ = self
    previous_ = self
  }

  /// Constructs a `LinkedListNode`.
  init(value: Element?, next: LinkedListNode?, previous: LinkedListNode?) {
    value_ = value
    next_ = next
    previous_ = previous
  }

  /// The value.
  var value_: Element!

  /// The next node.
  var next_: LinkedListNode!

  /// The previous node.
  var previous_: LinkedListNode!
}


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

final class ElaborationTests: XCTestCase {

}

import Manifold
import XCTest

Test that the type of Type is elaborated.

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

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

import Assertions
import Manifold
import XCTest


//
//  Message.swift
//  Rocket.Chat
//
//  Created by Rafael K. Streit on 7/14/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import Foundation
import RealmSwift
import SwiftyJSON

enum MessageType {
    case text
    case textAttachment
    case image
    case audio
    case video
    case url

    case roomNameChanged
    case userAdded
    case userRemoved
    case userJoined
    case userLeft
    case userMuted
    case userUnmuted
    case welcome
    case messageRemoved
    case subscriptionRoleAdded
    case subscriptionRoleRemoved
    case roomArchived
    case roomUnarchived
}

class Message: BaseModel {
    dynamic var subscription: Subscription!
    dynamic var internalType: String!
    dynamic var rid = ""
    dynamic var createdAt: Date?
    dynamic var updatedAt: Date?
    dynamic var user: User?
    dynamic var text = ""

    dynamic var alias = ""
    dynamic var avatar = ""

    var mentions = List<Mention>()
    var attachments = List<Attachment>()
    var urls = List<MessageURL>()

    var type: MessageType {
        if let attachment = attachments.first {
            return attachment.type
        }

        if let url = urls.first {
            if url.isValid() {
                return .url
            }
        }

        return .text
    }
}

Add real values & get it from enum

//
//  Message.swift
//  Rocket.Chat
//
//  Created by Rafael K. Streit on 7/14/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import Foundation
import RealmSwift
import SwiftyJSON

enum MessageType: String {
    case text
    case textAttachment
    case image
    case audio
    case video
    case url

    case roomNameChanged = "r"
    case userAdded = "au"
    case userRemoved = "ru"
    case userJoined = "uj"
    case userLeft = "ul"
    case userMuted = "user-muted"
    case userUnmuted = "user-unmuted"
    case welcome = "wm"
    case messageRemoved = "rm"
    case subscriptionRoleAdded = "subscription-role-added"
    case subscriptionRoleRemoved = "subscription-role-removed"
    case roomArchived = "room-archived"
    case roomUnarchived = "room-unarchived"
}

class Message: BaseModel {
    dynamic var subscription: Subscription!
    dynamic var internalType: String!
    dynamic var rid = ""
    dynamic var createdAt: Date?
    dynamic var updatedAt: Date?
    dynamic var user: User?
    dynamic var text = ""

    dynamic var alias = ""
    dynamic var avatar = ""

    var mentions = List<Mention>()
    var attachments = List<Attachment>()
    var urls = List<MessageURL>()

    var type: MessageType {
        if let attachment = attachments.first {
            return attachment.type
        }

        if let url = urls.first {
            if url.isValid() {
                return .url
            }
        }

        return MessageType(rawValue: internalType) ?? .text
    }
}


//
//  DocumentsUtil.swift
//  Pods
//
//  Created by Gregory Sholl e Santos on 19/07/17.
//
//

import UIKit

//MARK: - Variables & Accessors

public class DocumentsUtil {

    private init() {}
}

//MARK: - Path

public extension DocumentsUtil {

    public func path(forDomainMask domainMask: FileManager.SearchPathDomainMask = .userDomainMask) throws -> String {
        let documentPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, domainMask, true)
        if documentPaths.isEmpty {
            throw MochaException.fileNotFoundException
        }
        return documentPaths[0]
    }

    public func path(of filename: String?, with domainMask: FileManager.SearchPathDomainMask = .userDomainMask) throws -> String {
        guard let filename = filename, filename.isNotEmpty else {
            throw MochaException.fileNotFoundException
        }
        let documentPath = try path(forDomainMask: domainMask)
        return documentPath.appendingPathComponent(filename)
    }
}

Add existential methods for documents

//
//  DocumentsUtil.swift
//  Pods
//
//  Created by Gregory Sholl e Santos on 19/07/17.
//
//

import UIKit

//MARK: - Variables & Accessors

public class DocumentsUtil {

    private init() {}
}

//MARK: - Path

public extension DocumentsUtil {

    public func path(forDomainMask domainMask: FileManager.SearchPathDomainMask = .userDomainMask) throws -> String {
        let documentPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, domainMask, true)
        if documentPaths.isEmpty {
            throw MochaException.fileNotFoundException
        }
        return documentPaths[0]
    }

    public func path(of filename: String?, with domainMask: FileManager.SearchPathDomainMask = .userDomainMask) throws -> String {
        guard let filename = filename, filename.isNotEmpty else {
            throw MochaException.fileNotFoundException
        }
        let documentPath = try path(forDomainMask: domainMask)
        return documentPath.appendingPathComponent(filename)
    }
}

//MARK: - Exists

public extension DocumentsUtil {

    public func fileExists(_ filename: String?) -> Bool {
        do {
            let path = try self.path(of: filename)
            return FileManager.default.fileExists(atPath: path)
        } catch {
            return false
        }
    }

    public func fileExists(atPath path: String) -> Bool {
        return FileManager.default.fileExists(atPath: path)
    }
}


import UIKit
import AsyncDisplayKit

public class CounterNode: ASDisplayNode {

  public let size: CGSize
  public var textNode: ASTextNode

  // MARK: - Initialization

  public init(size: CGSize, count: Int, totalCount: Int) {
    self.size = size

    textNode = ASTextNode()
    super.init()

    backgroundColor = UIColor(white: 0, alpha: 0.5)

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .Center

    var attributes = [
      NSFontAttributeName: UIFont.systemFontOfSize(34),
      NSForegroundColorAttributeName: UIColor.whiteColor(),
      NSParagraphStyleAttributeName: paragraphStyle
    ]

    let text = "+\(totalCount - count)"

    textNode.attributedString = NSAttributedString(
      string: text,
      attributes: attributes)

    addSubnode(textNode)
  }

  // MARK: - Layout

  override public func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize {
    textNode.measure(CGSize(
      width: size.width,
      height: CGFloat(FLT_MAX)))

    return CGSizeMake(size.width, size.height)
  }

  override public func layout() {
    let textSize = textNode.calculatedSize
    let textOrigin = textSize.centerInSize(size)
    textNode.frame = CGRect(
      origin: textOrigin,
      size: textSize)
  }
}

Use let instead of var

import UIKit
import AsyncDisplayKit

public class CounterNode: ASDisplayNode {

  public let size: CGSize
  public var textNode: ASTextNode

  // MARK: - Initialization

  public init(size: CGSize, count: Int, totalCount: Int) {
    self.size = size

    textNode = ASTextNode()
    super.init()

    backgroundColor = UIColor(white: 0, alpha: 0.5)

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .Center

    let attributes = [
      NSFontAttributeName: UIFont.systemFontOfSize(34),
      NSForegroundColorAttributeName: UIColor.whiteColor(),
      NSParagraphStyleAttributeName: paragraphStyle
    ]

    let text = "+\(totalCount - count)"

    textNode.attributedString = NSAttributedString(
      string: text,
      attributes: attributes)

    addSubnode(textNode)
  }

  // MARK: - Layout

  override public func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize {
    textNode.measure(CGSize(
      width: size.width,
      height: CGFloat(FLT_MAX)))

    return CGSizeMake(size.width, size.height)
  }

  override public func layout() {
    let textSize = textNode.calculatedSize
    let textOrigin = textSize.centerInSize(size)
    textNode.frame = CGRect(
      origin: textOrigin,
      size: textSize)
  }
}


/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import Foundation
import XCTest

class ReaderModeTest : XCTestCase {
    func testReaderMode() {
        UITestUtils.restart()
        let app = XCUIApplication()
        UITestUtils.loadSite(app, "www.google.com/intl/en/about")

        app.buttons["Reader View"].tap()
        app.coordinateWithNormalizedOffset(CGVector(dx: 0, dy: 0)).coordinateWithOffset(CGVector(dx: 100, dy: 75)).tap()

        app.buttons["Serif"].tap()
        app.buttons["Sans-serif"].tap()
        app.buttons["Decrease text size"].tap()
        app.buttons["Increase text size"].tap()
        app.buttons["Light"].tap()
        app.buttons["Dark"].tap()
        app.buttons["Sepia"].tap()

        app.buttons["Reader View"].tap()
    }
}

Remove final step of reader mode test case which is causing test failures. The test is fine as-is.

/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import Foundation
import XCTest

class ReaderModeTest : XCTestCase {
    func testReaderMode() {
        UITestUtils.restart()
        let app = XCUIApplication()
        UITestUtils.loadSite(app, "www.google.com/intl/en/about")

        app.buttons["Reader View"].tap()
        app.coordinateWithNormalizedOffset(CGVector(dx: 0, dy: 0)).coordinateWithOffset(CGVector(dx: 100, dy: 75)).tap()

        app.buttons["Serif"].tap()
        app.buttons["Sans-serif"].tap()
        app.buttons["Decrease text size"].tap()
        app.buttons["Increase text size"].tap()
        app.buttons["Light"].tap()
        app.buttons["Dark"].tap()
        app.buttons["Sepia"].tap()

    }
}


//
//  ContentListHeaderView.swift
//  JumuNordost
//
//  Created by Martin Richter on 02/03/16.
//  Copyright © 2016 Martin Richter. All rights reserved.
//

import Cartography

class ContestListHeaderView: UIView {

    private let textLabel = Label(fontWeight: .Regular, fontStyle: .Italic, fontSize: .Medium)

    // MARK: - Lifecycle

    convenience init(text: String) {
        self.init()

        self.layoutMargins = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)

        textLabel.textAlignment = .Center
        textLabel.textColor = Color.secondaryTextColor
        textLabel.text = text

        addSubview(textLabel)
        makeConstraints()
    }

    // MARK: - Layout

    private func makeConstraints() {
        constrain(textLabel, self) { textLabel, superview in
            textLabel.top == superview.topMargin
            textLabel.leading == superview.leadingMargin
            textLabel.trailing == superview.trailingMargin
            textLabel.bottom == superview.bottom
        }
    }
}

Increase vertical whitespace around content list header

//
//  ContentListHeaderView.swift
//  JumuNordost
//
//  Created by Martin Richter on 02/03/16.
//  Copyright © 2016 Martin Richter. All rights reserved.
//

import Cartography

class ContestListHeaderView: UIView {

    private let textLabel = Label(fontWeight: .Regular, fontStyle: .Italic, fontSize: .Medium)

    // MARK: - Lifecycle

    convenience init(text: String) {
        self.init()

        self.layoutMargins = UIEdgeInsets(top: 24, left: 16, bottom: 8, right: 16)

        textLabel.textAlignment = .Center
        textLabel.textColor = Color.secondaryTextColor
        textLabel.text = text

        addSubview(textLabel)
        makeConstraints()
    }

    // MARK: - Layout

    private func makeConstraints() {
        constrain(textLabel, self) { textLabel, superview in
            textLabel.edges == superview.edgesWithinMargins
        }
    }
}


import XCTest
@testable import gattaca

class TCHome:XCTestCase
{
    private var session:MSession?
    private var controller:CHome?
    private let kWaitSession:UInt32 = 3

    override func setUp()
    {
        super.setUp()

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

        let controller:CHome = CHome(session:session)
        controller.beginAppearanceTransition(true, animated:false)
        controller.endAppearanceTransition()
        self.controller = controller
    }

    func testSessionLoads()
    {
        sleep(kWaitSession)

        guard

            let status:MSession.Status = session?.status

        else
        {
            return
        }

        XCTAssertEqual(
            status,
            MSession.Status.loaded,
            "session is not being loaded")
    }
}

Add test for session model

import XCTest
@testable import gattaca

class TCHome:XCTestCase
{
    private var session:MSession?
    private var controller:CHome?
    private let kWaitSession:UInt32 = 2

    override func setUp()
    {
        super.setUp()

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

        let controller:CHome = CHome(session:session)
        controller.beginAppearanceTransition(true, animated:false)
        controller.endAppearanceTransition()
        self.controller = controller
    }

    func testSessionLoads()
    {
        sleep(kWaitSession)

        guard

            let status:MSession.Status = session?.status

        else
        {
            return
        }

        XCTAssertEqual(
            status,
            MSession.Status.loaded,
            "session is not being loaded")
    }

    func testSessionModel()
    {
        sleep(kWaitSession)

        let session:DSession? = self.session?.session

        XCTAssertNotNil(
            session,
            "failed loading session from core data")
    }
}


// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: objc_interop

// Distributed under the terms of the MIT license
// Test case found by https://github.com/benshan (Ben Shanfelder)

import Cocoa

protocol A: class {
    var target: AnyObject? { set } // FIXME: Missing "get" wrt extension on NSControl leads to crash.
}

class B: NSObject {
}

extension NSControl: A {}

Annotate a crash test that depends on AppKit

// RUN: not --crash %target-swift-frontend %s -parse

// The test requires that NSControl is a class.  Remove this requirement when
// the crash is fixed.
// REQUIRES: OS=macosx

// Distributed under the terms of the MIT license
// Test case found by https://github.com/benshan (Ben Shanfelder)

import Cocoa

protocol A: class {
    var target: AnyObject? { set } // FIXME: Missing "get" wrt extension on NSControl leads to crash.
}

class B: NSObject {
}

extension NSControl: A {}


//
//  Appearance.swift
//  JumuNordost
//
//  Created by Martin Richter on 21/02/16.
//  Copyright © 2016 Martin Richter. All rights reserved.
//

import Argo
import Curry

enum ParticipantRole: String {
    case Soloist = "S"
    case Ensemblist = "E"
    case Accompanist = "B"
}

struct Appearance {
    let participantName: String
    let participantRole: ParticipantRole
    let instrument: String
}

// MARK: - Decodable

extension ParticipantRole: Decodable {}

extension Appearance: Decodable {
    static func decode(json: JSON) -> Decoded<Appearance> {
        return curry(self.init)
            <^> json <| "participant_name"
            <*> json <| "participant_role"
            <*> json <| "instrument_name"
    }
}

Update participant role mapping with new role identifiers

//
//  Appearance.swift
//  JumuNordost
//
//  Created by Martin Richter on 21/02/16.
//  Copyright © 2016 Martin Richter. All rights reserved.
//

import Argo
import Curry

enum ParticipantRole: String {
    case Soloist = "soloist"
    case Ensemblist = "ensemblist"
    case Accompanist = "accompanist"
}

struct Appearance {
    let participantName: String
    let participantRole: ParticipantRole
    let instrument: String
}

// MARK: - Decodable

extension ParticipantRole: Decodable {}

extension Appearance: Decodable {
    static func decode(json: JSON) -> Decoded<Appearance> {
        return curry(self.init)
            <^> json <| "participant_name"
            <*> json <| "participant_role"
            <*> json <| "instrument_name"
    }
}


import Foundation
import Kitura
import LoggerAPI
import HeliumLogger
import {{{applicationModule}}}

do {

    HeliumLogger.use(LoggerMessageType.info)

    let app = try App()
    try app.run()

} catch let error {
    Log.error(error.localizedDescription)
}

Remove logging config from executable target

import Kitura
import LoggerAPI
import {{{applicationModule}}}

do {

    let app = try App()
    try app.run()

} catch let error {
    Log.error(error.localizedDescription)
}


import Foundation

public class FileStorage {
    public enum Error: Swift.Error {
        case couldNotCreateDirectory
    }

    let path: String

    public init(path: String) throws {
        if !FileManager.default.directoryExists(atPath: path) {
            do {
                try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
            } catch {
                throw Error.couldNotCreateDirectory
            }
        }
        self.path = path
    }

    subscript(key: String) -> Data? {
        get {
            let entityPath = URL(fileURLWithPath: path).appendingPathComponent(key)
            guard let data = try? Data(contentsOf: entityPath, options: []) else {
                return nil
            }
            return data
        }
        set {
            let entityPath = URL(fileURLWithPath: path).appendingPathComponent(key)
            if let newValue = newValue {
                try! newValue.write(to: entityPath)
            } else {
                try! FileManager.default.removeItem(at: entityPath)
            }
        }
    }
}

Create nested directories in file storage, if required

import Foundation

public class FileStorage {
    public enum Error: Swift.Error {
        case couldNotCreateDirectory
    }

    let path: String

    public init(path: String) throws {
        if !FileManager.default.directoryExists(atPath: path) {
            do {
                try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            } catch {
                throw Error.couldNotCreateDirectory
            }
        }
        self.path = path
    }

    subscript(key: String) -> Data? {
        get {
            let entityPath = URL(fileURLWithPath: path).appendingPathComponent(key)
            guard let data = try? Data(contentsOf: entityPath, options: []) else {
                return nil
            }
            return data
        }
        set {
            let entityPath = URL(fileURLWithPath: path).appendingPathComponent(key)
            if let newValue = newValue {
                try! newValue.write(to: entityPath)
            } else {
                try! FileManager.default.removeItem(at: entityPath)
            }
        }
    }
}


//
//  ViewController.swift
//  KeyboardResize Example
//
//  Created by Juan Alberto Uribe Otero on 4/22/16.
//  Copyright © 2016 Kogi Mobile. All rights reserved.
//

import UIKit
import KeyboardResize

class ViewController: UIViewController {

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

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

}

Add tap gesture to dismiss keyboard on example

//
//  ViewController.swift
//  KeyboardResize Example
//
//  Created by Juan Alberto Uribe Otero on 4/22/16.
//  Copyright © 2016 Kogi Mobile. All rights reserved.
//

import UIKit
import KeyboardResize

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        kg_resizeViewWhenKeyboardAppears = true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeybaord))
        view.addGestureRecognizer(tapGesture)
    }

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

    func dismissKeybaord() {
        view.endEditing(true)
    }
}


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

import XCTest

final class BindTests: XCTestCase {
}

Define a Tree structure for the test.

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

import XCTest

struct Tree<T: Equatable>: Equatable, Printable {
	init(_ value: T, _ children: [Tree] = []) {
		self.values = [ value ]
		self.children = children
	}

	let values: [T]
	let children: [Tree]

	// MARK: Printable

	var description: String {
		let space = " "
		let valueString = space.join(map(values, toString))
		return children.count > 0 ?
			"(\(valueString) \(space.join(map(children, toString))))"
		:	"(\(valueString))"
	}
}

func == <T: Equatable> (left: Tree<T>, right: Tree<T>) -> Bool {
	return left.values == right.values && left.children == right.children
}

final class BindTests: XCTestCase {
}


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

/// Returns a parser which requires `parser` to parse, passes its parsed trees to a function `f`, and then requires the result of `f` to parse.
///
/// This can be used to conveniently make a parser which depends on earlier parsed input, for example to parse exactly the same number of characters, or to parse structurally significant indentation.
public func >>- <C: CollectionType, T, U> (parser: Parser<C, T>.Function, f: T -> Parser<C, U>.Function) -> Parser<C, U>.Function {
	return { input, index in
		parser(input, index).map { f($0)(input, $1) } ?? nil
	}
}

// MARK: - Operators

/// Flat map operator.
infix operator >>- {
	associativity left
	precedence 150
}

Define >>- in terms of Optional.flatMap.

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

/// Returns a parser which requires `parser` to parse, passes its parsed trees to a function `f`, and then requires the result of `f` to parse.
///
/// This can be used to conveniently make a parser which depends on earlier parsed input, for example to parse exactly the same number of characters, or to parse structurally significant indentation.
public func >>- <C: CollectionType, T, U> (parser: Parser<C, T>.Function, f: T -> Parser<C, U>.Function) -> Parser<C, U>.Function {
	return { input, index in
		parser(input, index).flatMap { f($0)(input, $1) }
	}
}

// MARK: - Operators

/// Flat map operator.
infix operator >>- {
	associativity left
	precedence 150
}


// 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-ios8.0 -target-cpu cyclone \
// RUN:     -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc -tbi \
// RUN:     -O -S %s -parse-as-library | \
// RUN:   FileCheck --check-prefix=NO_TBI %s
// REQUIRES: executable_test

// REQUIRES: CPU=arm64, OS=ios

// Verify that TBI is on by default in Swift.

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

Remove option from test that did not do anything.

// 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-ios8.0 -target-cpu cyclone \
// RUN:     -O -S %s -parse-as-library | \
// RUN:   FileCheck --check-prefix=NO_TBI %s
// REQUIRES: executable_test

// REQUIRES: CPU=arm64, OS=ios

// Verify that TBI is on by default in Swift.

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


// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "Bond",
    platforms: [
        .macOS(.v10_11), .iOS(.v8), .tvOS(.v9)
    ],
    products: [
        .library(name: "Bond", targets: ["Bond"])
    ],
    dependencies: [
        .package(url: "https://github.com/DeclarativeHub/ReactiveKit.git", .upToNextMajor(from: "3.14")),
        .package(url: "https://github.com/tonyarnold/Differ.git", .upToNextMajor(from: "1.4"))
    ],
    targets: [
        .target(name: "BNDProtocolProxyBase"),
        .target(name: "Bond", dependencies: ["BNDProtocolProxyBase", "ReactiveKit", "Differ"]),
        .testTarget(name: "BondTests", dependencies: ["Bond", "ReactiveKit"])
    ]
)

Fix the dependency versions to use semantic version numbers

// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "Bond",
    platforms: [
        .macOS(.v10_11), .iOS(.v8), .tvOS(.v9)
    ],
    products: [
        .library(name: "Bond", targets: ["Bond"])
    ],
    dependencies: [
        .package(url: "https://github.com/DeclarativeHub/ReactiveKit.git", .upToNextMajor(from: "3.14.2")),
        .package(url: "https://github.com/tonyarnold/Differ.git", .upToNextMajor(from: "1.4.3"))
    ],
    targets: [
        .target(name: "BNDProtocolProxyBase"),
        .target(name: "Bond", dependencies: ["BNDProtocolProxyBase", "ReactiveKit", "Differ"]),
        .testTarget(name: "BondTests", dependencies: ["Bond", "ReactiveKit"])
    ]
)


// swift-tools-version:4.0

import PackageDescription

let package = Package(
  name: "LLVM",
  products: [
    .library(
      name: "LLVM",
      targets: ["LLVM"]),
  ],
  dependencies: [
    .package(url: "https://github.com/trill-lang/cllvm.git", .branch("master")),
    .package(url: "https://github.com/trill-lang/FileCheck.git", .branch("master")),
  ],
  targets: [
    .target(
      name: "LLVM"),
    .testTarget(
      name: "LLVMTests",
      dependencies: ["LLVM", "FileCheck"]),
  ]
)

Use explicit dependencies for FileCheck and cllvm

// swift-tools-version:4.0

import PackageDescription

let package = Package(
  name: "LLVM",
  products: [
    .library(
      name: "LLVM",
      targets: ["LLVM"]),
  ],
  dependencies: [
    .package(url: "https://github.com/trill-lang/cllvm.git", from: "0.0.3"),
    .package(url: "https://github.com/trill-lang/FileCheck.git", from: "0.0.3"),
  ],
  targets: [
    .target(
      name: "LLVM"),
    .testTarget(
      name: "LLVMTests",
      dependencies: ["LLVM", "FileCheck"]),
  ]
)


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

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

// RUN: %swift -c -emit-module -o %t %S/ASTSection.swift
// RUN: %ld %t/ASTSection.o -sectcreate __SWIFT __ast %t/ASTSection.swiftmodule -o %t/ASTSection.dylib -L%libdir/swift/macosx -dylib -lSystem
// RUN: lldb-moduleimport-test %t/ASTSection.dylib | FileCheck %S/ASTSection.swift
// REQUIRES: OS=macosx

Drop the ability to set a custom 'ld'.

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

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

// RUN: %swift -c -emit-module -o %t %S/ASTSection.swift
// RUN: ld %t/ASTSection.o -sectcreate __SWIFT __ast %t/ASTSection.swiftmodule -o %t/ASTSection.dylib -L%libdir/swift/macosx -dylib -lSystem
// RUN: lldb-moduleimport-test %t/ASTSection.dylib | FileCheck %S/ASTSection.swift
// REQUIRES: OS=macosx


import Cocoa
import Foundation

class Installer {

    static func installAndRunApp(packagedApp: PackagedApp, simulator: Simulator) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            shutDownCurrentSimulatorSessions()

            system("xcrun instruments -w \"\(simulator.identifierString)\"")

            system("xcrun simctl install booted \"\(packagedApp.bundlePath)\"")
            system("xcrun simctl launch booted \(packagedApp.bundleIdentifier)")

            NSApplication.sharedApplication().terminate(nil)
        }
    }

    static func shutDownCurrentSimulatorSessions() {
        system("killall \"iOS Simulator\"")
        system("xcrun simctl shutdown booted")
    }

}

Uninstall the app first before installing.

import Cocoa
import Foundation

class Installer {

    static func installAndRunApp(packagedApp: PackagedApp, simulator: Simulator) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            shutDownCurrentSimulatorSessions()

            system("xcrun instruments -w \"\(simulator.identifierString)\"")

            system("xcrun simctl uninstall booted \(packagedApp.bundleIdentifier)")
            system("xcrun simctl install booted \"\(packagedApp.bundlePath)\"")
            system("xcrun simctl launch booted \(packagedApp.bundleIdentifier)")

            NSApplication.sharedApplication().terminate(nil)
        }
    }

    static func shutDownCurrentSimulatorSessions() {
        system("killall \"iOS Simulator\"")
        system("xcrun simctl shutdown booted")
    }

}


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

final class ValueTests: XCTestCase {
	func testQuotation() {
		assert(Value.pi(.type, id).quote, ==, Value.pi(.type, id).quote)
	}

	func testNestedQuotation() {
		assert(Value.pi(.type) { Value.pi(.type, const($0)) }.quote, ==, Term(.Pi(Box(.type), Box(Term(.Pi(Box(.type), Box(Term(.Bound(1)))))))))
	}

	func testQuotationMapsNestedBoundVariablesToBoundVariables() {
		assert(Value.pi(.type) { _ in Value.pi(.type, id) }.quote, ==, Term(.Pi(Box(.type), Box(Term(.Pi(Box(.type), Box(Term(.Bound(0)))))))))
	}

	func testNullaryProductIsUnitTerm() {
		assert(Value.product([]).quote, ==, Term.unitTerm)
	}
}

import Assertions
import Box
import Either
import Manifold
import Prelude
import XCTest

Test that the unary product ends with the unit term.

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

final class ValueTests: XCTestCase {
	func testQuotation() {
		assert(Value.pi(.type, id).quote, ==, Value.pi(.type, id).quote)
	}

	func testNestedQuotation() {
		assert(Value.pi(.type) { Value.pi(.type, const($0)) }.quote, ==, Term(.Pi(Box(.type), Box(Term(.Pi(Box(.type), Box(Term(.Bound(1)))))))))
	}

	func testQuotationMapsNestedBoundVariablesToBoundVariables() {
		assert(Value.pi(.type) { _ in Value.pi(.type, id) }.quote, ==, Term(.Pi(Box(.type), Box(Term(.Pi(Box(.type), Box(Term(.Bound(0)))))))))
	}

	func testNullaryProductIsUnitTerm() {
		assert(Value.product([]).quote, ==, Term.unitTerm)
	}

	func testUnaryProductEndsWithUnitTerm() {
		assert(Value.product([ Value.type ]).quote, ==, Term(.Sigma(Box(.type), Box(.unitTerm))))
	}
}

import Assertions
import Box
import Either
import Manifold
import Prelude
import XCTest


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

import Foundation
import BitByteData

class SevenZipProperty {

    let type: UInt8
    let size: Int
    let bytes: [UInt8]

    init(_ type: UInt8, _ size: Int, _ bytes: [UInt8]) {
        self.type = type
        self.size = size
        self.bytes = bytes
    }

    static func getProperties(_ bitReader: MsbBitReader) throws -> [SevenZipProperty] {
        var properties = [SevenZipProperty]()
        while true {
            let propertyType = bitReader.byte()
            if propertyType == 0 {
                break
            }
            let propertySize = bitReader.szMbd()
            properties.append(SevenZipProperty(propertyType, propertySize, bitReader.bytes(count: propertySize)))
        }
        return properties
    }

}

Change SevenZipProperty from class to struct

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

import Foundation
import BitByteData

struct SevenZipProperty {

    let type: UInt8
    let size: Int
    let bytes: [UInt8]

    init(_ type: UInt8, _ size: Int, _ bytes: [UInt8]) {
        self.type = type
        self.size = size
        self.bytes = bytes
    }

    static func getProperties(_ bitReader: MsbBitReader) throws -> [SevenZipProperty] {
        var properties = [SevenZipProperty]()
        while true {
            let propertyType = bitReader.byte()
            if propertyType == 0 {
                break
            }
            let propertySize = bitReader.szMbd()
            properties.append(SevenZipProperty(propertyType, propertySize, bitReader.bytes(count: propertySize)))
        }
        return properties
    }

}


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

/// Appends `collection` with the elements of a `reducible`.
public func += <E: ExtensibleCollectionType, R: ReducibleType where R.Element == E.Generator.Element> (inout left: E, right: R) {
	reduce(right, ()) {
		left.append($1)
	}
}

public func + <E: ExtensibleCollectionType, R: ReducibleType where R.Element == E.Generator.Element> (left: E, right: R) -> E {
	return reduce(right, left) { $0 + [$1] }
}

Correct the documentation of +=.

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

/// Extends `collection` with the elements of a `reducible`.
public func += <E: ExtensibleCollectionType, R: ReducibleType where R.Element == E.Generator.Element> (inout left: E, right: R) {
	reduce(right, ()) {
		left.append($1)
	}
}

public func + <E: ExtensibleCollectionType, R: ReducibleType where R.Element == E.Generator.Element> (left: E, right: R) -> E {
	return reduce(right, left) { $0 + [$1] }
}


//
//  Beer.swift
//  BreweryDB
//
//  Created by Jake Welton on 1/3/16.
//  Copyright © 2016 Jake Welton. All rights reserved.
//

import Foundation

class Beer {

}

Create initializers for api required properties

//
//  Beer.swift
//  BreweryDB
//
//  Created by Jake Welton on 1/3/16.
//  Copyright © 2016 Jake Welton. All rights reserved.
//

import Foundation

class Beer {
    init(name: String) {}
    init(abv: String) {}
    init(ibu: String) {}
    init(srmId: String) {}
    init(availabilityId: String) {}
    init(styleId: String) {}
}