// swift-tools-version:5.0
//===--- Package.swift ----------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//

import PackageDescription

let package = Package(

  name: "swift-numerics",
  products: [
    .library(name: "ComplexModule", targets: ["ComplexModule"]),
    .library(name: "Numerics", targets: ["Numerics"]),
    .library(name: "RealModule", targets: ["RealModule"]),
  ],

  targets: [
    // User-facing modules
    .target(name: "ComplexModule", dependencies: ["RealModule"]),
    .target(name: "Numerics", dependencies: ["ComplexModule", "RealModule"]),
    .target(name: "RealModule", dependencies: ["_NumericsShims"]),

    // Implementation details
    .target(name: "_NumericsShims", dependencies: []),
    .target(name: "_TestSupport", dependencies: ["Numerics"]),

    // Unit test bundles
    .testTarget(name: "ComplexTests", dependencies: ["_TestSupport"]),
    .testTarget(name: "RealTests", dependencies: ["_TestSupport"]),

    // Test executables
    .target(name: "ComplexLog", dependencies: ["Numerics", "_TestSupport"], path: "Tests/Executable/ComplexLog"),
    .target(name: "ComplexLog1p", dependencies: ["Numerics", "_TestSupport"], path: "Tests/Executable/ComplexLog1p")
  ]
)

Remove Real and Complex _libraries_; keep modules.

// swift-tools-version:5.0
//===--- Package.swift ----------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//

import PackageDescription

let package = Package(

  name: "swift-numerics",
  products: [
    .library(name: "Numerics", targets: ["Numerics"])
  ],

  targets: [
    // User-facing modules
    .target(name: "ComplexModule", dependencies: ["RealModule"]),
    .target(name: "Numerics", dependencies: ["ComplexModule", "RealModule"]),
    .target(name: "RealModule", dependencies: ["_NumericsShims"]),

    // Implementation details
    .target(name: "_NumericsShims", dependencies: []),
    .target(name: "_TestSupport", dependencies: ["Numerics"]),

    // Unit test bundles
    .testTarget(name: "ComplexTests", dependencies: ["_TestSupport"]),
    .testTarget(name: "RealTests", dependencies: ["_TestSupport"]),

    // Test executables
    .target(name: "ComplexLog", dependencies: ["Numerics", "_TestSupport"], path: "Tests/Executable/ComplexLog"),
    .target(name: "ComplexLog1p", dependencies: ["Numerics", "_TestSupport"], path: "Tests/Executable/ComplexLog1p")
  ]
)


// swift-tools-version:5.0

import PackageDescription

let package = Package(
    name: "PhoneNumberKit",
    products: [
        .library(name: "PhoneNumberKit", targets: ["PhoneNumberKit"])
    ],
    targets: [
        .target(name: "PhoneNumberKit", path: "PhoneNumberKit", exclude: ["UI"]),
        .testTarget(name: "PhoneNumberKitTests", dependencies: ["PhoneNumberKit"], path: "PhoneNumberKitTests")
    ]
)

Remove UI exclusion for SPM

// swift-tools-version:5.0

import PackageDescription

let package = Package(
    name: "PhoneNumberKit",
    products: [
        .library(name: "PhoneNumberKit", targets: ["PhoneNumberKit"])
    ],
    targets: [
        .target(name: "PhoneNumberKit", path: "PhoneNumberKit", exclude: []),
        .testTarget(name: "PhoneNumberKitTests", dependencies: ["PhoneNumberKit"], path: "PhoneNumberKitTests")
    ]
)


// Package.swift
// Copyright (c) 2017 Nicholas Maccharoli
//
// 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 PackageDescription

let package = Package(
    name: "UIDeviceComplete"
)

Update swift package to modern syntax

// swift-tools-version:5.0
//
// Package.swift
// Copyright (c) 2017 Nicholas Maccharoli
//
// 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 PackageDescription

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


// 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: "SwiftServerHttp",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "HTTP",
            targets: ["HTTP"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
        // ServerSecurity: common headers, definitions and protocols
        .package(url: "https://github.com/gtaban/security.git", from: "0.0.0"),
        // TLSService: implementation of ServerSecurity using OpenSSL and SecureTransport
        .package(url: "https://github.com/gtaban/TLSService.git", from: "0.20.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "CHTTPParser",
            dependencies: []),
        .target(
            name: "HTTP",
            dependencies: ["CHTTPParser", "ServerSecurity", "TLSService"]),
        .testTarget(
            name: "HTTPTests",
            dependencies: ["HTTP"]),
    ]
)

Update dependency on swift-server/TLSService instead of gtaban/TLSService.

// 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: "SwiftServerHttp",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "HTTP",
            targets: ["HTTP"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
        // ServerSecurity: common headers, definitions and protocols
        .package(url: "https://github.com/swift-server/security.git", from: "0.0.0"),
        // TLSService: implementation of ServerSecurity using OpenSSL and SecureTransport
        .package(url: "https://github.com/swift-server/TLSService.git", from: "0.20.3"),
    ],
    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: "CHTTPParser",
            dependencies: []),
        .target(
            name: "HTTP",
            dependencies: ["CHTTPParser", "ServerSecurity", "TLSService"]),
        .testTarget(
            name: "HTTPTests",
            dependencies: ["HTTP"]),
    ]
)


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

import PackageDescription

let package = Package(
    name: "RxBluetoothKit",
    products: [
        .library(name: "RxBluetoothKit", targets: ["RxBluetoothKit"])
    ],
    dependencies: [
        .package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMajor(from: "5.0.0"))
    ],
    targets: [
        .target(
                name: "RxBluetoothKit",
                dependencies: [
                    "RxSwift"
                ],
                path: ".",
                exclude: [
                    "Example",
                    "Tests"
                ],
                sources: [
                    "Source"
                ]
            )
    ]
)

Add supported platforms to SPM

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

import PackageDescription

let package = Package(
    name: "RxBluetoothKit",
    platforms: [
        .macOS(.v10_10), .iOS(.v8), .tvOS(.v11), .watchOS(.v4)
    ],
    products: [
        .library(name: "RxBluetoothKit", targets: ["RxBluetoothKit"])
    ],
    dependencies: [
        .package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMajor(from: "5.0.0"))
    ],
    targets: [
        .target(
                name: "RxBluetoothKit",
                dependencies: [
                    "RxSwift"
                ],
                path: ".",
                exclude: [
                    "Example",
                    "Tests"
                ],
                sources: [
                    "Source"
                ]
            )
    ]
)


// swift-tools-version:5.6

import PackageDescription

let package = Package(
    name: "GLib",
    products: [ .library(name: "GLib", targets: ["GLib"]) ],
    dependencies: [
        .package(url: "https://github.com/rhx/gir2swift.git", branch: "plugin")
    ],
    targets: [
        .systemLibrary(name: "CGLib", pkgConfig: "gio-unix-2.0",
            providers: [
                .brew(["glib", "glib-networking", "gobject-introspection"]),
                .apt(["libglib2.0-dev", "glib-networking", "gobject-introspection", "libgirepository1.0-dev"])
            ]),
        .target(
            name: "GLib",
            dependencies: [
                "CGLib",
                .product(name: "gir2swift", package: "gir2swift"),
            ],
            swiftSettings: [.unsafeFlags(["-Xfrontend", "-serialize-debugging-options"], .when(configuration: .debug))],
            plugins: [
                .plugin(name: "gir2swift-plugin", package: "gir2swift")
            ]
        ),
        .testTarget(name: "GLibTests", dependencies: ["GLib"]),
    ]
)

Switch to gir2swift development branch

// swift-tools-version:5.6

import PackageDescription

let package = Package(
    name: "GLib",
    products: [ .library(name: "GLib", targets: ["GLib"]) ],
    dependencies: [
        .package(url: "https://github.com/rhx/gir2swift.git", branch: "development")
    ],
    targets: [
        .systemLibrary(name: "CGLib", pkgConfig: "gio-unix-2.0",
            providers: [
                .brew(["glib", "glib-networking", "gobject-introspection"]),
                .apt(["libglib2.0-dev", "glib-networking", "gobject-introspection", "libgirepository1.0-dev"])
            ]),
        .target(
            name: "GLib",
            dependencies: [
                "CGLib",
                .product(name: "gir2swift", package: "gir2swift"),
            ],
            swiftSettings: [.unsafeFlags(["-Xfrontend", "-serialize-debugging-options"], .when(configuration: .debug))],
            plugins: [
                .plugin(name: "gir2swift-plugin", package: "gir2swift")
            ]
        ),
        .testTarget(name: "GLibTests", dependencies: ["GLib"]),
    ]
)


// swift-tools-version: 5.6

import PackageDescription

let package = Package(
    name: "Gong",
    platforms: [
        .iOS(.v9),
        .macOS(.v10_15),
        .tvOS(.v9)
    ],
    products: [
        .library(name: "Gong", targets: ["Gong"])
    ],
    targets: [
        .target(name: "Gong", dependencies: [])
    ]
)

Set environment constraint back to macOS 10.10

// swift-tools-version: 5.6

import PackageDescription

let package = Package(
    name: "Gong",
    platforms: [
        .iOS(.v9),
        .macOS(.v10_10),
        .tvOS(.v9)
    ],
    products: [
        .library(name: "Gong", targets: ["Gong"])
    ],
    targets: [
        .target(name: "Gong", dependencies: [])
    ]
)


//
//  SPOTPViewController.swift
//  SiriPay
//
//  Created by Jatin Arora on 10/09/16.
//  Copyright © 2016 PhonePe Internet Private Limited. All rights reserved.
//

import Foundation

class SPOTPViewController : UIViewController {

    @IBOutlet weak var nextButton: UIBarButtonItem!
    var otpString: String?

    @IBAction func nextButtonTapped(sender: AnyObject) {

        SPPaymentController.sharedInstance.doSignIn(otp: otpString!) { (error) in

            if error == nil {
                self.performSegueWithIdentifier("SiriPaySegueIdentifier", sender: nil)
            } else {
                print("Wrong OTP with error = \(error)")
            }

        }

    }
}

extension SPOTPViewController : UITextFieldDelegate {

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        if textField.text?.characters.count == 3 {
            nextButton.enabled = true
        }

        return true

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let otp = sender as! String
        otpString = otp
    }
}

Add alert controller for wrong OTP alert

//
//  SPOTPViewController.swift
//  SiriPay
//
//  Created by Jatin Arora on 10/09/16.
//  Copyright © 2016 PhonePe Internet Private Limited. All rights reserved.
//

import Foundation

class SPOTPViewController : UIViewController {

    @IBOutlet weak var nextButton: UIBarButtonItem!
    var otpString: String?

    @IBAction func nextButtonTapped(sender: AnyObject) {

        SPPaymentController.sharedInstance.doSignIn(otp: otpString!) { (error) in

            if error == nil {
                self.performSegueWithIdentifier("SiriPaySegueIdentifier", sender: nil)
            } else {
                print("Wrong OTP with error = \(error)")

                let alert = UIAlertController(title: "Wrong OTP", message:"Please try again", preferredStyle: UIAlertControllerStyle.Alert)

                let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Cancel, handler: nil)

                alert.addAction(okAction)
                self.presentViewController(alert, animated: true, completion: nil)
            }

        }

    }
}

