//
//  Safe.swift
//  SafeSwift
//
//  Created by Terry Lewis II on 6/28/14.
//  Copyright (c) 2014 Blue Plover Productions. All rights reserved.
//

import Foundation

extension Array {
    func safeIndex(i:Int) -> T? {
        if  i >= 0 && i < self.count {
            return self[i]
        } else {
            return nil
        }
    }

    func safeHead() -> T? {
        if !self.isEmpty {
            return self[0]
        } else {
            return nil
        }
    }

    func safeLast() -> T? {
        if !self.isEmpty {
            return self[self.count - 1]
        } else {
            return nil
        }
    }

    func safeTail() -> T[]? {
        if self.count > 1 {
            return Array(self[1..self.count])
        } else {
            return nil
        }
    }

    func safeRange(r:Range<Int>) -> T[]? {
        if r.startIndex > r.endIndex {
            return nil
        }
        if r.startIndex >= 0 && r.endIndex <= self.count {
            return Array(self[r])
        }

        return nil
    }
}

func safeUnwrap<T>(op:Optional<T>, defaultVal:T) -> T {
    switch op {
    case let .Some(a): return a
    case .None: return defaultVal
    }
}

Update safeTail to return empty list if called

//
//  Safe.swift
//  SafeSwift
//
//  Created by Terry Lewis II on 6/28/14.
//  Copyright (c) 2014 Blue Plover Productions. All rights reserved.
//

import Foundation

extension Array {
    func safeIndex(i:Int) -> T? {
        if  i >= 0 && i < self.count {
            return self[i]
        } else {
            return nil
        }
    }

    func safeHead() -> T? {
        if !self.isEmpty {
            return self[0]
        } else {
            return nil
        }
    }

    func safeLast() -> T? {
        if !self.isEmpty {
            return self[self.count - 1]
        } else {
            return nil
        }
    }

    func safeTail() -> T[]? {
        if self.count > 1 {
            return Array(self[1..self.count])
        } else if self.count == 1 {
            return []
        } else {
            return nil
        }
    }

    func safeRange(r:Range<Int>) -> T[]? {
        if r.startIndex > r.endIndex {
            return nil
        }
        if r.startIndex >= 0 && r.endIndex <= self.count {
            return Array(self[r])
        }

        return nil
    }
}

func safeUnwrap<T>(op:Optional<T>, defaultVal:T) -> T {
    switch op {
    case let .Some(a): return a
    case .None: return defaultVal
    }
}


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

final class ChurchPairTests: XCTestCase {

}

import Manifold
import XCTest

Test that the church pair module typechecks.

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

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

private let module = Module<Term>.churchPair

import Manifold
import XCTest


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

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

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

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

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

Remove public modifier from functions

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

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

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

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

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


//
//  DateFormatterExtensions.swift
//  Pods
//
//  Created by Phillipe Casorla Sagot on 3/7/17.
//
//

import Foundation

extension DateFormatter {

    class internal func makespace() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        return dateFormatter
    }

    class internal func makespaceDateFormatterWithMicroSeconds() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
        return dateFormatter
    }

    class internal func makespaceHourMinute() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "h:mm a"
        return dateFormatter
    }

    class internal func makespaceYearMonthDay() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter
    }

    class internal func string(fromMSDate msDate: Date) -> String {
        return self.makespace().string(from: msDate)
    }

    class internal func date(fromMSString dateString: String) -> Date? {
        return self.makespace().date(from: dateString)
    }
}

Make date exstensions public again

//
//  DateFormatterExtensions.swift
//  Pods
//
//  Created by Phillipe Casorla Sagot on 3/7/17.
//
//

import Foundation

extension DateFormatter {

    class public func makespace() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        return dateFormatter
    }

    class public func makespaceDateFormatterWithMicroSeconds() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
        return dateFormatter
    }

    class public func makespaceHourMinute() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "h:mm a"
        return dateFormatter
    }

    class public func makespaceYearMonthDay() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter
    }

    class public func string(fromMSDate msDate: Date) -> String {
        return self.makespace().string(from: msDate)
    }

    class public func date(fromMSString dateString: String) -> Date? {
        return self.makespace().date(from: dateString)
    }
}


import XCTest
import SwiftSyntax
import SwiftParser

public class ParserTests: XCTestCase {
  func testSelfParse() throws {
    let currentDir = URL(fileURLWithPath: #file)
      .deletingLastPathComponent()
      .deletingLastPathComponent()
      .deletingLastPathComponent()
      .appendingPathComponent("Sources")
    let fileURLs = FileManager.default
      .enumerator(at: currentDir, includingPropertiesForKeys: nil)!
      .compactMap({ $0 as? URL })
      .filter({$0.pathExtension == "swift"})
    for fileURL in fileURLs {
      XCTAssertNoThrow(try {
        let fileContents = try String(contentsOf: fileURL)
        let parsed = try Parser.parse(source: fileContents)
        AssertStringsEqualWithDiff("\(parsed)", fileContents)
        let diagnostics = ParseDiagnosticsGenerator.diagnostics(for: parsed)
        if !diagnostics.isEmpty {
          var locationAndDiagnostics: [String] = []
          let locationConverter = SourceLocationConverter(file: fileURL.lastPathComponent, tree: parsed)
          for diag in diagnostics {
            let location = diag.location(converter: locationConverter)
            let message = diag.message
            locationAndDiagnostics.append("\(location): \(message)")
          }
          XCTFail("""
          Received the following diagnostics while parsing \(fileURL)
          \(locationAndDiagnostics.joined(separator: "\n"))
          """)
        }
      }())
    }
  }
}

Allow skipping the self parse test by settinging an environment variable

import XCTest
import SwiftSyntax
import SwiftParser

public class ParserTests: XCTestCase {
  func testSelfParse() throws {
    // Allow skipping the self parse test in local development environments
    // because it takes very long compared to all the other tests.
    try XCTSkipIf(ProcessInfo.processInfo.environment["SKIP_SELF_PARSE"] == "1")
    let currentDir = URL(fileURLWithPath: #file)
      .deletingLastPathComponent()
      .deletingLastPathComponent()
      .deletingLastPathComponent()
      .appendingPathComponent("Sources")
    let fileURLs = FileManager.default
      .enumerator(at: currentDir, includingPropertiesForKeys: nil)!
      .compactMap({ $0 as? URL })
      .filter({$0.pathExtension == "swift"})
    for fileURL in fileURLs {
      XCTAssertNoThrow(try {
        let fileContents = try String(contentsOf: fileURL)
        let parsed = try Parser.parse(source: fileContents)
        AssertStringsEqualWithDiff("\(parsed)", fileContents)
        let diagnostics = ParseDiagnosticsGenerator.diagnostics(for: parsed)
        if !diagnostics.isEmpty {
          var locationAndDiagnostics: [String] = []
          let locationConverter = SourceLocationConverter(file: fileURL.lastPathComponent, tree: parsed)
          for diag in diagnostics {
            let location = diag.location(converter: locationConverter)
            let message = diag.message
            locationAndDiagnostics.append("\(location): \(message)")
          }
          XCTFail("""
          Received the following diagnostics while parsing \(fileURL)
          \(locationAndDiagnostics.joined(separator: "\n"))
          """)
        }
      }())
    }
  }
}


import Foundation

extension MCreateMapStatusExpanded
{
    //MARK: internal

    static func factoryMenuItems() -> [MCreateMapMenuProtocol]
    {
        let itemContract:MCreateMapMenuContract = MCreateMapMenuContract()
        let itemUser:MCreateMapMenuUser = MCreateMapMenuUser()
        let itemStop:MCreateMapMenuStop = MCreateMapMenuStop()
        let itemDone:MCreateMapMenuDone = MCreateMapMenuDone()

        let items:[MCreateMapMenuProtocol] = [
            itemContract,
            itemUser,
            itemStop,
            itemDone]

        return items
    }
}

Add search to expanded factory

import Foundation

extension MCreateMapStatusExpanded
{
    //MARK: internal

    static func factoryMenuItems() -> [MCreateMapMenuProtocol]
    {
        let itemContract:MCreateMapMenuContract = MCreateMapMenuContract()
        let itemUser:MCreateMapMenuUser = MCreateMapMenuUser()
        let itemStop:MCreateMapMenuStop = MCreateMapMenuStop()
        let itemSearch:MCreateMapMenuSearch = MCreateMapMenuSearch()
        let itemDone:MCreateMapMenuDone = MCreateMapMenuDone()

        let items:[MCreateMapMenuProtocol] = [
            itemContract,
            itemUser,
            itemStop,
            itemSearch,
            itemDone]

        return items
    }
}


public class AsyncClosuresOperation : AsyncOperation {

    public typealias AsyncClosureIdentifier = Int
    public typealias AsyncClosure = (op: AsyncClosuresOperation, closureIdentifier: AsyncClosureIdentifier) -> Void

    private var closures = Dictionary<AsyncClosureIdentifier, AsyncClosure>()
    private var currentClosureIdentifier = 0
    private var numberOfClosures = 0
    public var closureQueue = dispatch_get_main_queue() // must be a serial queue!

    public func addAsyncClosure(asyncClosure: AsyncClosure) {
        dispatch_async(closureQueue) {
            let key = self.closures.count
            self.closures.updateValue(asyncClosure, forKey: key)
        }
    }

    public func markClosureWithIdentifierFinished(closureIdentifier: AsyncClosureIdentifier) {
        performClosureWithIdentifier(closureIdentifier + 1)
    }

    override public func main() {
        performClosureWithIdentifier(0)
    }

    override public func handleCancellation() {
        // empty implementation
    }

    private func performClosureWithIdentifier(closureIdentifier: AsyncClosureIdentifier) {

        dispatch_async(closureQueue) {
            if (!self.finished) {
                if let closure = self.closures[closureIdentifier] {
                    self.closures.removeValueForKey(closureIdentifier)
                    closure(op: self, closureIdentifier: closureIdentifier)
                } else {
                    self.finish()
                }
            }
        }

    }

}

Put interface items on top; make closure queue a computed property that can only be set once. (Will make this a property based on an enum.)

public class AsyncClosuresOperation : AsyncOperation {