extension SPOTPViewController : UITextFieldDelegate {

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        if textField.text?.characters.count == 3 {
            nextButton.enabled = true
        }

        return true

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let otp = sender as! String
        otpString = otp
    }
}


//
//  NSBundle+FileResource.swift
//  R.swift.Library
//
//  Created by Mathijs Kadijk on 10-01-16.
//  Copyright © 2016 Mathijs Kadijk. All rights reserved.
//

import Foundation

public extension NSBundle {
  /**
   Returns the file URL for the given resource (R.file.*).

   - parameter resource: The resource to get the file URL for (R.file.*).

   - returns: The file URL for the resource file (R.file.*) or nil if the file could not be located.
   */
  public func URLForResource(resource: FileResourceType) -> NSURL? {
    return URLForResource(resource.name, withExtension: resource.pathExtension, subdirectory: nil, localization: nil)
  }

  /**
   Returns the full pathname for the resource (R.file.*).

   - parameter resource: The resource file to get the path for (R.file.*).

   - returns: The full pathname for the resource file (R.file.*) or nil if the file could not be located.
   */
  public func pathForResource(resource: FileResourceType) -> String? {
    return pathForResource(resource.name, ofType: resource.pathExtension, inDirectory: nil, forLocalization: nil)
  }
}

Make URL-/pathForResource lookup global and local

//
//  NSBundle+FileResource.swift
//  R.swift.Library
//
//  Created by Mathijs Kadijk on 10-01-16.
//  Copyright © 2016 Mathijs Kadijk. All rights reserved.
//

import Foundation

public extension NSBundle {
  /**
   Returns the file URL for the given resource (R.file.*).

   - parameter resource: The resource to get the file URL for (R.file.*).

   - returns: The file URL for the resource file (R.file.*) or nil if the file could not be located.
   */
  public func URLForResource(resource: FileResourceType) -> NSURL? {
    return URLForResource(resource.name, withExtension: resource.pathExtension)
  }

  /**
   Returns the full pathname for the resource (R.file.*).

   - parameter resource: The resource file to get the path for (R.file.*).

   - returns: The full pathname for the resource file (R.file.*) or nil if the file could not be located.
   */
  public func pathForResource(resource: FileResourceType) -> String? {
    return pathForResource(resource.name, ofType: resource.pathExtension)
  }
}


//
//  QueueController.swift
//  AbstractPlayer
//
//  Created by 林達也 on 2016/09/28.
//  Copyright © 2016年 jp.sora0077. All rights reserved.
//

import Foundation
import AVKit
import AVFoundation
import RxSwift

public final class QueueController<Response> {

    private var workerQueue: WorkerQueue<Response>!

    private var queueCondition: Bool {
        return queueingCount <= bufferSize
    }

    private let bufferSize: Int

    private var queueingCount: Int = 0 {
        didSet {
            if queueCondition {
                workerQueue.run()
            }
        }
    }

    private let disposeBag = DisposeBag()

    public init(bufferSize: Int = 3, queueingCount: Observable<Int>, call: @escaping (Response) -> Void) {
        self.bufferSize = bufferSize

        workerQueue = WorkerQueue { [weak self] item in
            guard let item = item else { return true }
            call(item)
            return self?.queueCondition ?? true
        }

        queueingCount.distinctUntilChanged()
            .subscribe(onNext: { [weak self] count in
                self?.queueingCount = count
            })
            .addDisposableTo(disposeBag)
    }

    open func add<W: Worker>(_ worker: W, priority: Priority = .default) where W.Response == Response {
        workerQueue.add(worker, priority: priority)
    }
}

Replace open func to public func

//
//  QueueController.swift
//  AbstractPlayer
//
//  Created by 林達也 on 2016/09/28.
//  Copyright © 2016年 jp.sora0077. All rights reserved.
//

import Foundation
import AVKit
import AVFoundation
import RxSwift

public final class QueueController<Response> {

    private var workerQueue: WorkerQueue<Response>!

    private var queueCondition: Bool {
        return queueingCount <= bufferSize
    }

    private let bufferSize: Int

    private var queueingCount: Int = 0 {
        didSet {
            if queueCondition {
                workerQueue.run()
            }
        }
    }

    private let disposeBag = DisposeBag()

    public init(bufferSize: Int = 3, queueingCount: Observable<Int>, call: @escaping (Response) -> Void) {
        self.bufferSize = bufferSize

        workerQueue = WorkerQueue { [weak self] item in
            guard let item = item else { return true }
            call(item)
            return self?.queueCondition ?? true
        }

        queueingCount.distinctUntilChanged()
            .subscribe(onNext: { [weak self] count in
                self?.queueingCount = count
            })
            .addDisposableTo(disposeBag)
    }

    public func add<W: Worker>(_ worker: W, priority: Priority = .default) where W.Response == Response {
        workerQueue.add(worker, priority: priority)
    }
}


extension (Int, Int) {}

// RUN: %sourcekitd-test -req=sema %s -- -Xfrontend -enable-descriptive-diagnostics -Xfrontend -diagnostic-documentation-path -Xfrontend /educational/notes/path/prefix %s | %FileCheck %s -check-prefix=DESCRIPTIVE

// DESCRIPTIVE:      key.description: "non-nominal type
// DESCRIPTIVE:      key.educational_note_paths: [
// DESCRIPTIVE-NEXT:   "/educational/notes/path/prefix/nominal-types.md"
// DESCRIPTIVE-NEXT: ]

// RUN: %sourcekitd-test -req=sema %s -- %s | %FileCheck %s -check-prefix=DESCRIPTIVE-DISABLED

// DESCRIPTIVE-DISABLED:     key.description: "non-nominal type
// DESCRIPTIVE-DISABLED-NOT: key.educational_note_paths

Update test for Windows path

extension (Int, Int) {}

// RUN: %sourcekitd-test -req=sema %s -- -Xfrontend -enable-descriptive-diagnostics -Xfrontend -diagnostic-documentation-path -Xfrontend /educational/notes/path/prefix %s | %FileCheck %s -check-prefix=DESCRIPTIVE

// DESCRIPTIVE:      key.description: "non-nominal type
// DESCRIPTIVE:      key.educational_note_paths: [
// DESCRIPTIVE-NEXT:   "{{/|\\}}educational{{/|\\}}notes{{/|\\}}path{{/|\\}}prefix{{/|\\}}nominal-types.md"
// DESCRIPTIVE-NEXT: ]

// RUN: %sourcekitd-test -req=sema %s -- %s | %FileCheck %s -check-prefix=DESCRIPTIVE-DISABLED

// DESCRIPTIVE-DISABLED:     key.description: "non-nominal type
// DESCRIPTIVE-DISABLED-NOT: key.educational_note_paths


import Foundation

public struct DataManager {
  public var dataPath: String

  public
  init(dataPath: String = defaultDataPath) {
    self.dataPath = dataPath
  }

  public
  func read() throws -> Data {
    guard let data = FileManager.default.contents(atPath: dataPath)
    else { throw "Could not read file \(dataPath)" }
    return data
  }

  public
  func write(data: Data) throws {
    guard FileManager.default.createFile(atPath: dataPath, contents: data)
    else { throw "Could not write data (\(data)) to file \(dataPath)" }
  }
}

extension DataManager {
  fileprivate
  static var defaultDataPath: String {
    return FileManager.default.currentDirectoryPath + "/.todo"
  }
}

Remove default paths from DataManager

import Foundation

public struct DataManager {
  public var dataPath: String

  public func read() throws -> Data {
    guard let data = FileManager.default.contents(atPath: dataPath)
    else { throw "Could not read file \(dataPath)" }
    return data
  }

  public func write(data: Data) throws {
    guard FileManager.default.createFile(atPath: dataPath, contents: data)
    else { throw "Could not write data (\(data)) to file \(dataPath)" }
  }
}


import UIKit

class ControllerList:UIViewController
{
    let model:ModelList
    private weak var viewListBar:ViewListBar!

    init()
    {
        model = ModelList()

        super.init(nibName:nil, bundle:nil)

        let viewListBar:ViewListBar = ViewListBar()
        self.viewListBar = viewListBar
        navigationItem.titleView = viewListBar
    }

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

    override func loadView()
    {
        let view:ViewList = ViewList(controller:self)
        self.view = view
    }

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

Add items loaded to controller

import UIKit

class ControllerList:UIViewController
{
    let model:ModelList
    private weak var viewListBar:ViewListBar!

    init()
    {
        model = ModelList()

        super.init(nibName:nil, bundle:nil)

        let viewListBar:ViewListBar = ViewListBar()
        self.viewListBar = viewListBar
        navigationItem.titleView = viewListBar
    }

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

    override func loadView()
    {
        let view:ViewList = ViewList(controller:self)
        self.view = view
    }

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

    //MARK: private

    private func itemsLoaded()
    {
        viewListBar.isHidden = false

        guard

            let view:ViewList = self.view as? ViewList

        else
        {
            return
        }

        view.itemsLoaded()
    }
}


import Foundation

final class MCreateSaveBuilder
{
    weak var model:MCreateSave?
    var renders:[MCreateSaveRender]
    var urls:[URL]
    let directory:URL
    private(set) weak var timer:Timer?
    private let kTimeout:TimeInterval = 1

    init(renders:[MCreateSaveRender], directory:URL)
    {
        self.renders = renders
        self.directory = directory
        urls = []
    }

    deinit
    {
        timer?.invalidate()
    }

    //MARK: selectors

    @objc
    private func selectorTimeout(sender timer:Timer)
    {
        timer.invalidate()
        model?.buildingError()
    }

    //MARK: private

    private func asyncStartTimer()
    {
        let timer:Timer = Timer.scheduledTimer(
            timeInterval:kTimeout,
            target:self,
            selector:#selector(selectorTimeout(sender:)),
            userInfo:nil,
            repeats:false)

        self.timer = timer
    }

    //MARK: internal

    func startTimer()
    {
        timer?.invalidate()

        DispatchQueue.main.async
        { [weak self] in

            self?.asyncStartTimer()
        }
    }
}

Increase timeout to 9 seconds

import Foundation

final class MCreateSaveBuilder
{
    weak var model:MCreateSave?
    var renders:[MCreateSaveRender]
    var urls:[URL]
    let directory:URL
    private(set) weak var timer:Timer?
    private let kTimeout:TimeInterval = 9

    init(renders:[MCreateSaveRender], directory:URL)
    {
        self.renders = renders
        self.directory = directory
        urls = []
    }

    deinit
    {
        timer?.invalidate()
    }

    //MARK: selectors

    @objc
    private func selectorTimeout(sender timer:Timer)
    {
        timer.invalidate()
        model?.buildingError()
    }

    //MARK: private

    private func asyncStartTimer()
    {
        let timer:Timer = Timer.scheduledTimer(
            timeInterval:kTimeout,
            target:self,
            selector:#selector(selectorTimeout(sender:)),
            userInfo:nil,
            repeats:false)

        self.timer = timer
    }

    //MARK: internal

    func startTimer()
    {
        timer?.invalidate()

        DispatchQueue.main.async
        { [weak self] in

            self?.asyncStartTimer()
        }
    }
}


//
//  Errors.swift
//  ReactiveCocoa
//
//  Created by Justin Spahr-Summers on 2014-07-13.
//  Copyright (c) 2014 GitHub. All rights reserved.
//

import Foundation

/// The domain for all errors originating within the Swift components of
/// ReactiveCocoa.
///
/// For backwards compatibility reasons, the Objective-C components of
/// ReactiveCocoa use their own individual domains.
public let RACErrorDomain: NSString = "RACErrorDomain"

/// Possible error codes within `RACErrorDomain`.
public enum RACError: NSInteger {
	/// An error event occurred, but there was no `NSError` object.
	///
	/// This should only be used when bridging from Objective-C, or when
	/// invoking Objective-C APIs that may return a nil `NSError`.
	case Empty

	/// An attempt was made to execute an `Action` while it was disabled.
	case ActionNotEnabled

	/// Returns the `RACError` that corresponds to the code within the given
	/// `NSError`, or nil if the domain of the error is not `RACErrorDomain`.
	public static func fromError(error: NSError) -> RACError? {
		if error.domain == RACErrorDomain {
			return fromRaw(error.code)
		} else {
			return nil
		}
	}

	/// An `NSError` object corresponding to this error code.
	public var error: NSError {
		return NSError(domain: RACErrorDomain, code: toRaw(), userInfo: nil)
	}
}

Fix raw value conversions for Error enum

//
//  Errors.swift
//  ReactiveCocoa
//
//  Created by Justin Spahr-Summers on 2014-07-13.
//  Copyright (c) 2014 GitHub. All rights reserved.
//

import Foundation

/// The domain for all errors originating within the Swift components of
/// ReactiveCocoa.
///
/// For backwards compatibility reasons, the Objective-C components of
/// ReactiveCocoa use their own individual domains.
public let RACErrorDomain: NSString = "RACErrorDomain"

/// Possible error codes within `RACErrorDomain`.
public enum RACError: NSInteger {
	/// An error event occurred, but there was no `NSError` object.
	///
	/// This should only be used when bridging from Objective-C, or when
	/// invoking Objective-C APIs that may return a nil `NSError`.
	case Empty

	/// An attempt was made to execute an `Action` while it was disabled.
	case ActionNotEnabled

	/// Returns the `RACError` that corresponds to the code within the given
	/// `NSError`, or nil if the domain of the error is not `RACErrorDomain`.
	public static func fromError(error: NSError) -> RACError? {
		if error.domain == RACErrorDomain {
			return self(rawValue: error.code)
		} else {
			return nil
		}
	}

	/// An `NSError` object corresponding to this error code.
	public var error: NSError {
		return NSError(domain: RACErrorDomain, code: rawValue, userInfo: nil)
	}
}


// The MIT License (MIT)
//
// Copyright (c) 2015-2021 Alexander Grebenyuk (github.com/kean).

import XCTest
import Nuke

// `Task.swift` is added directly to this target.
class TaskPerformanceTests: XCTestCase {
    func testCompleteFlowOneSubscription() {

        measure {
            for _ in 0..<100_000 {
                let task = SimpleTask()
                _ = task.publisher.subscribe { _ in
                    // Do nothing
                }
            }
        }
    }
}

private struct MyError: Equatable {
    let raw: String
}

private final class SimpleTask: Task<Int, MyError> {
    override func start() {
        send(progress: TaskProgress(completed: 1, total: 2))
        send(value: 1)
        send(progress: TaskProgress(completed: 2, total: 2))
        send(value: 2, isCompleted: true)
    }
}

Add more Task performance tests

// The MIT License (MIT)
//
// Copyright (c) 2015-2021 Alexander Grebenyuk (github.com/kean).

import XCTest
import Nuke

// `Task.swift` is added directly to this target.
class TaskPerformanceTests: XCTestCase {
    func testAddOneSubscription() {
        measure {
            for _ in 0..<100_000 {
                let task = SimpleTask()
                _ = task.publisher.subscribe { _ in
                    // Do nothing
                }
            }
        }
    }

    func testChangePriority() {
        let task = EmptyTask()
        var priority = TaskPriority.normal
        let subscription = task.publisher.subscribe { _ in }
        _ = task.publisher.subscribe { _ in }
        measure {
            for _ in 0..<100_000 {
                let newPriority: TaskPriority = priority == .high ? .normal : .high
                subscription?.setPriority(newPriority)
                priority = newPriority
            }
        }
    }

    func testUnsubscribe() {
        measure {
            for _ in 0..<100_000 {
                let task = EmptyTask()
                let subscription = task.publisher.subscribe { _ in }
                subscription?.unsubscribe()
            }
        }
    }
}

private struct MyError: Equatable {
    let raw: String
}

private final class SimpleTask: Task<Int, MyError> {
    override func start() {
        send(progress: TaskProgress(completed: 1, total: 2))
        send(value: 1)
        send(progress: TaskProgress(completed: 2, total: 2))
        send(value: 2, isCompleted: true)
    }
}

private final class EmptyTask: Task<Int, MyError> {
    override func start() {
    }
}


import Foundation
import PackageDescription

var isSwiftPackagerManagerTest: Bool {
    return ProcessInfo.processInfo.environment["SWIFTPM_TEST_ReactiveSwift"] == "YES"
}

let package = Package(
    name: "ReactiveSwift",
    dependencies: {
        var deps: [Package.Dependency] = [
            .Package(url: "https://github.com/antitypical/Result.git", versions: Version(3, 2, 1)..<Version(3, .max, .max)),
        ]
        if isSwiftPackagerManagerTest {
            deps += [
                .Package(url: "https://github.com/Quick/Quick.git", majorVersion: 1, minor: 1),
                .Package(url: "https://github.com/Quick/Nimble.git", majorVersion: 7),
            ]
        }
        return deps
    }()
)

Support both Swift 3 and Swift 4

import Foundation
import PackageDescription

var isSwiftPackagerManagerTest: Bool {
    return ProcessInfo.processInfo.environment["SWIFTPM_TEST_ReactiveSwift"] == "YES"
}

let package = Package(
    name: "ReactiveSwift",
    dependencies: {
        var deps: [Package.Dependency] = [
            .Package(url: "https://github.com/antitypical/Result.git", versions: Version(3, 2, 1)..<Version(3, .max, .max)),
        ]
        if isSwiftPackagerManagerTest {
            deps += [
                .Package(url: "https://github.com/Quick/Quick.git", majorVersion: 1, minor: 1),
                .Package(url: "https://github.com/Quick/Nimble.git", majorVersion: 7),
            ]
        }
        return deps
    }(),
    swiftLanguageVersions: [3, 4]
)


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

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

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

import XCTest

#if !os(OSX)
public func allTests() -> [XCTestCaseEntry] {
    return [
        testCase(ByteStringTests.allTests),
        testCase(JSONTests.allTests),
        testCase(FSProxyTests.allTests),
        testCase(LazyCacheTests.allTests),
        testCase(LockTests.allTests),
        testCase(OptionParserTests.allTests),
        testCase(OutputByteStreamTests.allTests),
        testCase(TOMLTests.allTests),
        testCase(TemporaryFileTests.allTests),
    ]
}
#endif

Add PathTests and PathPerfTests to the TestManifest so they also run on Linux (macOS picks them up automatically)

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

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

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

import XCTest

#if !os(OSX)
public func allTests() -> [XCTestCaseEntry] {
    return [
        testCase(ByteStringTests.allTests),
        testCase(JSONTests.allTests),
        testCase(FSProxyTests.allTests),
        testCase(LazyCacheTests.allTests),
        testCase(LockTests.allTests),
        testCase(OptionParserTests.allTests),
        testCase(OutputByteStreamTests.allTests),
        testCase(PathTests.allTests),
        testCase(PathPerfTests.allTests),
        testCase(TOMLTests.allTests),
        testCase(TemporaryFileTests.allTests),
    ]
}
#endif


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

func foo<U>(_ x: U?) {
  _ = "\(anyLabelHere: x)"
}

// This one also crashes in a slightly different place
func bar(_ x: Int?) {
  _ = "\(anyLabelHere: x)"
}

Correct run line on fixed crasher

// RUN: %target-swift-frontend %s -emit-ir

func foo<U>(_ x: U?) {
  _ = "\(anyLabelHere: x)"
}

// This one also crashes in a slightly different place
func bar(_ x: Int?) {
  _ = "\(anyLabelHere: x)"
}


//
//  PairSpec.swift
//  SwiftyEcharts
//
//  Created by Pluto Y on 15/02/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import Quick
import Nimble
import SwiftyEcharts

class PairSpec : QuickSpec {

    override func spec() {

        describe("Testing for type named 'SECTwoElement'") {

            it(" needs to check constructor and jsonString ") {
                let noArgElements = Pair<LengthValue>()

                expect(noArgElements.jsonString).to(equal("null"))

                let percentValue: Float = 3
                let floatValue: Float = 2.1
                let twoElements: Pair<LengthValue> = [floatValue, percentValue%]

                expect(twoElements.jsonString).to(equal([floatValue, percentValue%].jsonString))

                let toMuchElements: Pair<LengthValue> = [3, 4, 5, 6%]
                expect(toMuchElements.jsonString).to(equal("null"))

                // 如果不是 LengthValue 的话，就会产生编译错误
//                let errorType: Pair = ["hello", 4]
            }

        }

    }

}

Add test case for `Pair`

//
//  PairSpec.swift
//  SwiftyEcharts
//
//  Created by Pluto Y on 15/02/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import Quick
import Nimble
import SwiftyEcharts

class PairSpec : QuickSpec {

    override func spec() {

        describe("Testing for type named 'SECTwoElement'") {

            it(" needs to check constructor and jsonString ") {
                let errorJsonString = "null"
                let noArgElements = Pair<LengthValue>()

                expect(noArgElements.jsonString).to(equal(errorJsonString))

                let percentValue: Float = 3
                let floatValue: Float = 2.1
                let twoElements: Pair<LengthValue> = [floatValue, percentValue%]

                expect(twoElements.jsonString).to(equal([floatValue, percentValue%].jsonString))

                let toMuchElements: Pair<LengthValue> = [3, 4, 5, 6%]
                expect(toMuchElements.jsonString).to(equal(errorJsonString))

                let errorElements = Pair([floatValue])
                expect(errorElements.jsonString).to(equal(errorJsonString))

                // 如果不是 LengthValue 的话，就会产生编译错误
//                let errorType: Pair = ["hello", 4]
            }

        }

    }

}


//
//  DeviceProperties.swift
//  Watson
//
//  Copyright © 2017 Anil. All rights reserved.
//

import Foundation
import UIKit
import LocalAuthentication
import CoreLocation

public enum DeviceProperties {
    case battery
    case deviceInfo
    case forceTouch
    case touchId
    case proximityMonitoring
    case beacons
    case location