    public typealias AsyncClosureIdentifier = Int
    public typealias AsyncClosure = (op: AsyncClosuresOperation, closureIdentifier: AsyncClosureIdentifier) -> Void

    public func markClosureWithIdentifierFinished(closureIdentifier: AsyncClosureIdentifier) {
        performClosureWithIdentifier(closureIdentifier + 1)
    }

    public func addAsyncClosure(asyncClosure: AsyncClosure) {
        dispatch_async(closureQueue) {
            let key = self.closures.count
            self.closures.updateValue(asyncClosure, forKey: key)
        }
    }

    public var closureQueue: dispatch_queue_t {
        get {
            if let _ = _closureQueue {
                return _closureQueue!
            } else {
                return dispatch_get_main_queue()
            }
        }
        set {
            if let _ = _closureQueue {
                println("Cannot reassign closure queue")
            } else {
                _closureQueue = newValue
            }
        }
    }

    private var closures = Dictionary<AsyncClosureIdentifier, AsyncClosure>()
    private var currentClosureIdentifier = 0
    private var numberOfClosures = 0

    private var _closureQueue: dispatch_queue_t? = nil

    override public func main() {
        performClosureWithIdentifier(0)
    }

    private func performClosureWithIdentifier(closureIdentifier: AsyncClosureIdentifier) {

        dispatch_async(closureQueue) {
            if (!self.finished) {
                if let closure = self.closures[closureIdentifier] {
                    self.closures.removeValueForKey(closureIdentifier)
                    closure(op: self, closureIdentifier: closureIdentifier)
                } else {
                    self.finish()
                }
            }
        }

    }

}


//
//  DynamicSettingCategoryViewController.swift
//  Ello
//
//  Created by Tony DiPasquale on 4/13/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import UIKit

class DynamicSettingCategoryViewController: UITableViewController, DynamicSettingCellDelegate {
    var category: DynamicSettingCategory?
    var currentUser: User?

    override func viewDidLoad() {
        super.viewDidLoad()

        title = category?.label
        setupTableView()
    }

    private func setupTableView() {
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 50
        tableView.registerNib(UINib(nibName: "DynamicSettingCell", bundle: .None), forCellReuseIdentifier: "DynamicSettingCell")
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return category?.settings.count ?? 0
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("DynamicSettingCell", forIndexPath: indexPath) as! DynamicSettingCell
        let setting = category?.settings[indexPath.row]
        setting.map { DynamicSettingCellPresenter.configure(cell, setting: $0) }
        cell.setting = setting
        cell.delegate = self
        return cell
    }

    func toggleSetting(setting: DynamicSetting) {

    }
}

Move delegate conformance into extension

//
//  DynamicSettingCategoryViewController.swift
//  Ello
//
//  Created by Tony DiPasquale on 4/13/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import UIKit

class DynamicSettingCategoryViewController: UITableViewController {
    var category: DynamicSettingCategory?
    var currentUser: User?

    override func viewDidLoad() {
        super.viewDidLoad()

        title = category?.label
        setupTableView()
    }

    private func setupTableView() {
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 50
        tableView.registerNib(UINib(nibName: "DynamicSettingCell", bundle: .None), forCellReuseIdentifier: "DynamicSettingCell")
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return category?.settings.count ?? 0
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("DynamicSettingCell", forIndexPath: indexPath) as! DynamicSettingCell
        let setting = category?.settings[indexPath.row]
        setting.map { DynamicSettingCellPresenter.configure(cell, setting: $0) }
        cell.setting = setting
        cell.delegate = self
        return cell
    }
}

extension DynamicSettingCategoryViewController: DynamicSettingCellDelegate {
    func toggleSetting(setting: DynamicSetting) { }
}


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

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

// 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>(j)
  return p[0]
}

Update the test for UnsafePointer API change

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

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

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


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

import XCTest
@testable import Artikolo

class DataManagerTests: XCTestCase {

    let dataManager = DataManager(backend: ArrayBackend())

    override func setUp() {
        super.setUp()

        try! dataManager.reset()
        // 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 testURLCanBeSaved() {
        let url = URL(string: "http://zeldathon.net/")!
        dataManager.save(url: url)

        XCTAssertEqual(dataManager.urls, [url])
    }

}

class ArrayBackend: DataManagerBackend {

    var urls: [URL] = []

    func save(url: URL) {
        urls += [url]
    }

    func reset() {
        urls = []
    }

}

Fix tests to be reactive based.

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

import XCTest
@testable import Artikolo
import RxSwift

class DataManagerTests: XCTestCase {

    let dataManager = DataManager(backend: ArrayBackend())
    var disposeBag: DisposeBag!

    override func setUp() {
        super.setUp()
        disposeBag = DisposeBag()

        try! dataManager.reset()
        // 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 testURLCanBeSaved() {
        let url = URL(string: "http://zeldathon.net/")!
        var urls: [URL] = []

        dataManager.urls.subscribe(onNext: {
            urls = $0
        })
        .addDisposableTo(disposeBag)

        dataManager.save(url: url)

        XCTAssertEqual(urls, [url])
    }

}

class ArrayBackend: DataManagerBackend {

    private let urlsVariable = Variable<[URL]>([])
    let urls: Observable<[URL]>

    init() {
        urls = urlsVariable.asObservable()
    }

    func save(url: URL) {
        var mutableUrls = urlsVariable.value
        mutableUrls.append(url)
        urlsVariable.value = mutableUrls
    }

    func reset() {
        urlsVariable.value = []
    }

}


//
//  ViewController.swift
//  SwitchDemo
//
//  Created by Thanh Pham on 8/31/16.
//  Copyright © 2016 TPM. All rights reserved.
//

import UIKit
import Switch

class ViewController: UIViewController {

    @IBOutlet var statusLabel: UILabel!
    @IBOutlet var sectionHeaderLabel: UILabel!
    var mySwitch: Switch!

    override func viewDidLoad() {
        super.viewDidLoad()
        mySwitch = Switch()
        mySwitch.leftText = "Windows"
        mySwitch.rightText = "Mac"
        mySwitch.rightSelected = true
        mySwitch.tintColor = UIColor.purpleColor()
        mySwitch.disabledColor = mySwitch.tintColor.colorWithAlphaComponent(0.2)
        mySwitch.sizeToFit()
        mySwitch.addTarget(self, action: #selector(ViewController.switchDidChangeValue(_:)), forControlEvents: .ValueChanged)
        view.addSubview(mySwitch)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        mySwitch.frame = CGRectApplyAffineTransform(sectionHeaderLabel.frame, CGAffineTransformMakeTranslation(0, sectionHeaderLabel.frame.size.height + 15))
    }

    @IBAction func switchDidChangeValue(theSwitch: Switch) {
        statusLabel.text = "\"\(theSwitch.rightSelected ? theSwitch.rightText ?? "" : theSwitch.leftText ?? "")\" selected"
    }
}

Fix - pod try not work

//
//  ViewController.swift
//  SwitchDemo
//
//  Created by Thanh Pham on 8/31/16.
//  Copyright © 2016 TPM. All rights reserved.
//

import UIKit
import RoundedSwitch

class ViewController: UIViewController {

    @IBOutlet var statusLabel: UILabel!
    @IBOutlet var sectionHeaderLabel: UILabel!
    var mySwitch: Switch!

    override func viewDidLoad() {
        super.viewDidLoad()
        mySwitch = Switch()
        mySwitch.leftText = "Windows"
        mySwitch.rightText = "Mac"
        mySwitch.rightSelected = true
        mySwitch.tintColor = UIColor.purpleColor()
        mySwitch.disabledColor = mySwitch.tintColor.colorWithAlphaComponent(0.2)
        mySwitch.sizeToFit()
        mySwitch.addTarget(self, action: #selector(ViewController.switchDidChangeValue(_:)), forControlEvents: .ValueChanged)
        view.addSubview(mySwitch)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        mySwitch.frame = CGRectApplyAffineTransform(sectionHeaderLabel.frame, CGAffineTransformMakeTranslation(0, sectionHeaderLabel.frame.size.height + 15))
    }

    @IBAction func switchDidChangeValue(theSwitch: Switch) {
        statusLabel.text = "\"\(theSwitch.rightSelected ? theSwitch.rightText ?? "" : theSwitch.leftText ?? "")\" selected"
    }
}


#include <builtins.swift>
#include <io.swift>
#include <files.swift>
#include <sys.swift>

//usage: stc 563-glob.swift -S=/home/zzhang/*.swift
main
{
  string s[];
  s = glob(argv("S"));
  foreach f in s
  {
    printf("file: %s", f);
  }
}

Change glob to return files

#include <builtins.swift>
#include <io.swift>
#include <files.swift>
#include <sys.swift>

//usage: stc 563-glob.swift -S=/home/zzhang/*.swift
main
{
  file s[];
  s = glob(argv("S"));
  foreach f in s
  {
    printf("file: %s", filename(f));
  }
}


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

import Foundation

import XCTest

@testable import zosconnectforswift

class Api: XCTestCase {

  let zosConnect = ZosConnect(hostName: "http://zosconnectmock.mybluemix.net", port: 80)

  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 testGetApiDoc() {
    zosConnect.getApi("healthApi") { (api) in
      api?.getApiDoc("swagger") { (swagger) in
        XCTAssertNotNil(swagger)
      }
    }
  }

}

Add test for undefined documentation type

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

import Foundation

import XCTest

@testable import zosconnectforswift

class Api: XCTestCase {

  let zosConnect = ZosConnect(hostName: "http://zosconnectmock.mybluemix.net", port: 80)

  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 testGetApiDoc() {
    zosConnect.getApi("healthApi") { (api) in
      api?.getApiDoc("swagger") { (swagger) in
        XCTAssertNotNil(swagger)
      }
    }
  }