    func details<T: WatsonInfo>() -> T? {
        switch self {
        case .battery:
            UIDevice.current.isBatteryMonitoringEnabled = true
            let stats = BatteryStats(
                batteryLevel: UIDevice.current.batteryLevel,
                batteryState: UIDevice.current.batteryState,
                isLowPowermodeEnabled: ProcessInfo.processInfo.isLowPowerModeEnabled
            )
            return stats as? T
        case .deviceInfo:
            return DeviceInfo() as? T
        case .touchId:
            var error: NSError?
            return LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) as? T
        case .proximityMonitoring:
            return UIDevice.current.isProximityMonitoringEnabled as? T
        case .beacons:
            return CLLocationManager.isRangingAvailable() as? T
        case .location:
            return CLLocationManager.locationServicesEnabled() as? T
        case .forceTouch:
            guard let keyWindow = UIApplication.shared.keyWindow else { return false as? T }
            return (keyWindow.traitCollection.forceTouchCapability == .available) as? T
        }
    }

    public static func all() -> [DeviceProperties] {
        return [.battery, .deviceInfo, .forceTouch, .touchId, .proximityMonitoring, .beacons, .location]
    }
}

Remove all device properties function

//
//  DeviceProperties.swift
//  Watson
//
//  Copyright © 2017 Anil. All rights reserved.
//

import Foundation
import UIKit
import LocalAuthentication
import CoreLocation

public enum DeviceProperties {
    case battery
    case deviceInfo
    case forceTouch
    case touchId
    case proximityMonitoring
    case beacons
    case location

    func details<T: WatsonInfo>() -> T? {
        switch self {
        case .battery:
            UIDevice.current.isBatteryMonitoringEnabled = true
            let stats = BatteryStats(
                batteryLevel: UIDevice.current.batteryLevel,
                batteryState: UIDevice.current.batteryState,
                isLowPowermodeEnabled: ProcessInfo.processInfo.isLowPowerModeEnabled
            )
            return stats as? T
        case .deviceInfo:
            return DeviceInfo() as? T
        case .touchId:
            var error: NSError?
            return LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) as? T
        case .proximityMonitoring:
            return UIDevice.current.isProximityMonitoringEnabled as? T
        case .beacons:
            return CLLocationManager.isRangingAvailable() as? T
        case .location:
            return CLLocationManager.locationServicesEnabled() as? T
        case .forceTouch:
            guard let keyWindow = UIApplication.shared.keyWindow else { return false as? T }
            return (keyWindow.traitCollection.forceTouchCapability == .available) as? T
        }
    }

}


import Nimble
import Moya

public func beOfSameErrorType(_ expectedValue: MoyaError) -> MatcherFunc<MoyaError> {
    return MatcherFunc { actualExpression, failureMessage in
        do {
            guard let actualValue = try actualExpression.evaluate() else {
                return false
            }

            switch actualValue {
            case .imageMapping:
                switch expectedValue {
                case .imageMapping:
                    return true
                default:
                    return false
                }
            case .jsonMapping:
                switch expectedValue {
                case .jsonMapping:
                    return true
                default:
                    return false
                }
            case .stringMapping:
                switch expectedValue {
                case .stringMapping:
                    return true
                default:
                    return false
                }
            case .statusCode:
                switch expectedValue {
                case .statusCode:
                    return true
                default:
                    return false
                }
            case .underlying:
                switch expectedValue {
                case .underlying:
                    return true
                default:
                    return false
                }
            case .requestMapping:
                switch expectedValue {
                case .requestMapping:
                    return true
                default:
                    return false
                }
            }
        } catch {
            return false;
        }
    }
}

Update beOfSameErrorType to new Nimble Predicate API.

import Nimble
import Moya

public func beOfSameErrorType(_ expectedValue: MoyaError) -> Predicate<MoyaError> {
    return Predicate { expression -> PredicateResult in
        let test: Bool
        if let value = try expression.evaluate() {
            switch value {
            case .imageMapping:
                switch expectedValue {
                case .imageMapping:
                    test = true
                default:
                    test = false
                }
            case .jsonMapping:
                switch expectedValue {
                case .jsonMapping:
                    test = true
                default:
                    test = false
                }
            case .stringMapping:
                switch expectedValue {
                case .stringMapping:
                    test = true
                default:
                    test = false
                }
            case .statusCode:
                switch expectedValue {
                case .statusCode:
                    test = true
                default:
                    test = false
                }
            case .underlying:
                switch expectedValue {
                case .underlying:
                    test = true
                default:
                    test = false
                }
            case .requestMapping:
                switch expectedValue {
                case .requestMapping:
                    test = true
                default:
                    test = false
                }
            }
        } else {
            test = false
        }

        return PredicateResult(bool: test, message: .expectedActualValueTo("<\(expectedValue)>"))
    }
}


//
//  RDF.swift
//  kineo-test
//
//  Created by Gregory Todd Williams on 3/25/18.
//  Copyright © 2018 Gregory Todd Williams. All rights reserved.
//

import Foundation

Add tests for numeric term constructors.

import XCTest
import Foundation
import Kineo

// swiftlint:disable type_body_length
class RDFTest: 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 testConstructorInteger() {
        let t = Term(integer: 7)
        XCTAssertEqual(t.value, "7")
    }

    func testConstructorDecimal() {
        let t = Term(decimal: 7.1)
        XCTAssertEqual(t.value, "7.100000")
    }

    func testConstructorFloat() {
        let t = Term(float: -70.1)
        XCTAssertEqual(t.value, "-7.010000E+01")
    }

    func testConstructorDouble() {
        let t = Term(double: 700.1)
        XCTAssertEqual(t.value, "7.001000E+02")
    }

}


//
//  AssertEqualsForOptionals.swift
//  Bond
//
//  Created by Anthony Egerton on 15/03/2015.
//  Copyright (c) 2015 Bond. All rights reserved.
//

import Foundation
import XCTest

func XCTAssertEqual<T:Equatable>(actual: T?, expected: T?, _ message: String = "", file: String = #file, line: UInt = #line) {
  switch (actual, expected) {
  case (nil, nil): break
  case (nil, _): XCTFail("(\"nil\") is not equal to (\"\(expected)\")", file: #file, line: line)
  case (_, nil): XCTFail("(\"\(actual)\") is not equal to (\"nil\")", file: #file, line: line)
  default: XCTAssertEqual(actual!, expected: expected!, message, file: file, line: line)
  }
}

Update to the file reference in XCTAssert for optionals

//
//  AssertEqualsForOptionals.swift
//  Bond
//
//  Created by Anthony Egerton on 15/03/2015.
//  Copyright (c) 2015 Bond. All rights reserved.
//

import Foundation
import XCTest

func XCTAssertEqual<T:Equatable>(actual: T?, expected: T?, _ message: String = "", file: StaticString = #file, line: UInt = #line) {
  switch (actual, expected) {
  case (nil, nil): break
  case (nil, _): XCTFail("(\"nil\") is not equal to (\"\(expected)\")", file: file, line: line)
  case (_, nil): XCTFail("(\"\(actual)\") is not equal to (\"nil\")", file: file, line: line)
  default: XCTAssertEqual(actual!, expected: expected!, message, file: file, line: line)
  }
}


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

import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

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

    // [START tracker_swift]
    FirebaseApp.configure()
    // [END tracker_swift]

    // Set a white background so that patterns are showcased.
    window?.backgroundColor = .white

    return true
  }

}

Update AnalyticsExample to Swift 4.2

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

import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    // [START tracker_swift]
    FirebaseApp.configure()
    // [END tracker_swift]

    // Set a white background so that patterns are showcased.
    window?.backgroundColor = .white

    return true
  }

}


// REQUIRES: OS=macosx
// RUN: %empty-directory(%t.tmp)
// mkdir %t.tmp/module-cache && mkdir %t.tmp/dummy.sdk
// RUN: %api-digester -dump-sdk -module Swift -o %t.tmp/current-stdlib.json -module-cache-path %t.tmp/module-cache -sdk %t.tmp/dummy.sdk
// RUN: %api-digester -diagnose-sdk -input-paths %S/Inputs/stdlib-stable.json -input-paths %t.tmp/current-stdlib.json -o %t.tmp/changes.txt
// RUN: %clang -E -P -x c %S/Outputs/stability-stdlib-source.swift.expected -o - | sed '/^\s*$/d' > %t.tmp/stability-stdlib-source.swift.expected
// RUN: %clang -E -P -x c %t.tmp/changes.txt -o - | sed '/^\s*$/d' > %t.tmp/changes.txt.tmp
// RUN: diff -u %t.tmp/stability-stdlib-source.swift.expected %t.tmp/changes.txt.tmp

Sort source stability results, similar to ABI test change

// REQUIRES: OS=macosx
// RUN: %empty-directory(%t.tmp)
// mkdir %t.tmp/module-cache && mkdir %t.tmp/dummy.sdk
// RUN: %api-digester -dump-sdk -module Swift -o %t.tmp/current-stdlib.json -module-cache-path %t.tmp/module-cache -sdk %t.tmp/dummy.sdk
// RUN: %api-digester -diagnose-sdk -input-paths %S/Inputs/stdlib-stable.json -input-paths %t.tmp/current-stdlib.json -o %t.tmp/changes.txt
// RUN: %clang -E -P -x c %S/Outputs/stability-stdlib-source.swift.expected -o - | sed '/^\s*$/d' | sort > %t.tmp/stability-stdlib-source.swift.expected
// RUN: %clang -E -P -x c %t.tmp/changes.txt -o - | sed '/^\s*$/d' | sort > %t.tmp/changes.txt.tmp
// RUN: diff -u %t.tmp/stability-stdlib-source.swift.expected %t.tmp/changes.txt.tmp


//
//  TransitionAnimator.swift
//  VanHaren
//
//  Created by Artem Novichkov on 30/11/2016.
//  Copyright © 2016 Rosberry. All rights reserved.
//

import UIKit

protocol TransitionAnimator: UIViewControllerAnimatedTransitioning {

    var presenting: Bool { get set }
    var options: AnimationOptions { get set }
}

typealias Controllers = (fromViewController: UIViewController, toViewController: UIViewController)
typealias AnimateTransitionHandler = (UIViewControllerContextTransitioning) -> ()

//MARK: - Defaults
extension TransitionAnimator {

    func configure(using transitionContext: UIViewControllerContextTransitioning) -> Controllers {
        let fromViewController = transitionContext.viewController(forKey: .from)!
        let toViewController = transitionContext.viewController(forKey: .to)!
        let containerView = transitionContext.containerView

        if presenting {
            containerView.addSubview(toViewController.view)
        }
        else {
            containerView.addSubview(fromViewController.view)
        }

        return (fromViewController, toViewController)
    }

    func animate(with context: UIViewControllerContextTransitioning, animations: @escaping () -> Swift.Void) {
        UIView.animate(withDuration: options.duration, delay: options.delay, options: options.option, animations: animations, completion: context.completion)
    }
}

extension UIViewControllerContextTransitioning {

    var completion: ((Bool) -> Swift.Void) {
        return { _ in
            self.completeTransition(!self.transitionWasCancelled)
        }
    }
}

Remove adding of from vc view

//
//  TransitionAnimator.swift
//  VanHaren
//
//  Created by Artem Novichkov on 30/11/2016.
//  Copyright © 2016 Rosberry. All rights reserved.
//

import UIKit

protocol TransitionAnimator: UIViewControllerAnimatedTransitioning {

    var presenting: Bool { get set }
    var options: AnimationOptions { get set }
}

typealias Controllers = (fromViewController: UIViewController, toViewController: UIViewController)
typealias AnimateTransitionHandler = (UIViewControllerContextTransitioning) -> ()

//MARK: - Defaults
extension TransitionAnimator {

    func configure(using transitionContext: UIViewControllerContextTransitioning) -> Controllers {
        let fromViewController = transitionContext.viewController(forKey: .from)!
        let toViewController = transitionContext.viewController(forKey: .to)!
        let containerView = transitionContext.containerView

        if presenting {
            containerView.addSubview(toViewController.view)
        }

        return (fromViewController, toViewController)
    }

    func animate(with context: UIViewControllerContextTransitioning, animations: @escaping () -> Swift.Void) {
        UIView.animate(withDuration: options.duration, delay: options.delay, options: options.option, animations: animations, completion: context.completion)
    }
}

extension UIViewControllerContextTransitioning {

    var completion: ((Bool) -> Swift.Void) {
        return { _ in
            self.completeTransition(!self.transitionWasCancelled)
        }
    }
}


// RUN: rm -rf %t && mkdir -p %t
// RUN: not %target-swift-frontend -typecheck %s -I %S/Inputs/non-modular -F %S/Inputs/non-modular 2>&1 | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-os %s

// CHECK: {{.+}}/non-modular/Foo.framework/Headers/Foo.h:1:9: error: include of non-modular header inside framework module 'Foo'
// CHECK-macosx: error: could not build Objective-C module 'Foo'
// CHECK-linux: error: could not build C module 'Foo'
// CHECK-NOT: error

import Foo

_ = Foo.x

Change Linux specific check to `linux-gnu`

// RUN: rm -rf %t && mkdir -p %t
// RUN: not %target-swift-frontend -typecheck %s -I %S/Inputs/non-modular -F %S/Inputs/non-modular 2>&1 | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-os %s

// CHECK: {{.+}}/non-modular/Foo.framework/Headers/Foo.h:1:9: error: include of non-modular header inside framework module 'Foo'
// CHECK-macosx: error: could not build Objective-C module 'Foo'
// CHECK-linux-gnu: error: could not build C module 'Foo'
// CHECK-NOT: error

import Foo

_ = Foo.x


//
//  CollectionExtensions.swift
//  SwiftDevHints
//
//  Created by Derek on 10/4/18.
//  Copyright © 2018 ZHOU DENGFENG DEREK. All rights reserved.
//

import Foundation

extension Collection {

    /// The safe way to return element at specified index.
    /// Referenced from https://github.com/Luur/SwiftTips#1-safe-way-to-return-element-at-specified-index
    ///
    ///     let animals = ["Zebra", "Giraffe", "Tiger"]
    ///     animals[safe: 2] // Tiger
    ///     animals[safe: 3] // nil
    ///
    /// - Parameter position: The position of the element to access. If the **position** is not a valid index
    /// of the collection, return nil.
    subscript(safe position: Index) -> Element? {
        return indices.contains(position) ? self[position] : nil
    }
}

Make Collection safe subscript public

//
//  CollectionExtensions.swift
//  SwiftDevHints
//
//  Created by Derek on 10/4/18.
//  Copyright © 2018 ZHOU DENGFENG DEREK. All rights reserved.
//

import Foundation

public extension Collection {

    /// The safe way to return element at specified index.
    /// Referenced from https://github.com/Luur/SwiftTips#1-safe-way-to-return-element-at-specified-index
    ///
    ///     let animals = ["Zebra", "Giraffe", "Tiger"]
    ///     animals[safe: 2] // Tiger
    ///     animals[safe: 3] // nil
    ///
    /// - Parameter position: The position of the element to access. If the **position** is not a valid index
    /// of the collection, return nil.
    subscript(safe position: Index) -> Element? {
        return indices.contains(position) ? self[position] : nil
    }
}


import Speedy
import Nimble

class RoostfileSpec: Spec {
  var definition: String {
    get {
      return "\n".join([
        "name: Test",
        "version: 0.1.2",
        "target_type: executable",
        "sources:",
        "  - TestFile.swift",
        "  - TestDirectory/",
      ])
    }
  }

  func spec() {
    describe("when parsing") {
      var r: Roostfile!

      beforeEach {
        r = Roostfile()
        r.parseFromString(self.definition)
      }

      it("should parse basic properties") {
        expect(r.name).to(equal("Test"))
        expect(r.targetType).to(equal(TargetType.Executable))
      }

      it("should parse sources") {
        expect(r.sources.count).to(equal(2))
        expect(r.sources[0]).to(equal("TestFile.swift"))
        expect(r.sources[1]).to(equal("TestDirectory/"))
      }
    }
  }
}

Add test for errors in Roostfile parsing

import Speedy
import Nimble

class RoostfileSpec: Spec {
  var definition: String {
    get {
      return "\n".join([
        "name: Test",
        "version: 0.1.2",
        "target_type: executable",
        "sources:",
        "  - TestFile.swift",
        "  - TestDirectory/",
      ])
    }
  }

  func spec() {
    describe("when parsing valid Roostfiles") {
      var r: Roostfile!

      beforeEach {
        r = Roostfile()
        r.parseFromString(self.definition)
      }

      it("should parse basic properties") {
        expect(r.name).to(equal("Test"))
        expect(r.targetType).to(equal(TargetType.Executable))
      }

      it("should parse sources") {
        expect(r.sources.count).to(equal(2))
        expect(r.sources[0]).to(equal("TestFile.swift"))
        expect(r.sources[1]).to(equal("TestDirectory/"))
      }
    }
    describe("when parsing invalid Roostfiles") {
      var r: Roostfile!

      beforeEach {
        r = Roostfile()
      }

      it("should not parse invalid properties") {
        let error = r.parseFromString("bad_property: bad")
        expect(error).toNot(beNil())
        expect(error!.message).to(contain("bad_property"))
      }
    }
  }
}


//
//  RepositoriesClient.swift
//  GithubClient
//
//  Created by Eduardo Arenas on 8/5/17.
//  Copyright © 2017 GameChanger. All rights reserved.
//

import Foundation
import RxSwift

public class ApiClient {

  let decoder = JSONDecoder()

  private let httpService = HTTPService()
  private let headers: [String: CustomStringConvertible]

  public init(authorizationToken: String) {
    headers = ["Authorization": authorizationToken,
               "Accept": "application/vnd.github.v3+json"]
    decoder.dateDecodingStrategy = .iso8601
  }

  func get<T: Decodable>(apiUrl: ApiUrl, parameters: [ApiParameter?]? = nil) -> Observable<T> {
    let queryDict = parameters.flatMap { CustomApiParameter.queryDict(forParameters: $0) }
    return httpService.get(url: apiUrl.fullPath, query: queryDict, headers: headers)
      .map { return try self.decoder.decode(T.self, from: $0.0) }
  }
}

Add patch method taking an Encodable object to the API Client

//
//  RepositoriesClient.swift
//  GithubClient
//
//  Created by Eduardo Arenas on 8/5/17.
//  Copyright © 2017 GameChanger. All rights reserved.
//

import Foundation
import RxSwift

public class ApiClient {

  let encoder = JSONEncoder()
  let decoder = JSONDecoder()

  private let httpService = HTTPService()
  private let headers: [String: CustomStringConvertible]

  public init(authorizationToken: String) {
    headers = ["Authorization": authorizationToken,
               "Accept": "application/vnd.github.v3+json"]
    encoder.dateEncodingStrategy = .iso8601
    decoder.dateDecodingStrategy = .iso8601
  }

  func get<T: Decodable>(apiUrl: ApiUrl, parameters: [ApiParameter?]? = nil) -> Observable<T> {
    let queryDict = parameters.flatMap { CustomApiParameter.queryDict(forParameters: $0) }
    return httpService.get(url: apiUrl.fullPath, query: queryDict, headers: headers)
      .map { return try self.decoder.decode(T.self, from: $0.0) }
  }

  func patch<U: Encodable, R: Decodable>(apiUrl: ApiUrl, object: U) -> Observable<R> {
    return httpService.patch(url: apiUrl.fullPath, data: try! encoder.encode(object), headers: headers)
      .map { return try self.decoder.decode(R.self, from: $0.0) }
  }
}


import Foundation
import Argo
import Result

public protocol Request {
  typealias ResponseType
  func build() -> NSURLRequest
  func parse(j: JSON) -> Result<ResponseType, NSError>
}

Add default implementation of parse for Decodable

import Foundation
import Argo
import Result

public protocol Request {
  typealias ResponseType
  func build() -> NSURLRequest
  func parse(j: JSON) -> Result<ResponseType, NSError>
}

extension Request where ResponseType: Decodable, ResponseType.DecodedType == ResponseType {
  func parse(j: JSON) -> Result<ResponseType, NSError> {
    return .fromDecoded(ResponseType.decode(j))
  }
}


//
//  PredictedBG.swift
//  RileyLink
//
//  Created by Pete Schwamb on 8/8/16.
//  Copyright © 2016 Pete Schwamb. All rights reserved.
//

import Foundation
import HealthKit

public struct PredictedBG {
    let values: [Double]
    let cob: [Double]?
    let iob: [Double]?

    public init(values: [HKQuantity], cob: [HKQuantity]? = nil, iob: [HKQuantity]? = nil) {
        // BG values in nightscout are in mg/dL.
        let unit = HKUnit.milligramsPerDeciliterUnit()
        self.values = values.map { $0.doubleValueForUnit(unit) }
        self.cob = cob?.map { $0.doubleValueForUnit(unit) }
        self.iob = iob?.map { $0.doubleValueForUnit(unit) }
    }

    public var dictionaryRepresentation: [String: AnyObject] {

        var rval = [String: AnyObject]()

        rval["values"] = values

        if let cob = cob {
            rval["cob"] = cob
        }

        if let iob = iob {
            rval["iob"] = iob
        }

        return rval
    }
}

Fix case of carb and insulin effect attributes

//
//  PredictedBG.swift
//  RileyLink
//
//  Created by Pete Schwamb on 8/8/16.
//  Copyright © 2016 Pete Schwamb. All rights reserved.
//

import Foundation
import HealthKit