  func testGetUnknownApiDoc() {
    zosConnect.getApi("healthApi") { (api) in
      api?.getApiDoc("raml", callback: { (doc) in
        XCTAssertNil(doc)
      })
    }
  }

}


/// Represents a HTTP Header, Key and Value
public typealias Header = (String, String)

/// Represents a HTTP request or response body
public protocol PayloadType {
  /// Returns the next byte in the payload
  mutating func next() -> UInt8?
}

/// Represents a HTTP Request
public protocol RequestType {
  var method:String { get }
  var path:String { get }
  var headers:[Header] { get }
  var body: PayloadType? { get }
}

/// Represents a HTTP Response
public protocol ResponseType {
  var statusLine:String { get }
  var headers:[Header] { get }
  var body: PayloadType? { get }
}

public typealias Application = RequestType -> ResponseType

Make bodies get and set

/// Represents a HTTP Header, Key and Value
public typealias Header = (String, String)

/// Represents a HTTP request or response body
public protocol PayloadType {
  /// Returns the next byte in the payload
  mutating func next() -> UInt8?
}

/// Represents a HTTP Request
public protocol RequestType {
  var method:String { get }
  var path:String { get }
  var headers:[Header] { get }
  var body: PayloadType? { get set }
}

/// Represents a HTTP Response
public protocol ResponseType {
  var statusLine:String { get }
  var headers:[Header] { get }
  var body: PayloadType? { get set }
}

public typealias Application = RequestType -> ResponseType


import Node
import HTTP

extension Request {
    /// form url encoded encoded request data
    public var formURLEncoded: Node? {
        get {
            if let existing = storage["form-urlencoded"] as? Node {
                return existing
            } else if let type = headers["Content-Type"], type.contains("application/x-www-form-urlencoded") {
                guard case let .data(body) = body else { return nil }
                let formURLEncoded = Node(formURLEncoded: body)
                storage["form-urlencoded"] = formURLEncoded
                return formURLEncoded
            } else {
                return nil
            }
        }

        set(data) {
            if let data = data, let bytes = try? data.formURLEncoded() {
                body = .data(bytes)
                headers["Content-Type"] = "application/x-www-form-urlencoded"
            }

            storage["form-urlencoded"] = data
        }
    }
}

extension Request {
    /// Query data from the URI path
    public var query: Node? {
        get {
            if let existing = storage["query"] {
                return existing as? Node
            } else if let queryRaw = uri.query {
                let query = Node(formURLEncoded: queryRaw.bytes)
                storage["query"] = query
                return query
            } else {
                return nil
            }
        }
        set(data) {
            if let data = data {
                do {
                    uri.query = try data.formURLEncoded().string
                    storage["query"] = data
                } catch {
                    // make no changes
                }
            } else {
                uri.query = nil
            }
        }
    }
}

Move formURLEncoded body extension from Request to HTTP.Message

import Node
import HTTP

extension Message {
    /// form url encoded encoded request data
    public var formURLEncoded: Node? {
        get {
            if let existing = storage["form-urlencoded"] as? Node {
                return existing
            } else if let type = headers["Content-Type"], type.contains("application/x-www-form-urlencoded") {
                guard case let .data(body) = body else { return nil }
                let formURLEncoded = Node(formURLEncoded: body)
                storage["form-urlencoded"] = formURLEncoded
                return formURLEncoded
            } else {
                return nil
            }
        }

        set(data) {
            if let data = data, let bytes = try? data.formURLEncoded() {
                body = .data(bytes)
                headers["Content-Type"] = "application/x-www-form-urlencoded"
            }

            storage["form-urlencoded"] = data
        }
    }
}

extension Request {
    /// Query data from the URI path
    public var query: Node? {
        get {
            if let existing = storage["query"] {
                return existing as? Node
            } else if let queryRaw = uri.query {
                let query = Node(formURLEncoded: queryRaw.bytes)
                storage["query"] = query
                return query
            } else {
                return nil
            }
        }
        set(data) {
            if let data = data {
                do {
                    uri.query = try data.formURLEncoded().string
                    storage["query"] = data
                } catch {
                    // make no changes
                }
            } else {
                uri.query = nil
            }
        }
    }
}


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

extension Module {
	public static var churchBoolean: Module {
		let Boolean = Declaration("Boolean",
			type: .Type,
			value: Recur.lambda(.Type) { Recur.lambda($0, $0, const($0)) })

		let `true` = Declaration("true",
			type: Boolean.ref,
			value: Recur.lambda(.Type) { A in Recur.lambda(A, A, { a, _ in a }) })

		return Module([ Boolean, `true` ])
	}
}

import Prelude

Add a Church-encoded `false` value.

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

extension Module {
	public static var churchBoolean: Module {
		let Boolean = Declaration("Boolean",
			type: .Type,
			value: Recur.lambda(.Type) { Recur.lambda($0, $0, const($0)) })

		let `true` = Declaration("true",
			type: Boolean.ref,
			value: Recur.lambda(.Type) { A in Recur.lambda(A, A, { a, _ in a }) })

		let `false` = Declaration("false",
			type: Boolean.ref,
			value: Recur.lambda(.Type) { A in Recur.lambda(A, A, { _, b in b }) })

		return Module([ Boolean, `true`, `false` ])
	}
}

import Prelude


//
//  MusicSelector.swift
//  BreakBaloon
//
//  Created by Emil on 26/06/2016.
//  Copyright © 2016 Snowy_1803. All rights reserved.
//

import Foundation
import MediaPlayer
import SpriteKit

class MusicSelector: Selector {
    init(gvc: GameViewController) {
        super.init(gvc: gvc, title: NSLocalizedString("settings.music", comment: "Music"), value: gvc.currentMusicInt)
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func didSetSelectorValue() {
        gvc.currentMusicInt = value
        UserDefaults.standard.set(gvc.currentMusicFileName, forKey: "currentMusic")
        super.didSetSelectorValue()
        gvc.reloadBackgroundMusic()
    }

    override var maxValue: Int {
        GameViewController.getMusicURLs().count - 1
    }

    override var text: String {
        let cmps = GameViewController.getMusicURLs()[value].absoluteString.components(separatedBy: "/")
        let text = cmps[cmps.count - 1].components(separatedBy: ".")[0].removingPercentEncoding!
        return text == "Race" ? NSLocalizedString("theme.default.name", comment: "Default theme name") : text
    }
}

Fix crash if Race failed downloading

//
//  MusicSelector.swift
//  BreakBaloon
//
//  Created by Emil on 26/06/2016.
//  Copyright © 2016 Snowy_1803. All rights reserved.
//

import Foundation
import MediaPlayer
import SpriteKit

class MusicSelector: Selector {
    init(gvc: GameViewController) {
        super.init(gvc: gvc, title: NSLocalizedString("settings.music", comment: "Music"), value: gvc.currentMusicInt)
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func didSetSelectorValue() {
        gvc.currentMusicInt = value
        UserDefaults.standard.set(gvc.currentMusicFileName, forKey: "currentMusic")
        super.didSetSelectorValue()
        gvc.reloadBackgroundMusic()
    }

    override var maxValue: Int {
        GameViewController.getMusicURLs().count - 1
    }

    override var text: String {
        let urls = GameViewController.getMusicURLs()
        guard urls.indices.contains(value) else {
            return NSLocalizedString("error", comment: "Error")
        }
        let cmps = urls[value].absoluteString.components(separatedBy: "/")
        let text = cmps[cmps.count - 1].components(separatedBy: ".")[0].removingPercentEncoding!
        return text == "Race" ? NSLocalizedString("theme.default.name", comment: "Default theme name") : text
    }
}


//
//  Messages.swift
//  CoordinatorExample
//
//  Created by Aleksandar Vacić on 4.3.17..
//  Copyright © 2017. Radiant Tap. All rights reserved.
//

import Foundation
import Coordinator

extension Coordinable {

	func greet(_ p: Person) {
		print(String(describing: self))

		coordinatingResponder?.greet(p)
	}

	func find(_ p: Place) {
		print(String(describing: self))

		coordinatingResponder?.find(p)
	}

	func go(_ d: Direction) {
		print(String(describing: self))

		coordinatingResponder?.go(d)
	}
}

Print out the message path

//
//  Messages.swift
//  CoordinatorExample
//
//  Created by Aleksandar Vacić on 4.3.17..
//  Copyright © 2017. Radiant Tap. All rights reserved.
//

import Foundation
import Coordinator

extension Coordinable {

	func greet(_ p: Person) {
		print("\n\( String(describing: self) )")

		coordinatingResponder?.greet(p)
	}

	func find(_ p: Place) {
		print("\n\( String(describing: self) )")

		coordinatingResponder?.find(p)
	}

	func go(_ d: Direction) {
		print("\n\( String(describing: self) )")

		coordinatingResponder?.go(d)
	}
}


//
//  TextFieldTests.swift
//  PhoneNumberKitTests
//
//  Created by Travis Kaufman on 10/4/19.
//  Copyright © 2019 Roy Marmelstein. All rights reserved.
//

@testable import PhoneNumberKit
import UIKit
import XCTest

class TextFieldTests: XCTestCase {
    func testWorksWithPhoneNumberKitInstance() {
        let pnk = PhoneNumberKit()
        let tf = PhoneNumberTextField(withPhoneNumberKit: pnk)
        tf.text = "4125551212"
        XCTAssertEqual(tf.text, "(412) 555-1212")
    }

    func testWorksWithFrameAndPhoneNumberKitInstance() {
        let pnk = PhoneNumberKit()
        let frame = CGRect(x: 10.0, y: 20.0, width: 400.0, height: 250.0)
        let tf = PhoneNumberTextField(frame: frame, phoneNumberKit: pnk)
        XCTAssertEqual(tf.frame, frame)
        tf.text = "4125551212"
        XCTAssertEqual(tf.text, "(412) 555-1212")
    }
}

Fix Swift Package Manager build issue for test

//
//  TextFieldTests.swift
//  PhoneNumberKitTests
//
//  Created by Travis Kaufman on 10/4/19.
//  Copyright © 2019 Roy Marmelstein. All rights reserved.
//

#if canImport(UIKit)

@testable import PhoneNumberKit
import UIKit
import XCTest

class TextFieldTests: XCTestCase {
    func testWorksWithPhoneNumberKitInstance() {
        let pnk = PhoneNumberKit()
        let tf = PhoneNumberTextField(withPhoneNumberKit: pnk)
        tf.text = "4125551212"
        XCTAssertEqual(tf.text, "(412) 555-1212")
    }