public struct PredictedBG {
    let values: [Double]
    let cob: [Double]?
    let iob: [Double]?

    public init(values: [HKQuantity], cob: [HKQuantity]? = nil, iob: [HKQuantity]? = nil) {
        // BG values in nightscout are in mg/dL.
        let unit = HKUnit.milligramsPerDeciliterUnit()
        self.values = values.map { $0.doubleValueForUnit(unit) }
        self.cob = cob?.map { $0.doubleValueForUnit(unit) }
        self.iob = iob?.map { $0.doubleValueForUnit(unit) }
    }

    public var dictionaryRepresentation: [String: AnyObject] {

        var rval = [String: AnyObject]()

        rval["values"] = values

        if let cob = cob {
            rval["COB"] = cob
        }

        if let iob = iob {
            rval["IOB"] = iob
        }

        return rval
    }
}


//
//  AdminControllerCreators.swift
//  Walllpaper
//
//  Created by Maxime De Greve on 25/02/2017.
//
//

import Vapor
import HTTP

final class AdminCreatorsController {

    func addRoutes(to drop: Droplet) {

        drop.group(AdminProtectMiddleware()) { secure in
            secure.get("admin","creators", handler: creators)
        }

    }

    func creators(_ request: Request) throws -> ResponseRepresentable {

        let users = try User.withShots().makeNode()

        return try drop.view.make("admin-creator", [
            "users": users,
            ])

    }

}

Sort by followers in admin panel

//
//  AdminControllerCreators.swift
//  Walllpaper
//
//  Created by Maxime De Greve on 25/02/2017.
//
//

import Vapor
import HTTP

final class AdminCreatorsController {

    func addRoutes(to drop: Droplet) {

        drop.group(AdminProtectMiddleware()) { secure in
            secure.get("admin","creators", handler: creators)
        }

    }

    func creators(_ request: Request) throws -> ResponseRepresentable {

        let users = try User.withShots().sorted(by: { (user, otherUser) -> Bool in
            return user.followersCount > otherUser.followersCount
        }) .makeNode()

        return try drop.view.make("admin-creator", [
            "users": users,
            ])

    }

}


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

extension Request {
    public struct UpdateUser: Encodable {
        public struct BasicInfos: Encodable {
            public var userId: String = ""
            public var userToken: String = ""
            public var name: String?
            public var lastname: String?
            public var email: String?
            public var phone: String?
            public var cpf: String?

            public init() {}
        }

        public struct BillingInfos: Encodable {
            public var userId: String = ""
            public var userToken: String = ""
            public var zip: String = ""
            public var street: String = ""
            public var number: String = ""
            public var complement: String = ""
            public var district: String = ""
            public var city: String = ""
            public var state: String = ""

            public init() {}
        }
    }
}

Exclude userId and userToken from post params

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

extension Request {
    public struct UpdateUser: Encodable {
        public struct BasicInfos: Encodable {
            public var userId: String = ""
            public var userToken: String = ""
            public var name: String?
            public var lastname: String?
            public var email: String?
            public var phone: String?
            public var cpf: String?

            public init() {}

            private enum CodingKeys: String, CodingKey {
                case name
                case lastname
                case email
                case phone
                case cpf
            }
        }

        public struct BillingInfos: Encodable {
            public var userId: String = ""
            public var userToken: String = ""
            public var zip: String = ""
            public var street: String = ""
            public var number: String = ""
            public var complement: String = ""
            public var district: String = ""
            public var city: String = ""
            public var state: String = ""

            public init() {}

            private enum CodingKeys: String, CodingKey {
                case zip
                case street
                case number
                case complement
                case district
                case city
                case state
            }
        }
    }
}


//
//  Main.swift
//  subber-api
//
//  Created by Hakon Hanesand on 9/26/16.
//
//

import Vapor
import Fluent
import Node
import HTTP
import Turnstile
import Foundation
import Auth
import Stripe

let drop = Droplet.create()

drop.resource("boxes", BoxController())
drop.resource("customers", CustomerController())
drop.resource("shipping", ShippingController())
drop.resource("authentication", AuthenticationController())
drop.resource("categories", CategoryController())
drop.resource("orders", OrderController())
drop.resource("vendors", VendorController())
drop.resource("reviews", ReviewController())
drop.resource("subscriptions", SubscriptionController())
drop.resource("search", SearchController())
drop.resource("images", ImageController())
drop.resource("contracts", ContractController())
drop.resource("logs", LogFileController())

drop.collection(StripeCollection.self)
drop.collection(StripeWebhookManager.shared)

drop.run()

Make sure we actually create web hooks

//
//  Main.swift
//  subber-api
//
//  Created by Hakon Hanesand on 9/26/16.
//
//

import Vapor
import Fluent
import Node
import HTTP
import Turnstile
import Foundation
import Auth
import Stripe

let drop = Droplet.create()

drop.resource("boxes", BoxController())
drop.resource("customers", CustomerController())
drop.resource("shipping", ShippingController())
drop.resource("authentication", AuthenticationController())
drop.resource("categories", CategoryController())
drop.resource("orders", OrderController())
drop.resource("vendors", VendorController())
drop.resource("reviews", ReviewController())
drop.resource("subscriptions", SubscriptionController())
drop.resource("search", SearchController())
drop.resource("images", ImageController())
drop.resource("contracts", ContractController())
drop.resource("logs", LogFileController())

drop.collection(StripeCollection.self)
drop.collection(StripeWebhookManager.shared)

let webhooks = StripeWebhookCollection()

drop.run()


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

import Foundation

public protocol Nameable { }

public extension Nameable {

    public static var name: String {
        return String(describing: Self.self)
    }

    public func addAccessibilityIdentifiers() {
        for (label, object) in Mirror(reflecting: self).children {
            guard let label = label else { continue }
            let accessibleObject: UIAccessibilityIdentification
            if let view = object as? UIView {
                accessibleObject = view
            } else if let barItem = object as? UIBarItem {
                accessibleObject = barItem
            } else {
                continue
            }
            accessibleObject.accessibilityIdentifier = Self.name + "." + label
        }
    }

}

Fix compile issue in Xcode 10

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

import UIKit

public protocol Nameable { }

public extension Nameable {

    public static var name: String {
        return String(describing: Self.self)
    }

    public func addAccessibilityIdentifiers() {
        for (label, object) in Mirror(reflecting: self).children {
            guard let label = label else { continue }
            let accessibleObject: UIAccessibilityIdentification
            if let view = object as? UIView {
                accessibleObject = view
            } else if let barItem = object as? UIBarItem {
                accessibleObject = barItem
            } else {
                continue
            }
            accessibleObject.accessibilityIdentifier = Self.name + "." + label
        }
    }

}


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

extension Module {
	public static var churchEither: Module {
		let Either = Declaration("Either",
			type: Recur.FunctionType(.Type, .Type, .Type),
			value: (.Type, .Type, .Type) => { L, R, Result in (L --> Result) --> (R --> Result) --> Result })

		let left = Declaration("left",
			type: Recur.lambda(.Type, .Type) { L, R in .FunctionType(L, Either.ref[L, R]) },
			value: Recur.lambda(.Type, .Type) { L, R in Recur.lambda(L, .Type) { l, Result in Recur.lambda(.FunctionType(L, Result), .FunctionType(R, Result)) { ifL, _ in ifL[l] } } })

		let right = Declaration("right",
			type: Recur.lambda(.Type, .Type) { L, R in .FunctionType(R, Either.ref[L, R]) },
			value: Recur.lambda(.Type, .Type) { L, R in Recur.lambda(R, .Type) { r, Result in Recur.lambda(.FunctionType(L, Result), .FunctionType(R, Result)) { _, ifR in ifR[r] } } })

		return Module("ChurchEither", [ Either, left, right ])
	}
}

Use the --> operator to define ChurchEither.Either’s type.

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

extension Module {
	public static var churchEither: Module {
		let Either = Declaration<Recur>("Either",
			type: .Type --> .Type --> .Type,
			value: (.Type, .Type, .Type) => { L, R, Result in (L --> Result) --> (R --> Result) --> Result })

		let left = Declaration("left",
			type: Recur.lambda(.Type, .Type) { L, R in .FunctionType(L, Either.ref[L, R]) },
			value: Recur.lambda(.Type, .Type) { L, R in Recur.lambda(L, .Type) { l, Result in Recur.lambda(.FunctionType(L, Result), .FunctionType(R, Result)) { ifL, _ in ifL[l] } } })

		let right = Declaration("right",
			type: Recur.lambda(.Type, .Type) { L, R in .FunctionType(R, Either.ref[L, R]) },
			value: Recur.lambda(.Type, .Type) { L, R in Recur.lambda(R, .Type) { r, Result in Recur.lambda(.FunctionType(L, Result), .FunctionType(R, Result)) { _, ifR in ifR[r] } } })

		return Module("ChurchEither", [ Either, left, right ])
	}
}


// The clang module triggers a warning, make sure that -Fsystem has the effect of importing as system, which will suppress the warning.

// RUN: %empty-directory(%t)

// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -F %S/Inputs/systemframeworks -module-cache-path %t/mcp1 %s 2> %t/stderr-as-user.txt
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -Fsystem %S/Inputs/systemframeworks -module-cache-path %t/mcp2 %s 2> %t/stderr-as-system.txt
// RUN: %FileCheck -input-file=%t/stderr-as-user.txt %s -check-prefix=CHECK-USER
// RUN: %FileCheck -input-file=%t/stderr-as-system.txt %s -check-prefix=CHECK-SYSTEM --allow-empty

// CHECK-USER: control reaches end of non-void function
// CHECK-SYSTEM-NOT: control reaches end of non-void function
import Module

Update test for new Clang diagnostic wording

// The clang module triggers a warning, make sure that -Fsystem has the effect of importing as system, which will suppress the warning.

// RUN: %empty-directory(%t)

// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -F %S/Inputs/systemframeworks -module-cache-path %t/mcp1 %s 2> %t/stderr-as-user.txt
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -Fsystem %S/Inputs/systemframeworks -module-cache-path %t/mcp2 %s 2> %t/stderr-as-system.txt
// RUN: %FileCheck -input-file=%t/stderr-as-user.txt %s -check-prefix=CHECK-USER
// RUN: %FileCheck -input-file=%t/stderr-as-system.txt %s -check-prefix=CHECK-SYSTEM --allow-empty

// CHECK-USER: non-void function does not return a value
// CHECK-SYSTEM-NOT: non-void function does not return a value
import Module


//
//  UIViewController+NibResource.swift
//  R.swift Library
//
//  Created by Mathijs Kadijk on 06-12-15.
//  Copyright © 2015 Mathijs Kadijk. All rights reserved.
//

import Foundation
import UIKit

public extension UIViewController {
  /**
   Returns a newly initialized view controller with the nib resource (R.nib.*).

   - parameter nib: The name of the nib resource (R.nib.*) to associate with the view controller.

   - returns: A newly initialized UIViewController object.
  */
  public convenience init(nib: NibResourceType) {
    self.init(nibName: nib.name, bundle: nib.bundle)
  }
}

Correct comment about UIViewController nib loading

//
//  UIViewController+NibResource.swift
//  R.swift Library
//
//  Created by Mathijs Kadijk on 06-12-15.
//  Copyright © 2015 Mathijs Kadijk. All rights reserved.
//

import Foundation
import UIKit

public extension UIViewController {
  /**
   Returns a newly initialized view controller with the nib resource (R.nib.*).

   - parameter nib: The nib resource (R.nib.*) to associate with the view controller.

   - returns: A newly initialized UIViewController object.
  */
  public convenience init(nib: NibResourceType) {
    self.init(nibName: nib.name, bundle: nib.bundle)
  }
}


import Foundation

/// Convenience wrapper for generically storing values of type `T` in thread-local storage.
internal final class ThreadLocal<T> {
  let key: String

  init(_ key: String) {
    self.key = key
  }

  var value: T? {
    get {
#if swift(>=3.1)
      return Thread.current.threadDictionary[key] as? T
#else
      let box = Thread.current.threadDictionary[key] as? Box<T>
      return box?.value
#endif
    }
    set {
#if !swift(>=3.1)
      let newValue = newValue.map(Box.init(_:))
#endif
      Thread.current.threadDictionary[key] = newValue
    }
  }
}

#if !swift(>=3.1)
private final class Box<T> {
  let value: T

  init(_ value: T) {
    self.value = value
  }
}
#endif

Drop support for swift < 3.1

import Foundation

/// Convenience wrapper for generically storing values of type `T` in thread-local storage.
internal final class ThreadLocal<T> {
  let key: String

  init(_ key: String) {
    self.key = key
  }

  var value: T? {
    get {
      return Thread.current.threadDictionary[key] as? T
    }
    set {
      Thread.current.threadDictionary[key] = newValue
    }
  }
}


//
//  Extensions.swift
//  XcodeEdit
//
//  Created by Tom Lokhorst on 2015-08-29.
//  Copyright © 2015 nonstrict. All rights reserved.
//

import Foundation

func += <KeyType, ValueType> (left: inout Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
  for (k, v) in right {
    left.updateValue(v, forKey: k)
  }
}

extension Sequence {
  func ofType<T>(_ type: T.Type) -> [T] {
    return self.flatMap { $0 as? T }
  }

  func grouped<Key: Hashable>(by keySelector: (Iterator.Element) -> Key) -> [Key : [Iterator.Element]] {
    var groupedBy = Dictionary<Key, [Iterator.Element]>()

    for element in self {
      let key = keySelector(element)
      var array = groupedBy.removeValue(forKey: key) ?? []
      array.append(element)
      groupedBy[key] = array
    }

    return groupedBy
  }

  func sorted<U: Comparable>(by keySelector: (Iterator.Element) -> U) -> [Iterator.Element] {
    return self.sorted { keySelector($0) < keySelector($1) }
  }
}

Update grouped(by:) function to Swift 4

//
//  Extensions.swift
//  XcodeEdit
//
//  Created by Tom Lokhorst on 2015-08-29.
//  Copyright © 2015 nonstrict. All rights reserved.
//

import Foundation

func += <KeyType, ValueType> (left: inout Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
  for (k, v) in right {
    left.updateValue(v, forKey: k)
  }
}

extension Sequence {
  func ofType<T>(_ type: T.Type) -> [T] {
    return self.flatMap { $0 as? T }
  }

  func grouped<Key>(by keySelector: (Iterator.Element) -> Key) -> [Key : [Iterator.Element]] {
    var groupedBy = Dictionary<Key, [Iterator.Element]>()

    for element in self {
      let key = keySelector(element)
      groupedBy[key, default: []].append(element)
    }

    return groupedBy
  }

  func sorted<U: Comparable>(by keySelector: (Iterator.Element) -> U) -> [Iterator.Element] {
    return self.sorted { keySelector($0) < keySelector($1) }
  }
}


//
//  PreferencesWindow.swift
//  Amethyst
//
//  Created by Ian Ynda-Hummel on 7/19/17.
//  Copyright © 2017 Ian Ynda-Hummel. All rights reserved.
//

import AppKit

class PreferencesWindowController: NSWindowController {
    override func awakeFromNib() {
        super.awakeFromNib()

        guard let firstItem = window?.toolbar?.items.first else {
            return
        }

        window?.toolbar?.selectedItemIdentifier = firstItem.itemIdentifier
        selectPane(firstItem)
    }

    @IBAction func selectPane(_ sender: NSToolbarItem) {
        switch sender.itemIdentifier.rawValue {
        case "general":
            contentViewController = GeneralPreferencesViewController()
        case "shortcuts":
            contentViewController = ShortcutsPreferencesViewController()
        case "floating":
            contentViewController = FloatingPreferencesViewController()
        default:
            break
        }
    }
}

final class PreferencesWindow: NSWindow {
    @IBOutlet var closeMenuItem: NSMenuItem?

    override func keyDown(with event: NSEvent) {
        super.keyDown(with: event)

        guard let closeMenuItem = closeMenuItem else {
            return
        }

        let eventModifierMask = event.modifierFlags.intersection(.deviceIndependentFlagsMask)

        guard closeMenuItem.keyEquivalentModifierMask == eventModifierMask && closeMenuItem.keyEquivalent == event.characters else {
            return
        }

        close()
    }
}

Remove the generic window title on preferences

//
//  PreferencesWindow.swift
//  Amethyst
//
//  Created by Ian Ynda-Hummel on 7/19/17.
//  Copyright © 2017 Ian Ynda-Hummel. All rights reserved.
//

import AppKit

class PreferencesWindowController: NSWindowController {
    override func awakeFromNib() {
        super.awakeFromNib()

        window?.title = ""

        guard let firstItem = window?.toolbar?.items.first else {
            return
        }

        window?.toolbar?.selectedItemIdentifier = firstItem.itemIdentifier
        selectPane(firstItem)
    }

    @IBAction func selectPane(_ sender: NSToolbarItem) {
        switch sender.itemIdentifier.rawValue {
        case "general":
            contentViewController = GeneralPreferencesViewController()
        case "shortcuts":
            contentViewController = ShortcutsPreferencesViewController()
        case "floating":
            contentViewController = FloatingPreferencesViewController()
        default:
            break
        }
    }
}

final class PreferencesWindow: NSWindow {
    @IBOutlet var closeMenuItem: NSMenuItem?

    override func keyDown(with event: NSEvent) {
        super.keyDown(with: event)

        guard let closeMenuItem = closeMenuItem else {
            return
        }

        let eventModifierMask = event.modifierFlags.intersection(.deviceIndependentFlagsMask)

        guard closeMenuItem.keyEquivalentModifierMask == eventModifierMask && closeMenuItem.keyEquivalent == event.characters else {
            return
        }

        close()
    }
}


// Verify that async parses correctly via the parser lib even without the
// experimental flag being set in LangOpts.
//
// REQUIRES: syntax_parser_lib
// RUN: %swift-syntax-parser-test %s -dump-diags 2>&1 | %FileCheck %s

func asyncGlobal1() async { }
func asyncGlobal2() async throws { }

typealias AsyncFunc1 = () async -> ()
typealias AsyncFunc2 = () async throws -> ()

func testTypeExprs() {
  let _ = [() async -> ()]()
  let _ = [() async throws -> ()]()
}

func testAwaitOperator() async {
  let _ = __await asyncGlobal1()
}

func testAsyncClosure() {
  let _ = { () async in 5 }
  let _ = { () throws in 5 }
  let _ = { () async throws in 5 }
}

// CHECK: 0 error(s) 0 warnings(s) 0 note(s)

Fix one last test for __await -> await

// Verify that async parses correctly via the parser lib even without the
// experimental flag being set in LangOpts.
//
// REQUIRES: syntax_parser_lib
// RUN: %swift-syntax-parser-test %s -dump-diags 2>&1 | %FileCheck %s

func asyncGlobal1() async { }
func asyncGlobal2() async throws { }

typealias AsyncFunc1 = () async -> ()
typealias AsyncFunc2 = () async throws -> ()

func testTypeExprs() {
  let _ = [() async -> ()]()
  let _ = [() async throws -> ()]()
}

func testAwaitOperator() async {
  let _ = await asyncGlobal1()
}

func testAsyncClosure() {
  let _ = { () async in 5 }
  let _ = { () throws in 5 }
  let _ = { () async throws in 5 }
}

// CHECK: 0 error(s) 0 warnings(s) 0 note(s)


//
//  Types.swift
//  MoyskladNew
//
//  Created by Andrey Parshakov on 14.10.16.
//  Copyright © 2016 Andrey Parshakov. All rights reserved.
//

import Foundation

public enum MSObjectType : String {
    case customentity
    case customentitymetadata
    case attributemetadata
	case product
	case productfolder
	case consignment
	case variant
	case store
	case counterparty
	case organization
	case employee
	case companysettings
	case contract
	case project
	case state
	case currency
	case retailstore
	case demand
	case customerorder
	case invoiceout
	case invoicein
	case retailshift
	case retaildemand
	case retailsalesreturn
	case retailcashin
	case retailcashout
	case dashboard
	case stock
	case group
	case account
    case salesreturn
    case invoiceposition
    case customerorderposition
    case demandposition
    case purchaseorder
    case paymentin
    case cashin
    case service
    case factureout
    case salesbyproduct
    case bundle
    case bundlecomponent
    case embeddedtemplate
    case customtemplate
    case contactperson
    case uom
    case ordersstatistics
    case salesplotseries
    case ordersplotseries
    case moneyplotseries
    case retailstoreshift
    case task
}

Add ObjectType: paymentout and cashout

//
//  Types.swift
//  MoyskladNew
//
//  Created by Andrey Parshakov on 14.10.16.
//  Copyright © 2016 Andrey Parshakov. All rights reserved.
//

import Foundation

public enum MSObjectType : String {
    case customentity
    case customentitymetadata
    case attributemetadata
	case product
	case productfolder
	case consignment
	case variant
	case store
	case counterparty
	case organization
	case employee
	case companysettings
	case contract
	case project
	case state
	case currency
	case retailstore
	case demand
	case customerorder
	case invoiceout
	case invoicein
	case retailshift
	case retaildemand
	case retailsalesreturn
	case retailcashin
	case retailcashout
	case dashboard
	case stock
	case group
	case account
    case salesreturn
    case invoiceposition
    case customerorderposition
    case demandposition
    case purchaseorder
    case paymentin
    case paymentout
    case cashin
    case cashout
    case service
    case factureout
    case salesbyproduct
    case bundle
    case bundlecomponent
    case embeddedtemplate
    case customtemplate
    case contactperson
    case uom
    case ordersstatistics
    case salesplotseries
    case ordersplotseries
    case moneyplotseries
    case retailstoreshift
    case task
}


//
//  Copyright (c) 2015 Itty Bitty Apps. All rights reserved.
//

import Foundation