    func testWorksWithFrameAndPhoneNumberKitInstance() {
        let pnk = PhoneNumberKit()
        let frame = CGRect(x: 10.0, y: 20.0, width: 400.0, height: 250.0)
        let tf = PhoneNumberTextField(frame: frame, phoneNumberKit: pnk)
        XCTAssertEqual(tf.frame, frame)
        tf.text = "4125551212"
        XCTAssertEqual(tf.text, "(412) 555-1212")
    }
}

#endif


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

/// Ignores any parse trees produced by `parser`.
public func ignore<C: CollectionType, T>(parser: Parser<C, T>.Function) -> Parser<C, ()>.Function {
	return parser --> const(())
}

/// Ignores any parse trees produced by a parser which parses `string`.
public func ignore(string: String) -> Parser<String, ()>.Function {
	return ignore(%string)
}

// MARK: - Imports

import Prelude

Add a public typealias for ignored input.

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

/// The type of trees to drop from the input.
public typealias Ignore = ()

/// Ignores any parse trees produced by `parser`.
public func ignore<C: CollectionType, T>(parser: Parser<C, T>.Function) -> Parser<C, ()>.Function {
	return parser --> const(())
}

/// Ignores any parse trees produced by a parser which parses `string`.
public func ignore(string: String) -> Parser<String, ()>.Function {
	return ignore(%string)
}

// MARK: - Imports

import Prelude


//
//  SensorTimestampGlucoseEvent.swift
//  RileyLink
//
//  Created by Timothy Mecklem on 10/16/16.
//  Copyright © 2016 Pete Schwamb. All rights reserved.
//

import Foundation

public struct SensorTimestampGlucoseEvent: GlucoseEvent {
    public let length: Int
    public let rawData: Data
    public let timestamp: DateComponents
    private let timestampType: String

    public init?(availableData: Data, relativeTimestamp: DateComponents) {
        length = 5

        guard length <= availableData.count else {
            return nil
        }

        func d(_ idx:Int) -> Int {
            return Int(availableData[idx] as UInt8)
        }

        rawData = availableData.subdata(in: 0..<length)
        timestamp = DateComponents(glucoseEventBytes: availableData.subdata(in: 1..<5))

        switch (d(3) >> 5 & 0b00000011) {
        case 0x00:
            timestampType = "last_rf"
        case 0x01:
            timestampType = "page_end"
        case 0x02:
            timestampType = "gap"
        default:
            timestampType = "unknown"
        }

    }

    public var dictionaryRepresentation: [String: Any] {
        return [
            "name": "SensorTimestamp",
            "timestampType": timestampType
        ]
    }
}

Move timestampType into an enum

//
//  SensorTimestampGlucoseEvent.swift
//  RileyLink
//
//  Created by Timothy Mecklem on 10/16/16.
//  Copyright © 2016 Pete Schwamb. All rights reserved.
//

import Foundation

public enum SensorTimestampType: String {
    case lastRf
    case pageEnd
    case gap
    case unknown

    public static func eventType(code: UInt8) -> SensorTimestampType {
        switch code {
        case 0x00:
            return .lastRf
        case 0x01:
            return .pageEnd
        case 0x02:
            return .gap
        default:
            return .unknown
        }
    }

}

public struct SensorTimestampGlucoseEvent: GlucoseEvent {
    public let length: Int
    public let rawData: Data
    public let timestamp: DateComponents
    public let timestampType: SensorTimestampType

    public init?(availableData: Data, relativeTimestamp: DateComponents) {
        length = 5

        guard length <= availableData.count else {
            return nil
        }

        func d(_ idx:Int) -> Int {
            return Int(availableData[idx] as UInt8)
        }

        rawData = availableData.subdata(in: 0..<length)
        timestamp = DateComponents(glucoseEventBytes: availableData.subdata(in: 1..<5))
        timestampType = SensorTimestampType.eventType(code: UInt8(d(3) >> 5) & 0b00000011)

    }

    public var dictionaryRepresentation: [String: Any] {
        return [
            "name": "SensorTimestamp",
            "timestampType": timestampType
        ]
    }
}


import PackageDescription

let package = Package(
    name: "AdminPanelProvider",
    dependencies: [
        // Vapor
        .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 2),
        .Package(url: "https://github.com/vapor/leaf-provider.git", majorVersion: 1),
        .Package(url: "https://github.com/vapor/mysql-provider.git", majorVersion: 2),
        .Package(url: "https://github.com/vapor/auth-provider.git", majorVersion: 1),

        // Nodes
        .Package(url: "https://github.com/nodes-vapor/flash.git", majorVersion: 1),
        .Package(url: "https://github.com/nodes-vapor/slugify.git", majorVersion: 1),
        .Package(url: "https://github.com/nodes-vapor/storage.git", majorVersion: 0, minor: 4),
        .Package(url: "https://github.com/nodes-vapor/paginator.git", majorVersion: 2, minor: 0),
        .Package(url: "https://github.com/nodes-vapor/audit-provider.git", majorVersion: 0, minor: 1),
    ]
)

Remove mysql as a dependency

import PackageDescription

let package = Package(
    name: "AdminPanelProvider",
    dependencies: [
        // Vapor
        .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 2),
        .Package(url: "https://github.com/vapor/leaf-provider.git", majorVersion: 1),
        .Package(url: "https://github.com/vapor/auth-provider.git", majorVersion: 1),

        // Nodes
        .Package(url: "https://github.com/nodes-vapor/flash.git", majorVersion: 1),
        .Package(url: "https://github.com/nodes-vapor/slugify.git", majorVersion: 1),
        .Package(url: "https://github.com/nodes-vapor/storage.git", majorVersion: 0, minor: 4),
        .Package(url: "https://github.com/nodes-vapor/paginator.git", majorVersion: 2, minor: 0),
        .Package(url: "https://github.com/nodes-vapor/audit-provider.git", majorVersion: 0, minor: 1),
    ]
)


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

import PackageDescription

let package = Package(
    name: "Sugar",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "Sugar",
            targets: ["Sugar"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(url: "https://github.com/vapor/auth.git", from: "2.0.0-rc"),
        .package(url: "https://github.com/vapor/fluent.git", from: "3.0.0-rc"),
        .package(url: "https://github.com/vapor/vapor.git", from: "3.0.0-rc"),
        .package(url: "https://github.com/vapor/jwt.git", from: "3.0.0-rc"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "Sugar",
            dependencies: ["Authentication", "Fluent", "Vapor", "JWT"]),
        .testTarget(
            name: "SugarTests",
            dependencies: ["Sugar"]),
    ]
)

Remove JWT - not needed

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

import PackageDescription

let package = Package(
    name: "Sugar",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "Sugar",
            targets: ["Sugar"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(url: "https://github.com/vapor/auth.git", from: "2.0.0-rc"),
        .package(url: "https://github.com/vapor/fluent.git", from: "3.0.0-rc"),
        .package(url: "https://github.com/vapor/vapor.git", from: "3.0.0-rc"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "Sugar",
            dependencies: ["Authentication", "Fluent", "Vapor"]),
        .testTarget(
            name: "SugarTests",
            dependencies: ["Sugar"]),
    ]
)


import PackageDescription

let package = Package(
    name: "GObject",
    dependencies: [
        .Package(url: "https://github.com/rhx/CGLib.git", majorVersion: 1),
        .Package(url: "https://github.com/rhx/SwiftGLib.git", majorVersion: 2)
    ]
)

Remove redundant include of CGLib

import PackageDescription

let package = Package(
    name: "GObject",
    dependencies: [
        .Package(url: "https://github.com/rhx/SwiftGLib.git", majorVersion: 2)
    ]
)


import PackageDescription

let package = Package(
    name: "VaporAPNS",
    dependencies: [
        .Package(url: "https://github.com/vapor/json.git", majorVersion: 1, minor: 0),
        .Package(url: "https://github.com/vapor/clibressl.git", majorVersion: 1),
        .Package(url: "https://github.com/iamjono/SwiftString.git", majorVersion: 1, minor: 0),
        .Package(url: "https://github.com/boostcode/CCurl.git", majorVersion: 0, minor: 2)
    ]
)

Switch to my version of SwiftString so it'll build on Travis

import PackageDescription

let package = Package(
    name: "VaporAPNS",
    dependencies: [
        .Package(url: "https://github.com/vapor/json.git", majorVersion: 1, minor: 0),
        .Package(url: "https://github.com/vapor/clibressl.git", majorVersion: 1),
        .Package(url: "https://github.com/matthijs2704/SwiftString.git", majorVersion: 1, minor: 0),
        .Package(url: "https://github.com/boostcode/CCurl.git", majorVersion: 0, minor: 2)
    ]
)


//
//  Loggable.swift
//  Loggable
//
//  Created by Michael Fourre on 2/4/17.
//

public protocol Loggable {

}

public extension Loggable {
    fileprivate static func position(file: String, function: String, line: Int) -> String {
        let path = file.components(separatedBy: "/")
        if let file = path[path.count - 1]?.replacingOccurrences(of: ".swift", with: "") {
            return "<\(file):\(line)>"
        }
        return ""
    }

    fileprivate static func logFirst(_ type: String, file: String, function: String, line: Int, strArr: [String]?) {
        print("Log.\(type)\(position(file: file, function: function, line: line)): \(strArr?.first ?? "Could not parse string")")
    }

    fileprivate static func logRemaining(_ strArr: [String]?) {
        guard let count = strArr?.count , count > 1 else { return }
        for newLine in 1..<count {
            if let line = strArr?[newLine] {
                print(line)
            }
        }
    }

    public static func log(type: String, string: String?, file: String, function: String, line: Int) {
        let strArr = string?.components(separatedBy: "\n")
        self.logFirst(type, file: file, function: function, line: line, strArr: strArr)
        self.logRemaining(strArr)
    }
}

Remove nil chain on array subscript which is no longer optional

//
//  Loggable.swift
//  Loggable
//
//  Created by Michael Fourre on 2/4/17.
//

public protocol Loggable {

}

public extension Loggable {
    fileprivate static func position(file: String, function: String, line: Int) -> String {
        let path = file.components(separatedBy: "/")
        if let file = path[path.count - 1].replacingOccurrences(of: ".swift", with: "") {
            return "<\(file):\(line)>"
        }
        return ""
    }

    fileprivate static func logFirst(_ type: String, file: String, function: String, line: Int, strArr: [String]?) {
        print("Log.\(type)\(position(file: file, function: function, line: line)): \(strArr?.first ?? "Could not parse string")")
    }

    fileprivate static func logRemaining(_ strArr: [String]?) {
        guard let count = strArr?.count , count > 1 else { return }
        for newLine in 1..<count {
            if let line = strArr?[newLine] {
                print(line)
            }
        }
    }

    public static func log(type: String, string: String?, file: String, function: String, line: Int) {
        let strArr = string?.components(separatedBy: "\n")
        self.logFirst(type, file: file, function: function, line: line, strArr: strArr)
        self.logRemaining(strArr)
    }
}


//
//  NotificationCenterExtensions.swift
//  KTSwiftExtensions
//
//  Created by Kyle Thomas on 6/27/16.
//  Copyright © 2016 Kyle Thomas. All rights reserved.
//

import Foundation

public extension NotificationCenter {

    func postNotificationName(_ aName: String) {
        post(name: Notification.Name(rawValue: aName), object: nil)
    }

    func addObserver(_ observer: AnyObject, selector: Selector, name: String?) {
        addObserver(observer, selector: selector, name: name.map { NSNotification.Name(rawValue: $0) }, object: nil)
    }

    func addObserverForName(_ name: String?, queue: OperationQueue? = nil, usingBlock block: @escaping (Notification!) -> Void) {
        self.addObserver(forName: name.map { NSNotification.Name(rawValue: $0) }, object: nil, queue: queue, using: block)
    }
}

Add new notification center convenience methods so that the older ones can eventually be retired

//
//  NotificationCenterExtensions.swift
//  KTSwiftExtensions
//
//  Created by Kyle Thomas on 6/27/16.
//  Copyright © 2016 Kyle Thomas. All rights reserved.
//

import Foundation

public extension NotificationCenter {

    func postNotificationName(_ aName: String) {
        post(name: Notification.Name(rawValue: aName), object: nil)
    }

    func addObserver(_ observer: AnyObject, selector: Selector, name: String?) {
        addObserver(observer, selector: selector, name: name.map { NSNotification.Name(rawValue: $0) }, object: nil)
    }

    func addObserverForName(_ name: String?, queue: OperationQueue? = nil, usingBlock block: @escaping (Notification!) -> Void) {
        self.addObserver(forName: name.map { NSNotification.Name(rawValue: $0) }, object: nil, queue: queue, using: block)
    }

    class func post(name: Notification.Name, object: Any? = nil) {
        NotificationCenter.default.post(name: name, object: object)
    }

    class func addObserver(forName name: NSNotification.Name?, object: Any? = nil, queue: OperationQueue? = nil, using block: @escaping (Notification) -> Void) {
        NotificationCenter.default.addObserver(forName: name, object: object, queue: queue, using: block)
    }

    class func addObserver(observer: Any, selector: Selector, name: NSNotification.Name?, object: Any? = nil) {
        NotificationCenter.default.addObserver(observer, selector: selector, name: name, object: object)
    }
}


//
//  Loggable.swift
//  Loggable
//
//  Created by Michael Fourre on 2/4/17.
//

public protocol Loggable {

}

public extension Loggable {
    fileprivate static func position(file: String, function: String, line: Int) -> String {
        let path = file.components(separatedBy: "/")
        if let file = path[safe: path.count - 1]?.replacingOccurrences(of: ".swift", with: "") {
            return "<\(file):\(line)>"
        }
        return ""
    }

    fileprivate static func logFirst(_ type: String, file: String, function: String, line: Int, strArr: [String]?) {
        print("Log.\(type)\(position(file: file, function: function, line: line)): \(strArr?.first ?? "Could not parse string")")
    }

    fileprivate static func logRemaining(_ strArr: [String]?) {
        guard let count = strArr?.count , count > 1 else { return }
        for newLine in 1..<count {
            if let line = strArr?[safe: newLine] {
                print(line)
            }
        }
    }

    public static func log(type: String, string: String?, file: String, function: String, line: Int) {
        let strArr = string?.components(separatedBy: "\n")
        self.logFirst(type, file: file, function: function, line: line, strArr: strArr)
        self.logRemaining(strArr)
    }
}

Remove dependency on subscript extension for Array types

//
//  Loggable.swift
//  Loggable
//
//  Created by Michael Fourre on 2/4/17.
//

public protocol Loggable {

}

public extension Loggable {
    fileprivate static func position(file: String, function: String, line: Int) -> String {
        let path = file.components(separatedBy: "/")
        if let file = path[path.count - 1]?.replacingOccurrences(of: ".swift", with: "") {
            return "<\(file):\(line)>"
        }
        return ""
    }

    fileprivate static func logFirst(_ type: String, file: String, function: String, line: Int, strArr: [String]?) {
        print("Log.\(type)\(position(file: file, function: function, line: line)): \(strArr?.first ?? "Could not parse string")")
    }

    fileprivate static func logRemaining(_ strArr: [String]?) {
        guard let count = strArr?.count , count > 1 else { return }
        for newLine in 1..<count {
            if let line = strArr?[newLine] {
                print(line)
            }
        }
    }

    public static func log(type: String, string: String?, file: String, function: String, line: Int) {
        let strArr = string?.components(separatedBy: "\n")
        self.logFirst(type, file: file, function: function, line: line, strArr: strArr)
        self.logRemaining(strArr)
    }
}


// SKIP-THIS-TEST
// Check wrapping and recursive wait for struct with nested arrays and structs
type person {
  string name;
  int age;
}

type megastruct {
  person people[];
  person person;
}

type uberstruct {
  person person;
  megastruct mega;
}

(string o) fmt(megastruct s) "turbine" "0" [
  "set <<o>> <<s>>"
];

(string o) fmt2(uberstruct s) "turbine" "0" [
  "set <<o>> <<s>>"
];

import assert;

main {
  megastruct s;
  s.person.name = "Bob";
  s.person.age = 100;

  person t;
  t.name = "X";
  t.age = 1;
  s.people[0] = t;
  s.people[1] = s.person;
  s.people[2] = t;

  trace("test1",fmt(s));

  uberstruct s2;
  s2.mega.person = s.person;
  s2.mega.people = s.people;
  s2.person.name = "Jane";
  s2.person.age = 101;

  trace("test2",fmt2(s2));
}

Test for recursive store of struct

// SKIP-THIS-TEST
// Check returning structs with nested arrays
type person {
  string name;
  int age;
}

type megastruct {
  person people[];
  person person;
}

type uberstruct {
  person person;
  megastruct mega;
}

(megastruct o) fmt(person person, person ppl[]) "turbine" "0" [
  "set <<o>> [ dict create person <<person>> people <<ppl>>]"
];

(uberstruct o) fmt2(person person, person ppl[]) "turbine" "0" [
  "set <<o>> [ dict create mega [ dict create person <<person>> people <<ppl>> ] person <<person>> ]"
];

import assert;

main {
  person p1, p2;
  p1.name = "Bob";
  p1.age = 100;
  p2.name = "Jane";
  p2.age = 101;

  person ppl[] = [p1, p2, p1];

  assertEqual(fmt(p1, ppl).person.name, "Bob", "a");
  assertEqual(fmt(p1, ppl).person.age, 100, "b");
  assertEqual(fmt(p1, ppl).people[0].name, "Bob", "c");
  assertEqual(fmt(p1, ppl).people[1].name, "Jane", "d");

  assertEqual(fmt2(p1, ppl).person.name, "Bob", "e");
  assertEqual(fmt2(p1, ppl).person.age, 100, "f");

  assertEqual(fmt2(p1, ppl).mega.people[0], "Bob", "g");
  assertEqual(fmt2(p1, ppl).mega.people[1], "Jane", "h");

}


public struct SwitchCaseAlignmentConfiguration: RuleConfiguration, Equatable {
    private(set) var severityConfiguration = SeverityConfiguration(.warning)
    private(set) var indentedCases = false

    init() {}

    public var consoleDescription: String {
        return severityConfiguration.consoleDescription + ", indented_cases: \(indentedCases)"
    }

    public mutating func apply(configuration: Any) throws {
        guard let configuration = configuration as? [String: Any] else {
            throw ConfigurationError.unknownConfiguration
        }

        self.indentedCases = configuration["indented_cases"] as? Bool ?? false
    }

    public static func == (lhs: SwitchCaseAlignmentConfiguration,
                           rhs: SwitchCaseAlignmentConfiguration) -> Bool {
        return lhs.indentedCases == rhs.indentedCases &&
               lhs.severityConfiguration == rhs.severityConfiguration
    }
}

Apply correct severity form configuration

public struct SwitchCaseAlignmentConfiguration: RuleConfiguration, Equatable {
    private(set) var severityConfiguration = SeverityConfiguration(.warning)
    private(set) var indentedCases = false

    init() {}

    public var consoleDescription: String {
        return severityConfiguration.consoleDescription + ", indented_cases: \(indentedCases)"
    }

    public mutating func apply(configuration: Any) throws {
        guard let configuration = configuration as? [String: Any] else {
            throw ConfigurationError.unknownConfiguration
        }

        indentedCases = configuration["indented_cases"] as? Bool ?? false

        if let severityString = configuration["severity"] as? String {
            try severityConfiguration.apply(configuration: severityString)
        }
    }

    public static func == (lhs: SwitchCaseAlignmentConfiguration,
                           rhs: SwitchCaseAlignmentConfiguration) -> Bool {
        return lhs.indentedCases == rhs.indentedCases &&
               lhs.severityConfiguration == rhs.severityConfiguration
    }
}


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

final class DescriptionTests: XCTestCase {
	func testOneEmptyBranchProducesUnitType() {
		let UnitDescription: Description = [
			"unit": .End,
		]

		assert(UnitDescription.out, ==, .UnitType)
	}