private enum Attributes: String {
  case Title = "title"
  case Rows = "rows"
}

struct CollectableGroup<I: Collectable>: Collection {
  typealias T = I

  let items: [I]
  let title: String?

  init(dictionary: [String: AnyObject]) {
    guard let rowsData = dictionary[Attributes.Rows.rawValue] as? [[String: AnyObject]] else {
      fatalError("Unable to deserialize Group rows")
    }

    self.title = dictionary[Attributes.Title.rawValue] as? String
    self.items = rowsData.map { I(dictionary: $0) }
  }
}

Remove items that aren't supported by the version of iOS.

//
//  Copyright (c) 2015 Itty Bitty Apps. All rights reserved.
//

import Foundation

private enum Attributes: String {
  case Title = "title"
  case Rows = "rows"
}

struct CollectableGroup<I: Collectable>: Collection {
  typealias T = I

  let items: [I]
  let title: String?

  init(dictionary: [String: AnyObject]) {
    guard let rowsData = dictionary[Attributes.Rows.rawValue] as? [[String: AnyObject]] else {
      fatalError("Unable to deserialize Group rows")
    }

    self.title = dictionary[Attributes.Title.rawValue] as? String
    let unfilteredItems = rowsData.map { I(dictionary: $0) }
    self.items = unfilteredItems.filter { (element) -> Bool in
      if let requiredClassName = element.requiredClassName {
        return nil != NSClassFromString(requiredClassName)
      }

      return true
    }
  }
}


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

// MARK: - Optional conjunction

/// Returns a tuple of two `Optional` values, or `nil` if either or both are `nil`.
public func &&& <T, U> (left: T?, right: U?) -> (T, U)? {
	return left.map { x in right.map { y in (x, y) } } ?? nil
}

// MARK: - Operators

infix operator &&& {
	/// Same associativity as &&.
	associativity left

	/// Same precedence as &&.
	precedence 120
}

Use @autoclosure for the right operand.

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

// MARK: - Optional conjunction

/// Returns a tuple of two `Optional` values, or `nil` if either or both are `nil`.
public func &&& <T, U> (left: T?, @autoclosure right: () -> U?) -> (T, U)? {
	if let x = left, let y = right() {
		return (x, y)
	}
	return nil
}

// MARK: - Operators

infix operator &&& {
	/// Same associativity as &&.
	associativity left

	/// Same precedence as &&.
	precedence 120
}


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

public enum Telescope {
	indirect case Recursive(Telescope)
	indirect case Argument(Term, Telescope)
	case End

	public func fold(recur: Term, terminal: Term, index: Int = 0, combine: (Term, Term) -> Term) -> Term {
		switch self {
		case .End:
			return terminal
		case let .Recursive(rest):
			return combine(recur, rest.fold(recur, terminal: terminal, index: index + 1, combine: combine))
		case let .Argument(type, rest):
			return (Name.Local(index), type) => rest.fold(recur, terminal: terminal, index: index + 1, combine: combine)
		}
	}
}

Remove the default value for the index parameter in `fold`.

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

public enum Telescope {
	indirect case Recursive(Telescope)
	indirect case Argument(Term, Telescope)
	case End

	public func fold(recur: Term, terminal: Term, index: Int, combine: (Term, Term) -> Term) -> Term {
		switch self {
		case .End:
			return terminal
		case let .Recursive(rest):
			return combine(recur, rest.fold(recur, terminal: terminal, index: index + 1, combine: combine))
		case let .Argument(type, rest):
			return (Name.Local(index), type) => rest.fold(recur, terminal: terminal, index: index + 1, combine: combine)
		}
	}
}


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

import RxCocoa
import RxMoya
import RxSwift
import Swiftz

struct SearchedMangaCollectionViewModel {
  private let _fetching = Variable(false)
  private let provider = RxMoyaProvider<YomuAPI>()
  private let _mangas = Variable(List<SearchedMangaViewModel>())

  var count: Int {
    return _mangas.value.count
  }

  var mangas: Driver<List<SearchedMangaViewModel>> {
    return _mangas.asDriver()
  }

  subscript(index: Int) -> SearchedMangaViewModel {
    return _mangas.value[UInt(index)]
  }

  func search(term: String) -> Disposable {
    let api = YomuAPI.Search(term)

    return provider
      .request(api)
      .doOn { self._fetching.value = !$0.isStopEvent }
      .filterSuccessfulStatusCodes()
      .mapArray(SearchedManga.self, withRootKey: "mangas")
      .subscribeNext {
        self._mangas.value = List(fromArray: $0).map(SearchedMangaViewModel.init)
      }
  }
}

Add flag to show view controller

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

import RxCocoa
import RxMoya
import RxSwift
import Swiftz

struct SearchedMangaCollectionViewModel {
  private let _fetching = Variable(false)
  private let _showViewController = Variable(false)
  private let provider = RxMoyaProvider<YomuAPI>()
  private let _mangas = Variable(List<SearchedMangaViewModel>())

  var count: Int {
    return _mangas.value.count
  }

  var mangas: Driver<List<SearchedMangaViewModel>> {
    return _mangas.asDriver()
  }

  var showViewController: Driver<Bool> {
    return _showViewController.asDriver()
  }

  subscript(index: Int) -> SearchedMangaViewModel {
    return _mangas.value[UInt(index)]
  }

  func search(term: String) -> Disposable {
    let api = YomuAPI.Search(term)

    return provider
      .request(api)
      .doOn { self._fetching.value = !$0.isStopEvent }
      .filterSuccessfulStatusCodes()
      .mapArray(SearchedManga.self, withRootKey: "mangas")
      .subscribeNext {
        self._mangas.value = List(fromArray: $0).map(SearchedMangaViewModel.init)
      }
  }

  func hideViewController() {
    _showViewController.value = false
  }
}


//
//  XCGLogger+Logentries.swift
//
//  Created by Brian Batchelder on 1/7/16.
//  Copyright © 2016 Brian's Brain. All rights reserved.
//

import XCGLogger
import le

extension XCGLogger {

    open class XCGLogentriesLogDestination: XCGBaseLogDestination {
        open var leLog: LELog

        public init(leLog : LELog, owner: XCGLogger, identifier: String = "com.cerebralgardens.xcglogger.logdestination.logentries") {
            self.leLog = leLog
            super.init(owner: owner, identifier : identifier)
        }

        open override func output(_ logDetails: XCGLogDetails, text: String) {
            leLog.log(UIDevice.currentDevice().identifierForVendor!.UUIDString + ": " + text)
        }
    }
}

Update for new versions of XCGLogger and le_ios

//
//  XCGLogger+Logentries.swift
//
//  Created by Brian Batchelder on 1/7/16.
//  Copyright © 2016 Brian's Brain. All rights reserved.
//

import XCGLogger
import le

extension XCGLogger {

    open class XCGLogentriesLogDestination: BaseDestination {
        open var leLog: LELog

        public init(leLog : LELog, owner: XCGLogger, identifier: String = "com.cerebralgardens.xcglogger.logdestination.logentries") {
            self.leLog = leLog
            super.init(owner: owner, identifier : identifier)
        }

        open override func output(logDetails: LogDetails, message: String) {
            let logOutput = (UIDevice.current.identifierForVendor?.uuidString)! + ": " + message
            leLog.log(logOutput as NSObject!)
        }
    }
}


import UIKit

public extension UIView {

    public func updateLayoutTo(_ layoutClosure: (UIViewLayout) -> ()) {
        let layout = UIViewLayout(view: self)
        layoutClosure(layout)

        layout.executeAddSubviews()

        let newConstraints = layout.allconstraints()
        let currentConstraints = allConstraintsRecursively(fromView: self)

        var constraintsToRemove = currentConstraints
        var constraintsToActivate = newConstraints

        for constraint in newConstraints {
            let matchingConstraints = currentConstraints.filter { $0 == constraint }

            if let matchingConstraint = matchingConstraints.first {
                if let index = constraintsToRemove.index(of: matchingConstraint) {
                    constraintsToRemove.remove(at: index)
                }

                if let index = constraintsToActivate.index(of: constraint) {
                    constraintsToActivate.remove(at: index)
                }

                if matchingConstraint.constant != constraint.constant {
                    matchingConstraint.constant = constraint.constant
                }

                if matchingConstraint.priority != constraint.priority {
                    matchingConstraint.priority = constraint.priority
                }
            }
        }

        NSLayoutConstraint.deactivate(constraintsToRemove)
        NSLayoutConstraint.activate(constraintsToActivate)
    }

    private func allConstraintsRecursively(fromView view: UIView) -> [NSLayoutConstraint] {
        return view.constraints + view.subviews.flatMap { allConstraintsRecursively(fromView: $0) }
    }
}

Set identifier on constraint if needed

import UIKit

public extension UIView {

    public func updateLayoutTo(_ layoutClosure: (UIViewLayout) -> ()) {
        let layout = UIViewLayout(view: self)
        layoutClosure(layout)

        layout.executeAddSubviews()

        let newConstraints = layout.allconstraints()
        let currentConstraints = allConstraintsRecursively(fromView: self)

        var constraintsToRemove = currentConstraints
        var constraintsToActivate = newConstraints

        for constraint in newConstraints {
            let matchingConstraints = currentConstraints.filter { $0 == constraint }

            if let matchingConstraint = matchingConstraints.first {
                if let index = constraintsToRemove.index(of: matchingConstraint) {
                    constraintsToRemove.remove(at: index)
                }

                if let index = constraintsToActivate.index(of: constraint) {
                    constraintsToActivate.remove(at: index)
                }

                if matchingConstraint.constant != constraint.constant {
                    matchingConstraint.constant = constraint.constant
                }

                if matchingConstraint.priority != constraint.priority {
                    matchingConstraint.priority = constraint.priority
                }

                if matchingConstraint.identifier != constraint.identifier {
                    matchingConstraint.identifier = constraint.identifier
                }
            }
        }

        NSLayoutConstraint.deactivate(constraintsToRemove)
        NSLayoutConstraint.activate(constraintsToActivate)
    }

    private func allConstraintsRecursively(fromView view: UIView) -> [NSLayoutConstraint] {
        return view.constraints + view.subviews.flatMap { allConstraintsRecursively(fromView: $0) }
    }
}


//
//  LocalizationUtils.swift
//  Pageboy
//
//  Created by Merrick Sapsford on 18/06/2017.
//  Copyright © 2017 Merrick Sapsford. All rights reserved.
//

import UIKit

extension UIView {

    /// Whether the layout direction of the view is right to left.
    var layoutIsRightToLeft: Bool {
        if #available(iOS 9.0, *) {
            return UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute) == .rightToLeft
        } else {
            // Fallback on earlier versions
            return false
        }
    }

}

Add RtL language support for iOS 8 fallback

//
//  LocalizationUtils.swift
//  Pageboy
//
//  Created by Merrick Sapsford on 18/06/2017.
//  Copyright © 2017 Merrick Sapsford. All rights reserved.
//

import UIKit

extension UIView {

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

}