	func testTwoEmptyBranchesProduceBooleanType() {
		let BooleanDescription: Description = [
			"true": .End,
			"false": .End,
		]

		assert(Term(term: BooleanDescription).out, ==, Expression.lambda(.BooleanType) { .If($0, .UnitType, .UnitType) })
	}
}

import Assertions
@testable import Manifold
import XCTest

Test the construction of a Natural Description.

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

final class DescriptionTests: XCTestCase {
	func testOneEmptyBranchProducesUnitType() {
		let UnitDescription: Description = [
			"unit": .End,
		]

		assert(UnitDescription.out, ==, .UnitType)
	}

	func testTwoEmptyBranchesProduceBooleanType() {
		let BooleanDescription: Description = [
			"true": .End,
			"false": .End,
		]

		assert(Term(term: BooleanDescription).out, ==, Expression.lambda(.BooleanType) { .If($0, .UnitType, .UnitType) })
	}

	func testCaseConstruction() {
		let NaturalDescription: Description = [
			"zero": .End,
			"successor": .Argument(.Recursive(.End), id),
		]

		assert(NaturalDescription, ==, Description.Argument(.BooleanType) { .If($0, .UnitType, .Argument(.Recursive(.End), id)) })
	}
}

import Assertions
@testable import Manifold
import XCTest


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


import HTTP
import Turnstile

public final class Helper {
    public let request: Request
    public init(request: Request) {
        self.request = request
    }

    public var header: Authorization? {
        guard let authorization = request.headers["Authorization"] else {
            return nil
        }

        return Authorization(header: authorization)
    }

    public func login(_ credentials: Credentials, persist: Bool = true) throws {
        return try request.subject().login(credentials: credentials, persist: persist)
    }

    public func logout() throws {
        return try request.subject().logout()
    }

    public func user() throws -> User {
        let subject = try request.subject()

        guard let details = subject.authDetails else {
            throw AuthError.notAuthenticated
        }

        guard let user = details.account as? User else {
            throw AuthError.invalidAccountType
        }

        return user
    }
}

extension Request {
    public var auth: Helper {
        let key = "auth"

        guard let helper = storage[key] as? Helper else {
            let helper = Helper(request: self)
            storage[key] = helper
            return helper
        }

        return helper
    }
}

Make request a weak reference in Auth Header Helper to avoid retain cycle and memory leak.

import HTTP
import Turnstile

public final class Helper {
    public weak var request: Request?
    public init(request: Request) {
        self.request = request
    }

    public var header: Authorization? {
        guard let authorization = request?.headers["Authorization"] else {
            return nil
        }

        return Authorization(header: authorization)
    }

    public func login(_ credentials: Credentials, persist: Bool = true) throws {
        try request?.subject().login(credentials: credentials, persist: persist)
    }

    public func logout() throws {
        try request?.subject().logout()
    }

    public func user() throws -> User {
        let subject = try request?.subject()

        guard let details = subject?.authDetails else {
            throw AuthError.notAuthenticated
        }

        guard let user = details.account as? User else {
            throw AuthError.invalidAccountType
        }

        return user
    }
}

extension Request {
    public var auth: Helper {
        let key = "auth"

        guard let helper = storage[key] as? Helper else {
            let helper = Helper(request: self)
            storage[key] = helper
            return helper
        }

        return helper
    }
}


import Foundation

final class MSettings:Model<ArchSettings>
{
    private(set) var items:[MSettingsProtocol]
    private var database:Database?

    required init()
    {
        items = []

        super.init()
    }

    //MARK: private

    private func loadSettings(
        settings:DSettings,
        database:Database)
    {
        items = MSettings.factoryItems(
            settings:settings,
            database:database)

        view?.settingsLoaded()
    }

    //MARK: internal

    func loadSettings()
    {
        guard

            let database:Database = Database(bundle:nil)

        else
        {
            return
        }

        self.database = database

        database.fetch
        { [weak self] (settingsList:[DSettings]) in

            guard

                let settings:DSettings = settingsList.first

            else
            {
                return
            }

            self?.loadSettings(
                settings:settings,
                database:database)
        }
    }
}

Add strong reference to settings

import Foundation

final class MSettings:Model<ArchSettings>
{
    private(set) var items:[MSettingsProtocol]
    private var database:Database?
    private var settings:DSettings?

    required init()
    {
        items = []

        super.init()
    }

    //MARK: private

    private func loadSettings(
        settings:DSettings,
        database:Database)
    {
        self.settings = settings
        items = MSettings.factoryItems(
            settings:settings,
            database:database)

        view?.settingsLoaded()
    }

    //MARK: internal

    func loadSettings()
    {
        guard

            let database:Database = Database(bundle:nil)

        else
        {
            return
        }

        self.database = database

        database.fetch
        { [weak self] (settingsList:[DSettings]) in

            guard

                let settings:DSettings = settingsList.first

            else
            {
                return
            }

            self?.loadSettings(
                settings:settings,
                database:database)
        }
    }
}


//
//  TypeUtils.swift
//  Pods
//
//  Created by José Manuel Sánchez Peñarroja on 7/6/16.
//
//

import Foundation

public struct TypeUtils {
	public static func name(thing: Any) -> String {
		let result = String(thing.self)
		return result.componentsSeparatedByString(".").last ?? result
	}
}

Revert last commit. That change wasn't necessary

//
//  TypeUtils.swift
//  Pods
//
//  Created by José Manuel Sánchez Peñarroja on 7/6/16.
//
//

import Foundation

public struct TypeUtils {
	public static func name(thing: Any) -> String {
		return String(thing.self)
	}
}


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

final class ReductionTests: XCTestCase {
	let reduction = %"x" --> { $0.uppercaseString }

	func testMapsParseTreesWithAFunction() {
		assertTree(reduction, "x", ==, "X")
	}

	func testRejectsInputRejectedByItsParser() {
		assertUnmatched(reduction, "y")
	}
}

// MARK: - Imports

import Madness
import XCTest

Test reduction with source location.

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

final class ReductionTests: XCTestCase {
	let reduction = %"x" --> { $0.uppercaseString }

	func testMapsParseTreesWithAFunction() {
		assertTree(reduction, "x", ==, "X")
	}

	func testRejectsInputRejectedByItsParser() {
		assertUnmatched(reduction, "y")
	}

	let reductionWithIndex = %"x" --> { $2.uppercaseString + String(distance($0.startIndex, $1)) }

	func testMapsParseTreesWithAFunctionWhichTakesTheSourceIndex() {
		assertTree(reductionWithIndex, "x", ==, "X1")
	}
}

// MARK: - Imports

import Madness
import XCTest


import WebKit

extension WebViewController: NeemanUIDelegate {

    @IBAction open func unwindToParentWebView(_ segue: UIStoryboardSegue) {
        dismiss(animated: true, completion: nil)
    }

    /**
     Load a request in the popup web view.

     - parameter request: The request to load in the popup.
     */
    @objc open func loadPopupRequest(_ request: NSMutableURLRequest) {
        _ = webViewPopup?.load(request as URLRequest)
    }

    /**
     The done button of the popup view controller was pressed.

     - parameter sender: The button that was tapped.
     */
    @objc open func didTapDoneButton(_ sender: AnyObject) {
        closeWebView(webView)
    }

    /**
     Close the popup webview.

     - parameter webView: The web view to close.
     */
    @objc open func closeWebView(_ webView: WKWebView) {
        if let popupWebView = webViewPopup {
            webViewObserver.stopObservingWebView(popupWebView)
            dismiss(animated: true, completion: nil)
            webViewPopup = nil
            popupNavController = nil
        }
    }

    /**
     Presents the alert controller in the windows root view controller.

     - parameter alert: The alert controller to present.
     */
    open func presentAlertController(_ alert: UIAlertController) {
        present(alert, animated: true, completion: nil)
    }
}

Make sure the view controller is dismissed if it is a popup or not.

import WebKit

extension WebViewController: NeemanUIDelegate {

    @IBAction open func unwindToParentWebView(_ segue: UIStoryboardSegue) {
        dismiss(animated: true, completion: nil)
    }

    /**
     Load a request in the popup web view.

     - parameter request: The request to load in the popup.
     */
    @objc open func loadPopupRequest(_ request: NSMutableURLRequest) {
        _ = webViewPopup?.load(request as URLRequest)
    }

    /**
     The done button of the popup view controller was pressed.

     - parameter sender: The button that was tapped.
     */
    @objc open func didTapDoneButton(_ sender: AnyObject) {
        closeWebView(webView)
    }

    /**
     Close the popup webview.

     - parameter webView: The web view to close.
     */
    @objc open func closeWebView(_ webView: WKWebView) {
        if let popupWebView = webViewPopup {
            webViewObserver.stopObservingWebView(popupWebView)
            webViewPopup = nil
            popupNavController = nil
        }
        dismiss(animated: true, completion: nil)
    }

    /**
     Presents the alert controller in the windows root view controller.

     - parameter alert: The alert controller to present.
     */
    open func presentAlertController(_ alert: UIAlertController) {
        present(alert, animated: true, completion: nil)
    }
}


public final class Synchronized<Wrapped> {
	private var _lock: Lock
	private var _value: Wrapped

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

	public var value: Wrapped {
		get { return _lock.sync { _value } }
		set { _lock.sync { _value = newValue } }
	}

	public func atomicallyUpdate(_ update: (inout Wrapped) throws -> Void) rethrows {
		try _lock.sync({ try update(&_value) })
	}
}

Add option to allow concurrent reads

public final class Synchronized<Wrapped> {
	private var _lock: Lock
	private var _value: Wrapped

	public init(_ value: Wrapped, allowConcurrentReads: Bool = true) {
		self._value = value
		self._lock = allowConcurrentReads ? ReadWriteLock() : MutexLock()
	}

	private func readSync <T> (_ perform: () throws -> T) rethrows -> T {
		guard let concurrentLock = _lock as? ConcurrentLock else {
			return try _lock.sync(perform)
		}
		return try concurrentLock.concurrentSync(perform)
	}

	public var value: Wrapped {
		get { return readSync { _value } }
		set { _lock.sync { _value = newValue } }
	}

	public func atomicallyUpdate(_ update: (inout Wrapped) throws -> Void) rethrows {
		try _lock.sync({ try update(&_value) })
	}
}


// RUN: rm -rf %t/clang-module-cache
// RUN: %swift -module-cache-path %t/clang-module-cache -target x86_64-apple-macosx10.9 -sdk %S/../../SILGen/Inputs %s -I %S/../../SILGen/Inputs -enable-source-import -parse -verify

import Foundation
import gizmo

@objc class X {
  func foo() -> X { return self }
}

@NSManaged var global: Int // expected-error {{'NSManaged' attribute only allowed on a property in a class}}

@NSManaged     // expected-error {{'NSManaged' may only be used on 'var' declarations}}
func managedFunction() {}

class SwiftGizmo : Gizmo {
  @NSManaged var a: X
  @NSManaged var b: Int
  @NSManaged let c: Int  // expected-error {{'NSManaged' attribute not allowed on a 'let' property}}

  @NSManaged class var d: Int = 4  // expected-error {{'NSManaged' attribute only allowed on a property in a class}} \
            // expected-error {{class variables not yet supported}}

  @NSManaged var e: Int { return 4 } // expected-error {{'NSManaged' not allowed on computed properties}}

  @NSCopying @NSManaged var optionalProperty : NSString?  // expected-error {{'NSManaged' property cannot also be marked @NSCopying}}

  override init() {}
}

Rewrite @NSManaged test to use the regular mock SDK instead of SILGen's.

// RUN: rm -rf %t/clang-module-cache
// RUN: %swift -module-cache-path %t/clang-module-cache %clang-importer-sdk -parse %s -verify

import Foundation

@objc class X {
  func foo() -> X { return self }
}

@NSManaged var global: Int // expected-error {{'NSManaged' attribute only allowed on a property in a class}}

@NSManaged     // expected-error {{'NSManaged' may only be used on 'var' declarations}}
func managedFunction() {}

class SwiftGizmo : A {
  @NSManaged var a: X
  @NSManaged var b: Int
  @NSManaged let c: Int  // expected-error {{'NSManaged' attribute not allowed on a 'let' property}}

  @NSManaged class var d: Int = 4  // expected-error {{'NSManaged' attribute only allowed on a property in a class}} \
            // expected-error {{class variables not yet supported}}

  @NSManaged var e: Int { return 4 } // expected-error {{'NSManaged' not allowed on computed properties}}

  @NSCopying @NSManaged var optionalProperty : NSString?  // expected-error {{'NSManaged' property cannot also be marked @NSCopying}}

  override init() {}
}


//
//  StringExtensions.swift
//  lottie-swift
//
//  Created by Brandon Withrow on 1/25/19.
//

import Foundation
import CoreGraphics

extension String {

  func hexColorComponents() -> (red: CGFloat, green: CGFloat, blue: CGFloat) {

    var cString:String = trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
      cString.remove(at: cString.startIndex)
    }

    if ((cString.count) != 6) {
      return (red: 0, green: 0, blue: 0)
    }

    var rgbValue:UInt32 = 0
    Scanner(string: cString).scanHexInt32(&rgbValue)

    return (red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0)
  }
}

Use scanHexInt64 instead of the deprecated scanHexInt32 in iOS 13

//
//  StringExtensions.swift
//  lottie-swift
//
//  Created by Brandon Withrow on 1/25/19.
//

import Foundation
import CoreGraphics

extension String {

  func hexColorComponents() -> (red: CGFloat, green: CGFloat, blue: CGFloat) {

    var cString:String = trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
      cString.remove(at: cString.startIndex)
    }

    if ((cString.count) != 6) {
      return (red: 0, green: 0, blue: 0)
    }

    var rgbValue:UInt64 = 0
    Scanner(string: cString).scanHexInt64(&rgbValue)

    return (red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0)
  }
}


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

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

	func testZeroTypechecksAsNatural() {
		assert(zero.checkType("Natural", environment, context), ==, "Natural")
		assert(zero.inferType(environment, context), ==, "Natural")
	}

	func testSuccessorOfZeroTypechecksAsNatural() {
		assert(successor[zero].inferType(environment, context), ==, "Natural")
	}
}

private let module = Module<Term>.natural
private let environment = module.environment
private let context = module.context

private let successor: Term = "successor"
private let zero: Term = "zero"

import Assertions
import Manifold
import XCTest

Add a private global for `Natural`.

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

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

	func testZeroTypechecksAsNatural() {
		assert(zero.checkType("Natural", environment, context), ==, "Natural")
		assert(zero.inferType(environment, context), ==, "Natural")
	}

	func testSuccessorOfZeroTypechecksAsNatural() {
		assert(successor[zero].inferType(environment, context), ==, "Natural")
	}
}

private let module = Module<Term>.natural
private let environment = module.environment
private let context = module.context

private let Natural: Term = "Natural"
private let successor: Term = "successor"
private let zero: Term = "zero"

import Assertions
import Manifold
import XCTest


//
//  CoreDataStackTVTests.swift
//  CoreDataStackTVTests
//
//  Created by Robert Edwards on 12/17/15.
//  Copyright © 2015 Big Nerd Ranch. All rights reserved.
//

import XCTest

@testable import CoreDataStack

class CoreDataStackTVTests: TempDirectoryTestCase {

    var inMemoryStack: CoreDataStack!
    var sqlStack: CoreDataStack!

    override func setUp() {
        super.setUp()

        let modelName = "Sample"

        do {
            inMemoryStack = try CoreDataStack.constructInMemoryStack(withModelName: modelName, inBundle: unitTestBundle)
        } catch {
            failingOn(error)
        }

        guard let tempStoreURL = tempStoreURL else {
            XCTFail("Temp Dir not created")
            return
        }

        weak var ex1 = expectationWithDescription("SQLite Setup")
        CoreDataStack.constructSQLiteStack(withModelName: modelName, inBundle: unitTestBundle, withStoreURL: tempStoreURL) { result in
            switch result {
            case .success(let stack):
                self.sqlStack = stack
            case .failure(let error):
                self.failingOn(error)
            }
            ex1?.fulfill()
        }
        waitForExpectationsWithTimeout(10, handler: nil)
    }

    func testInMemoryInitialization() {
        XCTAssertNotNil(inMemoryStack)
    }

    func testSQLiteInitialization() {
        XCTAssertNotNil(sqlStack)
    }
}

Update swift syntax for tvOS scheme

//
//  CoreDataStackTVTests.swift
//  CoreDataStackTVTests
//
//  Created by Robert Edwards on 12/17/15.
//  Copyright © 2015 Big Nerd Ranch. All rights reserved.
//

import XCTest

@testable import CoreDataStack

class CoreDataStackTVTests: TempDirectoryTestCase {

    var inMemoryStack: CoreDataStack!
    var sqlStack: CoreDataStack!

    override func setUp() {
        super.setUp()

        let modelName = "Sample"

        do {
            inMemoryStack = try CoreDataStack.constructInMemoryStack(modelName: modelName, in: unitTestBundle)
        } catch {
            failingOn(error)
        }

        guard let tempStoreURL = tempStoreURL else {
            XCTFail("Temp Dir not created")
            return
        }

        weak var ex1 = expectation(description: "SQLite Setup")
        CoreDataStack.constructSQLiteStack(modelName: modelName, in: unitTestBundle, at: tempStoreURL) { result in
            switch result {
            case .success(let stack):
                self.sqlStack = stack
            case .failure(let error):
                self.failingOn(error)
            }
            ex1?.fulfill()
        }
        waitForExpectations(timeout: 10, handler: nil)
    }

    func testInMemoryInitialization() {
        XCTAssertNotNil(inMemoryStack)
    }

    func testSQLiteInitialization() {
        XCTAssertNotNil(sqlStack)
    }
}


//
//  AppDelegate.swift
//  TrainTrippin
//
//  Created by Maciek on 18.10.2016.
//  Copyright © 2016 Fortunity. All rights reserved.
//

import UIKit

class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        return true
    }
}

Fix problem with going straight to DetailsViewController on iPhone

//
//  AppDelegate.swift
//  TrainTrippin
//
//  Created by Maciek on 18.10.2016.
//  Copyright © 2016 Fortunity. All rights reserved.
//

import UIKit

class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let splitViewController = self.window!.rootViewController as! UISplitViewController
        splitViewController.delegate = self

        return true
    }

    func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
        guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
        guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
        if topAsDetailController.detailItem == nil {
            return true
        }
        return false
    }
}


//
//  ShuffleSwiftTests.swift
//  ShuffleSwiftTests
//
//  Created by Steve Baker on 12/28/15.
//  Copyright © 2015 Beepscore LLC. All rights reserved.
//

import XCTest
@testable import ShuffleSwift

class ShuffleSwiftTests: XCTestCase {

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

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

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

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

}

Delete testPerformanceExample and in testExample add XCTAssertEqual. Test passes, but Xcode navigator and gutter don't display green diamonds.

//
//  ShuffleSwiftTests.swift
//  ShuffleSwiftTests
//
//  Created by Steve Baker on 12/28/15.
//  Copyright © 2015 Beepscore LLC. All rights reserved.
//

import XCTest
@testable import ShuffleSwift

class ShuffleSwiftTests: 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.
        XCTAssertEqual(1, 1)
    }

}


import Foundation

open class Label: Codable {
    open var url: URL?
    open var name: String?
    open var color: String?
}

Create method to get a single label from a repo

import Foundation
import RequestKit

open class Label: Codable {
    open var url: URL?
    open var name: String?
    open var color: String?
}

// MARK: request

public extension Octokit {
    /**
     Fetches a single label in a repository
     - parameter session: RequestKitURLSession, defaults to URLSession.sharedSession()
     - parameter owner: The user or organization that owns the repository.
     - parameter repository: The name of the repository.
     - parameter name: The name of the label.
     - parameter completion: Callback for the outcome of the fetch.
    */
    @discardableResult
    func label(_ session: RequestKitURLSession = URLSession.shared, owner: String, repository: String, name: String, completion: @escaping (_ response: Response<Label>) -> Void) -> URLSessionDataTaskProtocol? {
        let router = LabelRouter.readLabel(configuration, owner, repository, name)
        return router.load(session, dateDecodingStrategy: .formatted(Time.rfc3339DateFormatter), expectedResultType: Label.self) { label, error in
            if let error = error {
                completion(Response.failure(error))
            } else {
                if let label = label {
                    completion(Response.success(label))
                }
            }
        }
    }
}

enum LabelRouter: JSONPostRouter {
    case readLabel(Configuration, String, String, String)
    var method: HTTPMethod {
        switch self {
        default:
            return .GET
        }
    }

    var encoding: HTTPEncoding {
        switch self {
        default:
            return .url
        }
    }

    var configuration: Configuration {
        switch self {
        case .readLabel(let config, _, _, _): return config
        }
    }

    var params: [String : Any] {
        switch self {
        case .readLabel: return [:]
        }
    }

    var path: String {
        switch self {
        case .readLabel(_, let owner, let repository, let name):
            let name = name.stringByAddingPercentEncodingForRFC3986() ?? name
            return "/repos/\(owner)/\(repository)/labels/\(name)"
        }
    }
}


import Foundation

/// The protocol used to define the specifications necessary for a `MoyaProvider`.
public protocol TargetType {

    /// The target's base `URL`.
    var baseURL: URL { get }

    /// The path to be appended to `baseURL` to form the full `URL`.
    var path: String { get }

    /// The HTTP method used in the request.
    var method: Moya.Method { get }

    /// Provides stub data for use in testing.
    var sampleData: Data { get }

    /// The type of HTTP task to be performed.
    var task: Task { get }

    /// Whether or not to perform Alamofire validation. Defaults to `false`.
    var validate: Bool { get }

    // The headers to be used in the request.
    var headers: [String: String]? { get }
}

public extension TargetType {
    var validate: Bool {
        return false
    }
}

Fix typo: // to ///

import Foundation

/// The protocol used to define the specifications necessary for a `MoyaProvider`.
public protocol TargetType {

    /// The target's base `URL`.
    var baseURL: URL { get }

    /// The path to be appended to `baseURL` to form the full `URL`.
    var path: String { get }

    /// The HTTP method used in the request.
    var method: Moya.Method { get }

    /// Provides stub data for use in testing.
    var sampleData: Data { get }

    /// The type of HTTP task to be performed.
    var task: Task { get }

    /// Whether or not to perform Alamofire validation. Defaults to `false`.
    var validate: Bool { get }

    /// The headers to be used in the request.
    var headers: [String: String]? { get }
}

public extension TargetType {
    var validate: Bool {
        return false
    }
}


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

private var a = 1

func doSomething(b: Int) {
	a += strideof(b.dynamicType) //% self.expect("expr a", substrs=['Int', '= 1'])
}

doSomething(b:2)

Migrate from strideof(); this test does not need it

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

private var a = 1

func doSomething(b: Int) {
	a += b //% self.expect("expr a", substrs=['Int', '= 1'])
}

doSomething(b:2)


//
//  UINavigationBar+Colors.swift
//  RGUIExtension
//
//  Created by RAIN on 15/11/30.
//  Copyright © 2015年 Smartech. All rights reserved.
//

import UIKit

extension UINavigationBar {
    /**
     修改 Navigation Bar 的背景颜色

     - parameter color: 提供给 Navigation Bar 的背景的 tint color
     */
    static func barTintColor(color: UIColor) {
        UINavigationBar.appearance().barTintColor = color
    }

    /**
     修改 Navigation item 和 bar button item 的 tint color

     - parameter color: 提供给 Navigation item 和 bar button item 的 tint color
     */
    static func tintColor(color: UIColor) {
        UINavigationBar.appearance().tintColor = color
    }

    /**
     修改 Navigation Bar 的文字颜色

     - parameter color: 提供给 Navigation Bar 上文字的颜色
     */
    static func titleTextColor(color: UIColor) {
        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: color]
    }
}

Add a MARK to an extension of UINavigationBar

//
//  UINavigationBar+Colors.swift
//  RGUIExtension
//
//  Created by RAIN on 15/11/30.
//  Copyright © 2015年 Smartech. All rights reserved.
//

import UIKit

//  MARK: Colors
extension UINavigationBar {
    /**
     修改 Navigation Bar 的背景颜色

     - parameter color: 提供给 Navigation Bar 的背景的 tint color
     */
    static func barTintColor(color: UIColor) {
        UINavigationBar.appearance().barTintColor = color
    }

    /**
     修改 Navigation item 和 bar button item 的 tint color

     - parameter color: 提供给 Navigation item 和 bar button item 的 tint color
     */
    static func tintColor(color: UIColor) {
        UINavigationBar.appearance().tintColor = color
    }

    /**
     修改 Navigation Bar 的文字颜色

     - parameter color: 提供给 Navigation Bar 上文字的颜色
     */
    static func titleTextColor(color: UIColor) {
        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: color]
    }
}


import UIKit
import MovieKit
import MoviesUI
import PlaygroundSupport

let listVC = MovieListController()

PlaygroundPage.current.liveView = listVC

Add sample results to the MovieList playground

import UIKit
import MovieKit
import MoviesUI
import PlaygroundSupport

let listVC = MovieListController()
listVC.loadOneMorePage = { callback in
    callback(MovieListPage.template.results)
}

PlaygroundPage.current.liveView = listVC


// UNSUPPORTED: OS=windows-msvc
// static library is not well supported yet on Windows

// REQUIRES: lld_lto

// RUN: %empty-directory(%t)
// RUN: %target-swiftc_driver -emit-library -static -lto=llvm-full -emit-module %S/Inputs/lto/module1.swift -working-directory %t
// RUN: %target-swiftc_driver -lto=llvm-full %s -I%t -L%t -lmodule1 -module-name main -o %t/main
// RUN: %llvm-nm --defined-only %t/main | %FileCheck %s

// CHECK-NOT: _$s7module120unusedPublicFunctionyyF

import module1

Disable test that's failing in CI

// UNSUPPORTED: OS=windows-msvc
// static library is not well supported yet on Windows

// REQUIRES: lld_lto
// REQUIRES: rdar75301449

// RUN: %empty-directory(%t)
// RUN: %target-swiftc_driver -emit-library -static -lto=llvm-full -emit-module %S/Inputs/lto/module1.swift -working-directory %t
// RUN: %target-swiftc_driver -lto=llvm-full %s -I%t -L%t -lmodule1 -module-name main -o %t/main
// RUN: %llvm-nm --defined-only %t/main | %FileCheck %s

// CHECK-NOT: _$s7module120unusedPublicFunctionyyF

import module1


//
//  CurrencyField.swift
//  CurrencyField
//
//  Created by Aaren Tebbutt on 20/5/17.
//  Copyright © 2017 Noshjournal. All rights reserved.
//

import UIKit

public class CurrencyField: UITextField {

}

Set keyboard to "digitalPad" in the init

//
//  CurrencyField.swift
//  CurrencyField
//
//  Created by Aaren Tebbutt on 20/5/17.
//  Copyright © 2017 Noshjournal. All rights reserved.
//

import UIKit

public class CurrencyField: UITextField {

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        keyboardType = .decimalPad
    }

    override public init(frame: CGRect) {
        super.init(frame: frame)
        keyboardType = .decimalPad
    }

}


var sentence:String = "Is it able to extract integer from long sentence, like 'Please wait for three minutes yeah', and the result is five minutes walking"

var numDictionary = [
    "zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9,
    "ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16,
    "seventeen": 17, "eighteen": 18, "nineteen": 19, "twenty": 20
]

func extractTimeFromSentence(inout str:String) -> (Int) {
    var numInt: Int?
    let splitedSentenceArray: [String] = str.componentsSeparatedByString(" ")
    for tuple in splitedSentenceArray.enumerate() {
        if ((tuple.element == "minute") || (tuple.element == "minutes")) {
            print("\(tuple.index)")
            let indexNum = tuple.index-1
            let numStr = splitedSentenceArray[indexNum]
            numInt = numDictionary[numStr]
        }
    }
    return numInt!
}

let num = extractTimeFromSentence(&sentence)
print(num)

Fix extract time from sentence func

var sentence:String = "Is it able to extract integer from long sentence, like 'Please wait for three minutes yeah', and the result is five minutes walking"

var numDictionary = [
    "zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9,
    "ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16,
    "seventeen": 17, "eighteen": 18, "nineteen": 19, "twenty": 20
]

func extractTimeFromSentence(inout str:String) -> (Int) {
    var numInt: Int?
    let splitedSentenceArray: [String] = str.componentsSeparatedByString(" ")
    for tuple in splitedSentenceArray.enumerate() {
        if ((tuple.element == "minute") || (tuple.element == "minutes")) {
            let indexNum = tuple.index-1
            let numStr = splitedSentenceArray[indexNum]
            if Int(numStr) == nil {
                if (numDictionary[numStr] == nil) {
                    numInt = 0
                } else {
                    numInt = numDictionary[numStr]
                }
            } else {
                numInt = Int(numStr)
            }
        }
    }
    return numInt!
}

let num = extractTimeFromSentence(&sentence)
print(num)


/*
 MIT License

 Copyright (c) 2017 MessageKit

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 */

import Foundation
import MessageKit

struct MockMessage: MessageType {

    var messageId: String
    var sender: Sender
    var sentDate: Date
    var data: MessageData

    init(text: String, sender: Sender, messageId: String) {
        data = .text(text)
        self.sender = sender
        self.messageId = id
        self.sentDate = Date()
    }

}

Revert parameter renaming due to SwiftLint

/*
 MIT License

 Copyright (c) 2017 MessageKit

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 */

import Foundation
import MessageKit

struct MockMessage: MessageType {

    var messageId: String
    var sender: Sender
    var sentDate: Date
    var data: MessageData

    init(text: String, sender: Sender, id: String) {
        data = .text(text)
        self.sender = sender
        self.messageId = id
        self.sentDate = Date()
    }

}