import Files // package: https://github.com/JohnSundell/Files.git

import Foundation
import Danger

let danger = Danger()

let allSourceFiles = danger.git.modifiedFiles + danger.git.createdFiles

let changelogChanged = allSourceFiles.contains("CHANGELOG.md")
let sourceChanges = allSourceFiles.first(where: { $0.hasPrefix("Sources") })
let isTrivial = danger.github.pullRequest.title.contains("#trivial")

if (danger.git.createdFiles.count + danger.git.modifiedFiles.count - danger.git.deletedFiles.count > 10) {
    warn("Big PR, try to keep changes smaller if you can")
}

if !isTrivial && !changelogChanged && sourceChanges != nil {
    warn("""
     Any changes to library code should be reflected in the Changelog.

     Please consider adding a note there and adhere to the [Changelog Guidelines](https://github.com/Moya/contributors/blob/master/Changelog%20Guidelines.md).
    """)
}

if danger.github.pullRequest.title.contains("WIP") {
    warn("PR is classed as Work in Progress")
}

message("It works!")

Revert "add a dummy it works line to dangerfile to make sure it prints something"


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

import UIKit

public extension UIViewController {

    public var topMostViewController: UIViewController {
        if presentedViewController == nil {
            return self
        }
        if let navigation = presentedViewController as? UINavigationController {
            if let visible = navigation.visibleViewController {
                return visible.topMostViewController
            }
            if let top = navigation.topViewController {
                return top.topMostViewController
            }
            return navigation.topMostViewController
        }
        if let tab = presentedViewController as? UITabBarController {
            if let selectedTab = tab.selectedViewController {
                return selectedTab.topMostViewController
            }
            return tab.topMostViewController
        }
        return presentedViewController!.topMostViewController
    }

}

public extension UIApplication {

    public var topMostViewController: UIViewController? {
        return keyWindow?.rootViewController?.topMostViewController
    }

}

Allow for overridding top most view controller

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

import UIKit

extension UIViewController {

    open var topMostViewController: UIViewController {
        if presentedViewController == nil {
            return self
        }
        if let navigation = presentedViewController as? UINavigationController {
            if let visible = navigation.visibleViewController {
                return visible.topMostViewController
            }
            if let top = navigation.topViewController {
                return top.topMostViewController
            }
            return navigation.topMostViewController
        }
        if let tab = presentedViewController as? UITabBarController {
            if let selectedTab = tab.selectedViewController {
                return selectedTab.topMostViewController
            }
            return tab.topMostViewController
        }
        return presentedViewController!.topMostViewController
    }

}

public extension UIApplication {

    public var topMostViewController: UIViewController? {
        return keyWindow?.rootViewController?.topMostViewController
    }

}


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

final class TypeDifferentialTests: XCTestCase {

	// MARK: Patching

	func testEmptyDiffIsIdempotent() {
		assert(TypeDifferential.Empty.apply(Term.Bool), ==, Term.Bool)
	}

	func testUnitDiffReplacesOtherConstructors() {
		assert(TypeDifferential.Patch(Type.constructed(.Unit)).apply(Term.Bool), ==, Term.Unit)
	}
}

import Assertions
import Manifold
import TesseractCore
import XCTest

Test that constructors are not mutually exclusive with variables.

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

final class TypeDifferentialTests: XCTestCase {

	// MARK: Patching

	func testEmptyDiffIsIdempotent() {
		assert(TypeDifferential.Empty.apply(Term.Bool), ==, Term.Bool)
	}

	func testUnitDiffReplacesOtherConstructors() {
		assert(TypeDifferential.Patch(Type.constructed(.Unit)).apply(Term.Bool), ==, Term.Unit)
	}

	func testUnitDiffDoesNotReplaceVariables() {
		assert(TypeDifferential.Patch(Type.constructed(.Unit)).apply(0), ==, 0)
	}
}

import Assertions
import Manifold
import TesseractCore
import XCTest


import PackageDescription
import Foundation

let package = Package(
    name: "LibStorj",
    targets: [
        Target(name: "LibStorj")
    ],
    dependencies: [
        .Package(url: "https://github.com/Ybrin/CLibStorj.git", majorVersion: 1),
        .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1, 0, 0)..<Version(3, .max, .max))
    ],
    exclude: []
)

Update to SPM v4 format

// swift-tools-version:4.0
import PackageDescription
import Foundation

let package = Package(
    name: "LibStorj",
    products: [
        .library(name: "LibStorj", targets: ["LibStorj"]),
    ],
    dependencies: [
        .package(url: "https://github.com/Ybrin/CLibStorj.git", from: "1.0.0"),
        .package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", from: "3.0.0"),
    ],
    targets: [
        .target(name: "LibStorj", dependencies: ["CLibStorj", "SwiftyJSON"]),
        .testTarget(name: "LibStorjTests", dependencies: ["LibStorj"]),
    ],
    swiftLanguageVersions: [3]
)


// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "SRP",
    dependencies: [
        .package(url: "https://github.com/IBM-Swift/BlueCryptor.git", from: "0.8.16"),
        .package(url: "https://github.com/lorentey/BigInt.git", .branch("swift4")),
    ],
    targets: [
        .target(name: "SRP", dependencies: ["Cryptor", "BigInt"], path: "Sources"),
        .testTarget(name: "SRPTests", dependencies: ["Cryptor", "SRP"]),
    ],
    swiftLanguageVersions: [4]
)

Upgrade to BigInt 3 (Swift 4)

// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "SRP",
    dependencies: [
        .package(url: "https://github.com/IBM-Swift/BlueCryptor.git", from: "0.8.16"),
        .package(url: "https://github.com/lorentey/BigInt.git", from: "3.0.0"),
    ],
    targets: [
        .target(name: "SRP", dependencies: ["Cryptor", "BigInt"], path: "Sources"),
        .testTarget(name: "SRPTests", dependencies: ["Cryptor", "SRP"]),
    ],
    swiftLanguageVersions: [4]
)


//
//  User.swift
//  PartyUP
//
//  Created by Fritz Vander Heide on 2016-06-30.
//  Copyright © 2016 Sandcastle Application Development. All rights reserved.
//

import Foundation
import FBSDKCoreKit

class User {
	var aliases = [NSLocalizedString("Anonymous Milquetoast", comment: "anonymous user moniker")]

	init() {
		refresh()

		NSNotificationCenter.defaultCenter().addObserverForName(FBSDKAccessTokenDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in self.refresh() }
	}

	func refresh() {
		if let token = FBSDKAccessToken.currentAccessToken() where token.hasGranted("public_profile") {
			FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields":"name"]).startWithCompletionHandler({ (connection, profile, error) in
				if error == nil {
                    if let name = profile["name"] as? String {
                        self.aliases.append(name)
                    }
				}
			})
		}
	}
}

Remove an unnecessary explicit call to init.

//
//  User.swift
//  PartyUP
//
//  Created by Fritz Vander Heide on 2016-06-30.
//  Copyright © 2016 Sandcastle Application Development. All rights reserved.
//

import Foundation
import FBSDKCoreKit

class User {
	var aliases = [NSLocalizedString("Anonymous Milquetoast", comment: "anonymous user moniker")]

	init() {
		refresh()

		NSNotificationCenter.defaultCenter().addObserverForName(FBSDKAccessTokenDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in self.refresh() }
	}

	func refresh() {
		if let token = FBSDKAccessToken.currentAccessToken() where token.hasGranted("public_profile") {
			FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"name"]).startWithCompletionHandler({ (connection, profile, error) in
				if error == nil {
                    if let name = profile["name"] as? String {
                        self.aliases.append(name)
                    }
				}
			})
		}
	}
}


//
//  ScheduleDayCollectionViewCell.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 14/06/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import UIKit

class ScheduleDayCollectionViewCell: UICollectionViewCell, ScheduleDayComponent {

    @IBOutlet weak var selectedDecorationView: UIView!
    @IBOutlet weak var dayTitleLabel: UILabel!

    override var isSelected: Bool {
        didSet {
            selectedDecorationView.isHidden = !isSelected
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        selectedDecorationView.isHidden = true
    }

    func setDayTitle(_ title: String) {
        dayTitleLabel.text = title
    }

}

Update alpha value of decoration view on selection

//
//  ScheduleDayCollectionViewCell.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 14/06/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import UIKit

class ScheduleDayCollectionViewCell: UICollectionViewCell, ScheduleDayComponent {

    @IBOutlet weak var selectedDecorationView: UIView!
    @IBOutlet weak var dayTitleLabel: UILabel!

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

    override func awakeFromNib() {
        super.awakeFromNib()
        updateDecorationViewVisibility()
    }

    private func updateDecorationViewVisibility() {
        selectedDecorationView.alpha = isSelected ? 1 : 0
    }

    func setDayTitle(_ title: String) {
        dayTitleLabel.text = title
    }

}


//
//  Reactive+UIButton.swift
//  Pods
//
//  Created by Jeff Verkoeyen on 5/11/17.
//
//

import Foundation

Add a reactive button target type and an initial isHighlighted stream.

/*
 Copyright 2017-present The Material Motion Authors. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import Foundation
import UIKit

/**
 A reactive button target exposes streams for certain button events.
 */
public final class ReactiveButtonTarget: NSObject {
  public init(_ button: UIButton) {
    super.init()

    button.addTarget(self, action: #selector(didEnterEvent),
                     for: [.touchDown, .touchDragInside])
    button.addTarget(self, action: #selector(didExitEvent),
                     for: [.touchUpInside, .touchUpOutside, .touchDragOutside])
  }

  // MARK: Streams

  /**
   Emits true when the button should be highlighted and false when it should not.
   */
  public var didHighlight: MotionObservable<Bool> {
    return MotionObservable { observer in
      self.didHighlightObservers.append(observer)
      return {
        if let index = self.didHighlightObservers.index(where: { $0 === observer }) {
          self.didHighlightObservers.remove(at: index)
        }
      }
    }
  }

  func didEnterEvent(_ button: UIButton) {
    didHighlightObservers.forEach { $0.next(true) }
  }
  func didExitEvent(_ button: UIButton) {
    didHighlightObservers.forEach { $0.next(false) }
  }
  private var didHighlightObservers: [MotionObserver<Bool>] = []

  public let metadata = Metadata("Button target")
}


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

import UIKit
import Fabric
import Crashlytics

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

}

Clear database if migration is required

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

import UIKit
import Fabric
import Crashlytics
import RealmSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        Fabric.with([Crashlytics.self])

        Realm.Configuration.defaultConfiguration = Realm.Configuration(
            deleteRealmIfMigrationNeeded: true
        )

        return true
    }

}


//
//  UISwitch+Rx.swift
//  RxCocoa
//
//  Created by Carlos García on 8/7/15.
//  Copyright © 2015 Krunoslav Zaher. All rights reserved.
//

#if os(iOS)

import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif

extension Reactive where Base: UISwitch {

    /// Reactive wrapper for `isOn` property.
    public var isOn: ControlProperty<Bool> {
        return value
    }

    /**
    Reactive wrapper for `isOn` property.

    **⚠ Versions prior to iOS 10.2 were leaking `UIButton`s, so on those versions
     underlying observable sequence won't complete when nothing holds a strong reference
     to UISwitch.⚠**
    */
    public var value: ControlProperty<Bool> {
        return UIControl.rx.value(
            self.base,
            getter: { uiSwitch in
                uiSwitch.isOn
            }, setter: { uiSwitch, value in
                uiSwitch.isOn = value
            }
        )
    }

}

#endif

Fix UISwitch documentation referencing UIButton

//
//  UISwitch+Rx.swift
//  RxCocoa
//
//  Created by Carlos García on 8/7/15.
//  Copyright © 2015 Krunoslav Zaher. All rights reserved.
//

#if os(iOS)

import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif

extension Reactive where Base: UISwitch {

    /// Reactive wrapper for `isOn` property.
    public var isOn: ControlProperty<Bool> {
        return value
    }

    /**
    Reactive wrapper for `isOn` property.

    **⚠ Versions prior to iOS 10.2 were leaking `UISwitch`s, so on those versions
     underlying observable sequence won't complete when nothing holds a strong reference
     to UISwitch.⚠**
    */
    public var value: ControlProperty<Bool> {
        return UIControl.rx.value(
            self.base,
            getter: { uiSwitch in
                uiSwitch.isOn
            }, setter: { uiSwitch, value in
                uiSwitch.isOn = value
            }
        )
    }

}

#endif


//
//  JSONEncodable.swift
//  CesiumKit
//
//  Created by Ryan Walklin on 29/02/2016.
//  Copyright © 2016 Test Toast. All rights reserved.
//

import Foundation

protocol JSONEncodable {

    init (json: JSONObject) throws

    func toJSON () -> JSONObject
}

Use JSON rather than JSONObject directly

//
//  JSONEncodable.swift
//  CesiumKit
//
//  Created by Ryan Walklin on 29/02/2016.
//  Copyright © 2016 Test Toast. All rights reserved.
//

import Foundation

protocol JSONEncodable {

    init (fromJSON json: JSON) throws

    func toJSON () -> JSON
}


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

extension Module {
	public static var maybe: Module {
		let Maybe = Declaration.Datatype("Maybe", .Argument(.Type, {
			[
				"just": .Argument($0, const(.End)),
				"nothing": .End
			]
		}))

		let just: Term = "just"
		let nothing: Term = "nothing"
		let map = Declaration("Maybe.map",
			type: (.Type, .Type) => { A, B in (A --> B) --> Maybe.ref[A] --> Maybe.ref[B] },
			value: { A, B in (A --> B, nil) => { transform, maybe in maybe[Maybe.ref[B], () => { just[transform[$0]] }, nothing[B]] } })

		return Module("Maybe", [ Maybe, map ])
	}
}

import Prelude

Apply `just` to the type parameter.

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

extension Module {
	public static var maybe: Module {
		let Maybe = Declaration.Datatype("Maybe", .Argument(.Type, {
			[
				"just": .Argument($0, const(.End)),
				"nothing": .End
			]
		}))

		let just: Term = "just"
		let nothing: Term = "nothing"
		let map = Declaration("Maybe.map",
			type: (.Type, .Type) => { A, B in (A --> B) --> Maybe.ref[A] --> Maybe.ref[B] },
			value: { A, B in (A --> B, nil) => { transform, maybe in maybe[Maybe.ref[B], () => { just[B, transform[$0]] }, nothing[B]] } })

		return Module("Maybe", [ Maybe, map ])
	}
}

import Prelude


//
//  Venue.swift
//  VenueMap
//
//  Created by koogawa on 2015/07/21.
//  Copyright (c) 2015年 Kosuke Ogawa. All rights reserved.
//

import UIKit
import SwiftyJSON

let kCategoryIconSize = 88  // pixel

struct Venue: Printable {

    let venueId: NSString?
    let name: String?
    let address: String?
    let latitude: Double?
    let longitude: Double?
    let categoryIconURL: NSURL?

    var description: String {
        return "<venueId=\(venueId)"
            + ", name=\(name)"
            + ", address=\(address)"
            + ", latitude=\(latitude), longitude=\(longitude)"
            + ", categoryIconURL=\(categoryIconURL)>"
    }

    init(json: JSON) {

        self.venueId = json["id"].string
        self.name = json["name"].string
        self.address = json["location"]["address"].string
        self.latitude = json["location"]["lat"].double
        self.longitude = json["location"]["lng"].double

        // Primary Category
        if json["categories"].array?.count > 0 {
            let prefix = json["categories"][0]["icon"]["prefix"].string
            let suffix = json["categories"][0]["icon"]["suffix"].string
            let iconUrlString = NSString(format: "%@%d%@", prefix!, kCategoryIconSize, suffix!)
            self.categoryIconURL = NSURL(string: iconUrlString as String)
        }
        else {
            self.categoryIconURL = nil
        }
    }
}

Change venueId type: NSString -> String

//
//  Venue.swift
//  VenueMap
//
//  Created by koogawa on 2015/07/21.
//  Copyright (c) 2015年 Kosuke Ogawa. All rights reserved.
//

import UIKit
import SwiftyJSON

let kCategoryIconSize = 88  // pixel

struct Venue: Printable {

    let venueId: String?
    let name: String?
    let address: String?
    let latitude: Double?
    let longitude: Double?
    let categoryIconURL: NSURL?

    var description: String {
        return "<venueId=\(venueId)"
            + ", name=\(name)"
            + ", address=\(address)"
            + ", latitude=\(latitude), longitude=\(longitude)"
            + ", categoryIconURL=\(categoryIconURL)>"
    }

    init(json: JSON) {

        self.venueId = json["id"].string
        self.name = json["name"].string
        self.address = json["location"]["address"].string
        self.latitude = json["location"]["lat"].double
        self.longitude = json["location"]["lng"].double

        // Primary Category
        if json["categories"].array?.count > 0 {
            let prefix = json["categories"][0]["icon"]["prefix"].string
            let suffix = json["categories"][0]["icon"]["suffix"].string
            let iconUrlString = NSString(format: "%@%d%@", prefix!, kCategoryIconSize, suffix!)
            self.categoryIconURL = NSURL(string: iconUrlString as String)
        }
        else {
            self.categoryIconURL = nil
        }
    }
}


import Foundation

public final class Configuration {

    public static var headersWithBoldTrait = false

    static var defaultBoldFormatter: AttributeFormatter = {
        if headersWithBoldTrait {
            return BoldWithShadowForHeadingFormatter()
        } else {
            return BoldFormatter()
        }
    } ()
}

Create a formatter for each call.

import Foundation

public final class Configuration {

    public static var headersWithBoldTrait = false

    static var defaultBoldFormatter: AttributeFormatter {
        get {
            if headersWithBoldTrait {
                return BoldWithShadowForHeadingFormatter()
            } else {
                return BoldFormatter()
            }
        }
    }
}


//
//  RemoteNotificationServiceDefault.swift
//  iExtra
//
//  Created by Daniel Saidi on 2015-10-24.
//  Copyright © 2018 Daniel Saidi. All rights reserved.
//

import UserNotifications

open class RemoteNotificationServiceDefault: NSObject, RemoteNotificationService {

    open func alert(notification: [AnyHashable: Any]) {
        let app = UIApplication.shared
        guard let aps = notification["aps"] as? [AnyHashable: Any] else { return }
        let text = aps["alert"] as? String
        if app.applicationState == .active && text != nil {
            let alert: UIAlertController = UIAlertController(title: nil, message: text, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            app.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
        }
    }

    open func getDeviceToken(from deviceTokenData: Data) -> String {
        let token = deviceTokenData as NSData
        let tokenChars = token.bytes.bindMemory(to: CChar.self, capacity: deviceTokenData.count)
        var tokenString = ""
        for i in 0..<deviceTokenData.count {
            tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
        }
        return tokenString
    }

    open func handle(notification: [AnyHashable: Any]) {
        alert(notification: notification)
    }

    open func registerForRemoteNotifications() {
        // Implement in app
    }
}

Add fatal error for missing notification override

//
//  RemoteNotificationServiceDefault.swift
//  iExtra
//
//  Created by Daniel Saidi on 2015-10-24.
//  Copyright © 2018 Daniel Saidi. All rights reserved.
//

import UserNotifications

open class RemoteNotificationServiceDefault: NSObject, RemoteNotificationService {

    open func alert(notification: [AnyHashable: Any]) {
        let app = UIApplication.shared
        guard let aps = notification["aps"] as? [AnyHashable: Any] else { return }
        let text = aps["alert"] as? String
        if app.applicationState == .active && text != nil {
            let alert: UIAlertController = UIAlertController(title: nil, message: text, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            app.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
        }
    }

    open func getDeviceToken(from deviceTokenData: Data) -> String {
        let token = deviceTokenData as NSData
        let tokenChars = token.bytes.bindMemory(to: CChar.self, capacity: deviceTokenData.count)
        var tokenString = ""
        for i in 0..<deviceTokenData.count {
            tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
        }
        return tokenString
    }

    open func handle(notification: [AnyHashable: Any]) {
        alert(notification: notification)
    }

    open func registerForRemoteNotifications() {
        fatalError("registerForRemoteNotifications must be implemented in your app")
    }
}


import UIKit

protocol MMenuItemProtocol
{
    var icon:UIImage { get }
    var order:MMenu.Order { get }

    init(order:MMenu.Order)

    func controller(session:MSession) -> UIViewController
}

Add associated types to protocol

import UIKit

protocol MMenuItemProtocol
{
    associatedtype V:ViewMain
    associatedtype M:Model<Self.V>
    associatedtype C:Controller<Self.V, Self.M>

    var icon:UIImage { get }
    var order:MMenu.Order { get }
    var controller:C.Type { get }

    init(order:MMenu.Order)
}


import Foundation

func generatePermutations(of a: inout [Character], upTo n: Int) {
    if n == 0 {
        print(String(a))
    } else {
        for i in 0..<n {
            generatePermutations(of: &a, upTo: n-1)
            a.swapAt(n % 2 == 0 ? 0 : i, n)
        }
        generatePermutations(of: &a, upTo: n-1)
    }
}

if CommandLine.arguments.count != 2 {
    fputs("Exactly one argument is required\n", __stderrp)
    exit(1)
}
let word = CommandLine.arguments[1]
var charArray = Array(word)
generatePermutations(of: &charArray, upTo: charArray.count-1)

Use stderr instead of __stderrp

import Foundation

func generatePermutations(of a: inout [Character], upTo n: Int) {
    if n == 0 {
        print(String(a))
    } else {
        for i in 0..<n {
            generatePermutations(of: &a, upTo: n-1)
            a.swapAt(n % 2 == 0 ? 0 : i, n)
        }
        generatePermutations(of: &a, upTo: n-1)
    }
}

if CommandLine.arguments.count != 2 {
    fputs("Exactly one argument is required\n", stderr)
    exit(1)
}
let word = CommandLine.arguments[1]
var charArray = Array(word)
generatePermutations(of: &charArray, upTo: charArray.count-1)


//
//  Parent.swift
//  AccordionMenu
//
//  Created by Victor on 7/6/16.
//  Copyright © 2016 Victor Sigler. All rights reserved.
//

/**
 Define the state of a cell

 - Collapsed: Cell collapsed
 - Expanded:  Cell expanded
 */
public enum State {
    case collapsed
    case expanded
}

/**
 Enum to define the number of cell expanded at time

 - One:     One cell expanded at time.
 - Several: Several cells expanded at time.
 */
public enum NumberOfCellExpanded {
    case one
    case several
}

/**
 *  The Parent struct of the data source.
 */
public struct Parent {

    /// State of the cell
    var state: State

    /// The childs of the cell
    var childs: [String]

    /// The title for the cell.
    var title: String

    public init(state: State, childs: [String], title: String) {
        self.state = state
        self.childs = childs
        self.title = title
    }
}

/**
 Overload for the operator != for tuples

 - parameter lhs: The first tuple to compare
 - parameter rhs: The seconde tuple to compare

 - returns: true if there are different, otherwise false
 */
public func != (lhs: (Int, Int), rhs: (Int, Int)) -> Bool {
    return lhs.0 != rhs.0 && rhs.1 != lhs.1
}

Remove extra space to test TravisCI build


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

@exported import AssetsLibrary // Clang module

//===----------------------------------------------------------------------===//
// ALAssetsLibrary.h
//===----------------------------------------------------------------------===//
extension ALAssetsLibrary {
  public func enumerateGroupsWithTypes(var types: UInt32,
      usingBlock enumerationBlock: ALAssetsLibraryGroupsEnumerationResultsBlock!,
      failureBlock: ALAssetsLibraryAccessFailureBlock!) {
    if (types == ALAssetsGroupAll) {
      types = ALAssetsGroupLibrary | ALAssetsGroupAlbum | ALAssetsGroupEvent |
              ALAssetsGroupFaces | ALAssetsGroupSavedPhotos |
              ALAssetsGroupPhotoStream
    }
    return enumerateGroupsWithTypes(ALAssetsGroupType(types),
                                    usingBlock: enumerationBlock,
                                    failureBlock)

  }
}

Add missing keyword argument following changes for rdar://problem/18778670

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

@exported import AssetsLibrary // Clang module

//===----------------------------------------------------------------------===//
// ALAssetsLibrary.h
//===----------------------------------------------------------------------===//
extension ALAssetsLibrary {
  public func enumerateGroupsWithTypes(var types: UInt32,
      usingBlock enumerationBlock: ALAssetsLibraryGroupsEnumerationResultsBlock!,
      failureBlock: ALAssetsLibraryAccessFailureBlock!) {
    if (types == ALAssetsGroupAll) {
      types = ALAssetsGroupLibrary | ALAssetsGroupAlbum | ALAssetsGroupEvent |
              ALAssetsGroupFaces | ALAssetsGroupSavedPhotos |
              ALAssetsGroupPhotoStream
    }
    return enumerateGroupsWithTypes(ALAssetsGroupType(types),
                                    usingBlock: enumerationBlock,
                                    failureBlock: failureBlock)

  }
}


//
//  UIActivity.swift
//  ActivityKit
//
//  Created by Chrisna Aing on 6/14/16.
//  Copyright © 2016 Chrisna. All rights reserved.
//

import UIKit

extension UIActivity {

    @objc(cka_lengthInPointsOfActivityImageFor:)
    func lengthInPointsOfActivityImageFor(traitCollection: UITraitCollection) -> CGFloat {
        switch traitCollection.userInterfaceIdiom {
        case .phone:
            // Full length is 60 points.
            return 50.0
        case .pad:
            // Full length is 76 points.
            return 64.0
        case .carPlay, .TV, .unspecified:
            // Doesn't make sense at this point, so return the same number as we do for phone.
            return 50.0
        }
    }

}

Make "tv" enum case lowercase.

//
//  UIActivity.swift
//  ActivityKit
//
//  Created by Chrisna Aing on 6/14/16.
//  Copyright © 2016 Chrisna. All rights reserved.
//

import UIKit

extension UIActivity {

    @objc(cka_lengthInPointsOfActivityImageFor:)
    func lengthInPointsOfActivityImageFor(traitCollection: UITraitCollection) -> CGFloat {
        switch traitCollection.userInterfaceIdiom {
        case .phone:
            // Full length is 60 points.
            return 50.0
        case .pad:
            // Full length is 76 points.
            return 64.0
        case .carPlay, .tv, .unspecified:
            // Doesn't make sense at this point, so return the same number as we do for phone.
            return 50.0
        }
    }

}


//
//  TwistDelegate.swift
//  Twist
//
//  Created by Jais Cheema on 8/01/2016.
//  Copyright © 2016 Needle Apps. All rights reserved.
//

import Foundation
import AVFoundation

public protocol TwistDelegate {
    func twist(twist: Twist, loaded: NSTimeInterval, outOf totalDuration: NSTimeInterval)
    func twist(twist: Twist, playedTo currentTime: Double, outOf totalDuration: Double)
    func twist(twist: Twist, startedPlayingItemAtIndex itemIndex: Int)
    func twistStateChanged(twist: Twist)
}

public extension TwistDelegate {
    func twist(twist: Twist, loaded: NSTimeInterval, outOf totalDuration: NSTimeInterval) {}
    func twist(twist: Twist, playedTo currentTime: Double, outOf totalDuration: Double) {}
    func twist(twist: Twist, startedPlayingItemAtIndex itemIndex: Int) {}
    func twistStateChanged(twist: Twist) {}
}

Add method to notify of the media url play error and successful download

//
//  TwistDelegate.swift
//  Twist
//
//  Created by Jais Cheema on 8/01/2016.
//  Copyright © 2016 Needle Apps. All rights reserved.
//

import Foundation
import AVFoundation

public protocol TwistDelegate {
    func twist(twist: Twist, loaded: NSTimeInterval, outOf totalDuration: NSTimeInterval)
    func twist(twist: Twist, playedTo currentTime: Double, outOf totalDuration: Double)
    func twist(twist: Twist, startedPlayingItemAtIndex itemIndex: Int)
    func twist(twist: Twist, failedToPlayURL itemURL: NSURL, forItemAtIndex itemIndex: Int)
    func twist(twist: Twist, downloadedMedia fileItemURL: NSURL, forItemAtIndex itemIndex: Int)
    func twistStateChanged(twist: Twist)
}

public extension TwistDelegate {
    func twist(twist: Twist, loaded: NSTimeInterval, outOf totalDuration: NSTimeInterval) {}
    func twist(twist: Twist, playedTo currentTime: Double, outOf totalDuration: Double) {}
    func twist(twist: Twist, startedPlayingItemAtIndex itemIndex: Int) {}
    func twistStateChanged(twist: Twist) {}
    func twist(twist: Twist, downloadedMedia fileItemURL: NSURL, forItemAtIndex itemIndex: Int) {}

    func twist(twist: Twist, failedToPlayURL itemURL: NSURL, forItemAtIndex itemIndex: Int) {
        twist.next()
    }
}


// RUN: %empty-directory(%t)
// RUN: echo 'print("Hello, World!")' >%t/main.swift
// RUN: touch %t/file-01.swift %t/file-02.swift %t/file-03.swift
//
// Ensure that the supplementary output filelist argument is passed to the frontend:
//
// RUN: %swiftc_driver -enable-batch-mode -driver-filelist-threshold=0 -j2 %t/main.swift %t/file-01.swift %t/file-02.swift %t/file-03.swift -o %t/file-01.o -o %t/file-02.o -o %t/file-03.o -### | %FileCheck %s -check-prefix=CHECK-SUPPLEMENTARY-OUTPUT-FILELIST
//
// CHECK-SUPPLEMENTARY-OUTPUT-FILELIST: -supplementary-output-file-map {{.*(/|\\)}}supplementaryOutputs-
//
// XFAIL: OS=windows-msvc

Revert "Driver: mark test as XFAIL on windows"


// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s

func foldl1<T>(list: [T], function: (a: T, b: T) -> T) -> T {
     assert(list.count > 1)
     var accumulator = list[0]
     for var i = 1; i < list.count; ++i {
         accumulator = function(a: accumulator, b: list[i])
     }
     return accumulator
}

var a = [Int](count: 10, repeatedValue: 0)
for i in 0..<10 { a[i] = i }
// A closure is not an artificial function (the last i32 0).
// CHECK: !"0x2e\00\00\00_TF7closureU_FTSiSi_Si\0018\000\001\000\000\000\000\0018", {{.*}}[ DW_TAG_subprogram ]
// CHECK: [ DW_TAG_arg_variable ] [$0] [line [[@LINE+2]]]
// CHECK: [ DW_TAG_arg_variable ] [$1] [line [[@LINE+1]]]
var sum:Int = foldl1(a, { $0 + $1 })
println(sum)

Update this tescase for r25502. Thanks Jordan for noticing.

// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s

func foldl1<T>(list: [T], function: (a: T, b: T) -> T) -> T {
     assert(list.count > 1)
     var accumulator = list[0]
     for var i = 1; i < list.count; ++i {
         accumulator = function(a: accumulator, b: list[i])
     }
     return accumulator
}

var a = [Int](count: 10, repeatedValue: 0)
for i in 0..<10 { a[i] = i }
// A closure is not an artificial function (the last i32 0).
// CHECK: !"0x2e\00_TF7closureU_FTSiSi_Si\00_TF7closureU_FTSiSi_Si\00_TF7closureU_FTSiSi_Si\0018\000\001\000\000\000\000\0018", {{.*}}[ DW_TAG_subprogram ]
// CHECK: [ DW_TAG_arg_variable ] [$0] [line [[@LINE+2]]]
// CHECK: [ DW_TAG_arg_variable ] [$1] [line [[@LINE+1]]]
var sum:Int = foldl1(a, { $0 + $1 })
println(sum)


//
//  Notification.swift
//  ESOcean
//
//  Created by Tomohiro Kumagai on H27/04/23.
//
//

import Foundation

// MARK: - Protocol

/// All native notifications need to confirm to the protocol.
public protocol Notification : NotificationProtocol, Postable {

}

/// All notifications (without NSNotification) need to confirm to the protocol.
public protocol NotificationProtocol : AnyObject {

}

Fix a typo in comment.

//
//  Notification.swift
//  ESOcean
//
//  Created by Tomohiro Kumagai on H27/04/23.
//
//

import Foundation

// MARK: - Protocol

/// All native notifications need to confirm to the protocol.
public protocol Notification : NotificationProtocol, Postable {

}

/// All notifications (without NSNotification) need to conforms to the protocol.
public protocol NotificationProtocol : AnyObject {

}


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

final class TermTests: XCTestCase {
	func testHigherOrderConstruction() {
		let expected = Term(.Pi(1, Box(.type), Box(Term(.Pi(0, Box(Term(.Variable(1))), Box(Term(.Variable(0))))))))
		assert(identity, ==, expected)
	}

	func testTypechecking() {
		assert(identity.typecheck().right?.quote, ==, .lambda(.type, const(.lambda(.type, const(.type)))))
	}

	func testFunctionTypesArePrintedWithAnArrow() {
		assert(identity.typecheck().right?.quote.description, ==, "(Type) → (Type) → Type")
	}

	func testProductTypesArePrintedWithAnX() {
		assert(Term.pair(.type, const(.type)).typecheck().right?.quote.description, ==, "(Type ✕ Type)")
	}

	func testEvaluation() {
		let value = identity.typecheck().flatMap {
			Term.application(Term.application(identity, $0.quote), identity).evaluate().map(Either.right)
				?? Either.left("evaluation returned nil for some reason")
		}
		assert(value.right?.quote, ==, identity)
		assert(value.left, ==, nil)
	}
}

private let identity = Term.lambda(.type) { A in .lambda(A, id) }

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

Correct the test of higher order construction.

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

final class TermTests: XCTestCase {
	func testHigherOrderConstruction() {
		let expected = Term(.Pi(0, Box(.type), Box(Term(.Pi(1, Box(Term(.Variable(0))), Box(Term(.Variable(1))))))))
		assert(identity, ==, expected)
	}

	func testTypechecking() {
		assert(identity.typecheck().right?.quote, ==, .lambda(.type, const(.lambda(.type, const(.type)))))
	}

	func testFunctionTypesArePrintedWithAnArrow() {
		assert(identity.typecheck().right?.quote.description, ==, "(Type) → (Type) → Type")
	}

	func testProductTypesArePrintedWithAnX() {
		assert(Term.pair(.type, const(.type)).typecheck().right?.quote.description, ==, "(Type ✕ Type)")
	}

	func testEvaluation() {
		let value = identity.typecheck().flatMap {
			Term.application(Term.application(identity, $0.quote), identity).evaluate().map(Either.right)
				?? Either.left("evaluation returned nil for some reason")
		}
		assert(value.right?.quote, ==, identity)
		assert(value.left, ==, nil)
	}
}

private let identity = Term.lambda(.type) { A in .lambda(A, id) }

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


import Foundation

protocol MConnectingStatusProtocol
{
    var viewType:View<ArchConnecting>.Type { get }
}

Add button title to protocol

import Foundation

protocol MConnectingStatusProtocol
{
    var viewType:View<ArchConnecting>.Type { get }
    var buttonTitle:String { get }
}


//
//  PusherClientOptions.swift
//  PusherSwift
//
//  Created by Hamilton Chapman on 01/04/2016.
//
//

public enum PusherHost {
    case Host(String)
    case Cluster(String)

    public var stringValue: String {
        switch self {
            case .Host(let host): return host
            case .Cluster(let cluster): return "ws-\(cluster).pusher.com"
        }
    }
}

public enum AuthMethod {
    case Endpoint(authEndpoint: String)
    case Internal(secret: String)
    case NoMethod
}

public struct PusherClientOptions {
    public let authMethod: AuthMethod
    public let attemptToReturnJSONObject: Bool
    public let autoReconnect: Bool
    public let host: String
    public let port: Int
    public let encrypted: Bool

    public init(
        authMethod: AuthMethod = .NoMethod,
        attemptToReturnJSONObject: Bool = true,
        autoReconnect: Bool = true,
        host: PusherHost = .Host("ws.pusherapp.com"),
        port: Int? = nil,
        encrypted: Bool = true) {
            self.authMethod = authMethod
            self.attemptToReturnJSONObject = attemptToReturnJSONObject
            self.autoReconnect = autoReconnect
            self.host = host.stringValue
            self.port = port ?? (encrypted ? 443 : 80)
            self.encrypted = encrypted
    }
}

Add in AuthRequestBuilderProtocol (missed it in the cherry-pick)

//
//  PusherClientOptions.swift
//  PusherSwift
//
//  Created by Hamilton Chapman on 01/04/2016.
//
//

public enum PusherHost {
    case Host(String)
    case Cluster(String)

    public var stringValue: String {
        switch self {
            case .Host(let host): return host
            case .Cluster(let cluster): return "ws-\(cluster).pusher.com"
        }
    }
}

public protocol AuthRequestBuilderProtocol {
    func requestFor(socketID: String, channel: PusherChannel) -> NSMutableURLRequest
}

public enum AuthMethod {
    case Endpoint(authEndpoint: String)
    case AuthRequestBuilder(authRequestBuilder: AuthRequestBuilderProtocol)
    case Internal(secret: String)
    case NoMethod
}

public struct PusherClientOptions {
    public let authMethod: AuthMethod
    public let attemptToReturnJSONObject: Bool
    public let autoReconnect: Bool
    public let host: String
    public let port: Int
    public let encrypted: Bool

    public init(
        authMethod: AuthMethod = .NoMethod,
        attemptToReturnJSONObject: Bool = true,
        autoReconnect: Bool = true,
        host: PusherHost = .Host("ws.pusherapp.com"),
        port: Int? = nil,
        encrypted: Bool = true) {
            self.authMethod = authMethod
            self.attemptToReturnJSONObject = attemptToReturnJSONObject
            self.autoReconnect = autoReconnect
            self.host = host.stringValue
            self.port = port ?? (encrypted ? 443 : 80)
            self.encrypted = encrypted
    }
}


//
//  UDPSocketTests.swift
//  WIFIAV
//
//  Created by Max Odnovolyk on 3/13/17.
//  Copyright © 2017 Max Odnovolyk. All rights reserved.
//

import XCTest
@testable import WIFIAV

class UDPSocketTests: XCTestCase {

    override func setUp() {
        super.setUp()

        continueAfterFailure = false
    }

    func testNotListeningSocketGetsDeallocatedImmediately() {
        var socket: UDPSocket? = try! UDPSocket(port: 55000)
        weak var weakSocket = socket

        XCTAssertNotNil(weakSocket)

        socket = nil

        XCTAssertNil(weakSocket)
    }

    func testListeningSocketGetsDeallocatedAfterShutdown() {
        weak var weakSocket: Socket?

        autoreleasepool {
            var socket: UDPSocket? = try! UDPSocket(port: 55001)
            weakSocket = socket

            socket?.listen()

            socket = nil

            XCTAssertNotNil(weakSocket)

            weakSocket?.shutdown()
        }

        XCTAssertNil(weakSocket)
    }
}

Update Socket test to wait for socket shutdown

//
//  UDPSocketTests.swift
//  WIFIAV
//
//  Created by Max Odnovolyk on 3/13/17.
//  Copyright © 2017 Max Odnovolyk. All rights reserved.
//

import XCTest
@testable import WIFIAV

class UDPSocketTests: XCTestCase {

    override func setUp() {
        super.setUp()

        continueAfterFailure = false
    }

    func testNotListeningSocketGetsDeallocatedImmediately() {
        var socket: UDPSocket? = try! UDPSocket(port: 55000)
        weak var weakSocket = socket

        XCTAssertNotNil(weakSocket)

        socket = nil

        XCTAssertNil(weakSocket)
    }

    func testListeningSocketGetsDeallocatedAfterShutdown() {
        weak var weakSocket: Socket?
        var socket: UDPSocket? = try! UDPSocket(port: 55001)
        weakSocket = socket

        socket?.listen()

        socket = nil

        XCTAssertNotNil(weakSocket)

        weakSocket?.shutdown()

        let nullifyExpectation = expectation(description: "Wait for socket shutdown")

        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            XCTAssertNil(weakSocket)
            nullifyExpectation.fulfill()
        }

        waitForExpectations(timeout: 2)
    }
}


import Foundation
import UIKit

open class PreFormatter: ParagraphAttributeFormatter {

    let monospaceFont: UIFont
    let placeholderAttributes: [String : Any]?

    init(monospaceFont: UIFont = UIFont.monospacedDigitSystemFont(ofSize: 12, weight:UIFontWeightRegular) ,placeholderAttributes: [String : Any]? = nil) {
        self.monospaceFont = monospaceFont
        self.placeholderAttributes = placeholderAttributes
    }

    func apply(to attributes: [String : Any]) -> [String: Any] {
        var resultingAttributes = attributes
        let newParagraphStyle = ParagraphStyle()

        resultingAttributes[NSParagraphStyleAttributeName] = newParagraphStyle
        resultingAttributes[NSFontAttributeName] = monospaceFont

        return resultingAttributes
    }

    func remove(from attributes:[String: Any]) -> [String: Any] {
        var resultingAttributes = attributes
        let newParagraphStyle = ParagraphStyle()

        resultingAttributes[NSParagraphStyleAttributeName] = newParagraphStyle
        resultingAttributes[NSFontAttributeName] = monospaceFont

        return resultingAttributes
    }

    func present(in attributes: [String : Any]) -> Bool {
        if let font = attributes[NSFontAttributeName] as? UIFont {
            return font == monospaceFont
        }
        return false
    }
}

Use courier for monospace font.

import Foundation
import UIKit

open class PreFormatter: ParagraphAttributeFormatter {

    let monospaceFont: UIFont
    let placeholderAttributes: [String : Any]?

    init(monospaceFont: UIFont = UIFont(descriptor:UIFontDescriptor(name: "Courier", size: 12), size:12) ,placeholderAttributes: [String : Any]? = nil) {
        self.monospaceFont = monospaceFont
        self.placeholderAttributes = placeholderAttributes
    }

    func apply(to attributes: [String : Any]) -> [String: Any] {
        var resultingAttributes = attributes
        let newParagraphStyle = ParagraphStyle()

        resultingAttributes[NSParagraphStyleAttributeName] = newParagraphStyle
        resultingAttributes[NSFontAttributeName] = monospaceFont

        return resultingAttributes
    }

    func remove(from attributes:[String: Any]) -> [String: Any] {
        var resultingAttributes = attributes
        let newParagraphStyle = ParagraphStyle()

        resultingAttributes[NSParagraphStyleAttributeName] = newParagraphStyle
        resultingAttributes[NSFontAttributeName] = monospaceFont

        return resultingAttributes
    }

    func present(in attributes: [String : Any]) -> Bool {
        if let font = attributes[NSFontAttributeName] as? UIFont {
            return font == monospaceFont
        }
        return false
    }
}


import PackageDescription

let package = Package(
    name: "SteamPress",
    dependencies: [
    	.Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1),
    	.Package(url: "https://github.com/brokenhandsio/LeafMarkdown.git", majorVersion: 0),
    	.Package(url: "https://github.com/nodes-vapor/paginator", majorVersion: 0)
    ]
)

Add SwiftSoup as a dependency

import PackageDescription

let package = Package(
    name: "SteamPress",
    dependencies: [
    	.Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1),
    	.Package(url: "https://github.com/brokenhandsio/SwiftSoup.git", majorVersion: 1),
    	.Package(url: "https://github.com/brokenhandsio/LeafMarkdown.git", majorVersion: 0),
    	.Package(url: "https://github.com/nodes-vapor/paginator", majorVersion: 0)
    ]
)


import PackageDescription

let package = Package(
  name: "RequestDump",
  dependencies: [
    .Package(url: "https://github.com/briancroom/Curassow.git", majorVersion: 0, minor: 1),
  ]
)

Update to latest Curassow release

import PackageDescription

let package = Package(
  name: "RequestDump",
  dependencies: [
    .Package(url: "https://github.com/kylef/Curassow.git", majorVersion: 0, minor: 2),
  ]
)


// swift-tools-version:5.1

import PackageDescription

let package = Package(
    name: "SteamPressExample",
    products: [
        .library(name: "App", targets: ["App"]),
        .executable(name: "Run", targets: ["Run"])
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/leaf.git", .upToNextMajor(from: "3.0.0")),
        .package(url: "https://github.com/brokenhandsio/leaf-error-middleware.git", .upToNextMajor(from: "1.2.0")),
        .package(url: "https://github.com/brokenhandsio/VaporSecurityHeaders.git", .upToNextMajor(from: "2.0.0")),
        .package(url: "https://github.com/brokenhandsio/steampress-fluent-postgres.git", .upToNextMajor(from: "1.0.0")),
        .package(url: "https://github.com/vapor-community/leaf-markdown.git", .upToNextMajor(from: "2.0.0"))
    ],
    targets: [
        .target(name: "App",
            dependencies: [
                "Leaf",
                "LeafErrorMiddleware",
                "VaporSecurityHeaders",
                "SteampressFluentPostgres",
                "LeafMarkdown"]),
        .testTarget(name: "AppTests", dependencies: ["App"]),
        .target(name: "Run", dependencies: ["App"])
    ]
)

Update manifest to Swift 5.2

// swift-tools-version:5.2

import PackageDescription

let package = Package(
    name: "SteamPressExample",
    products: [
        .library(name: "App", targets: ["App"]),
        .executable(name: "Run", targets: ["Run"])
    ],
    dependencies: [
        .package(name: "Leaf", url: "https://github.com/vapor/leaf.git", from: "3.0.0"),
        .package(name: "LeafErrorMiddleware", url: "https://github.com/brokenhandsio/leaf-error-middleware.git", from: "1.2.0"),
        .package(url: "https://github.com/brokenhandsio/VaporSecurityHeaders.git", from: "2.0.0"),
        .package(name: "SteampressFluentPostgres", url: "https://github.com/brokenhandsio/steampress-fluent-postgres.git", from: "1.0.0"),
        .package(name: "LeafMarkdown", url: "https://github.com/vapor-community/leaf-markdown.git", from: "2.0.0")
    ],
    targets: [
        .target(name: "App",
            dependencies: [
                "Leaf",
                "LeafErrorMiddleware",
                "VaporSecurityHeaders",
                "SteampressFluentPostgres",
                "LeafMarkdown"]),
        .testTarget(name: "AppTests", dependencies: ["App"]),
        .target(name: "Run", dependencies: ["App"])
    ]
)


import PackageDescription

let package = Package(
    name: "plaster",
    dependencies: [
	.Package(url: "https://github.com/qmchenry/FileKit.git", Version(4, 0, 0, prereleaseIdentifiers: ["pre"], buildMetadataIdentifier: "1")),
        .Package(url: "https://github.com/jatoben/CommandLine.git", Version(3, 0, 0, prereleaseIdentifiers: ["pre"], buildMetadataIdentifier: "1")),
    ]
)

Update FileKit ref for XC 8.3 compatibility

import PackageDescription

let package = Package(
    name: "plaster",
    dependencies: [
	.Package(url: "https://github.com/qmchenry/FileKit.git", Version(4, 0, 2, prereleaseIdentifiers: ["pre"], buildMetadataIdentifier: "1")),
        .Package(url: "https://github.com/jatoben/CommandLine.git", Version(3, 0, 0, prereleaseIdentifiers: ["pre"], buildMetadataIdentifier: "1")),
    ]
)


import Foundation

public struct DarkSkyKit {
    public let configuration: Configuration

    public init(_ apiToken: String) {
        self.configuration = Configuration(token: apiToken)
    }

    public init(_ configuration: Configuration) {
        self.configuration = configuration
    }
}

Update Kit initializers to force parameter name usage

import Foundation

public struct DarkSkyKit {
    public let configuration: Configuration

    public init(apiToken: String) {
        self.configuration = Configuration(token: apiToken)
    }

    public init(configuration: Configuration) {
        self.configuration = configuration
    }
}


/*

 FontExtensionTests.swift
 Tests

 CotEditor
 https://coteditor.com

 Created by 1024jp on 2016-06-10.

 ------------------------------------------------------------------------------

 © 2016-2018 1024jp

 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

 https://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 XCTest
@testable import CotEditor

class FontExtensionTests: XCTestCase {

    func testFontSize() {

        let font = NSFont(name: "Menlo-Regular", size: 11)?.screen

        XCTAssertEqual(font?.spaceWidth, 7)
    }

}

Stop using scren font on test for advancement

/*

 FontExtensionTests.swift
 Tests

 CotEditor
 https://coteditor.com

 Created by 1024jp on 2016-06-10.

 ------------------------------------------------------------------------------

 © 2016-2018 1024jp

 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

 https://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 XCTest
@testable import CotEditor

class FontExtensionTests: XCTestCase {

    func testFontSize() {

        let font = NSFont(name: "Menlo-Regular", size: 11)

        XCTAssertEqual(font?.spaceWidth, 6.62255859375)
    }

}


// RUN: not %target-swift-frontend %s -emit-silgen
// XFAIL: no_asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/radex
// rdar://18851497

struct A {
    private let b: [Int] = []
    func a() {
    }
}
typealias B = (C, C)
enum C {
    case D
    case E
}
func c() {
    let d: (B, A)? = nil
    let (e, f) = d!
    f.a()
}

Fix run line for real this time.

// RUN: %target-swift-frontend %s -emit-silgen
// XFAIL: no_asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/radex
// rdar://18851497

struct A {
    private let b: [Int] = []
    func a() {
    }
}
typealias B = (C, C)
enum C {
    case D
    case E
}
func c() {
    let d: (B, A)? = nil
    let (e, f) = d!
    f.a()
}


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

import UIKit

public extension UIAlertController {

    public func addCancel(handler: ((UIAlertAction) -> Void)? = nil) {
        addCustomAction(with: NSLocalizedString("Cancel", comment: "Cancel button title"), handler: handler)
    }

    public func addOK(handler: ((UIAlertAction) -> Void)? = nil) {
        addCustomAction(with: NSLocalizedString("OK", comment: "OK button title"), handler: handler)
    }

    private func addCustomAction(with title: String, handler: ((UIAlertAction) -> Void)?) {
        let finalHandler = handler ?? { _ in
            if #available(iOS 10.0, *) {
                UIImpactFeedbackGenerator(style: .light).impactOccurred()
            }
        }
        addAction(UIAlertAction(title: title, style: .cancel, handler: finalHandler))
    }

}

Set OK action as preferred

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

import UIKit

public extension UIAlertController {

    public func addCancel(handler: ((UIAlertAction) -> Void)? = nil) {
        addAction(customAction(with: NSLocalizedString("Cancel", comment: "Cancel button title"), handler: handler))
    }

    public func addOK(handler: ((UIAlertAction) -> Void)? = nil) {
        let action = customAction(with: NSLocalizedString("OK", comment: "OK button title"), handler: handler)
        addAction(action)
        preferredAction = action
    }

    private func customAction(with title: String, handler: ((UIAlertAction) -> Void)?) -> UIAlertAction {
        let finalHandler = handler ?? { _ in
            if #available(iOS 10.0, *) {
                UIImpactFeedbackGenerator(style: .light).impactOccurred()
            }
        }
        return UIAlertAction(title: title, style: .cancel, handler: finalHandler)
    }

}


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

final class TelescopeTests: XCTestCase {

}

import Assertions
@testable import Manifold
import Prelude
import XCTest

Add some tests of telescope types.

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

final class TelescopeTests: XCTestCase {
	func testEmptyDataConstructorHasUnitType() {
		assert(Telescope.End.type("A"), ==, .UnitType)
	}

	func testRecursiveDataConstructorHasFunctionType() {
		assert(Telescope.Recursive(.End).type("A"), ==, .lambda("A", const(.UnitType)))
	}

	func testMultiplyRecursiveDataConstructorHasFunctionType() {
		assert(Telescope.Recursive(.Recursive(.End)).type("A"), ==, .lambda("A", const(.lambda("A", const(.UnitType)))))
	}

	func testArgumentDataConstructorHasFunctionType() {
		assert(Telescope.Argument("B", const(.Recursive(.End))).type("A"), ==, .lambda("B", const(.lambda("A", const(.UnitType)))))
	}
}

import Assertions
@testable import Manifold
import Prelude
import XCTest


//
//  FileKit.swift
//  FileKit
//
//  Created by Nikolai Vazquez on 9/1/15.
//  Copyright © 2015 Nikolai Vazquez. All rights reserved.
//

import Foundation

public class File: StringLiteralConvertible {

    // MARK: - File

    public var path: Path

    public init(path: Path) {
        self.path = path
    }

    func delete() throws {
        try NSFileManager.defaultManager().removeItemAtPath(path._path)
    }

    func moveToPath(path: Path) throws {
        try NSFileManager.defaultManager().moveItemAtPath(path._path, toPath: path._path)
        self.path = path
    }

    // MARK: - StringLiteralConvertible

    public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType

    public typealias UnicodeScalarLiteralType = StringLiteralType

    public required init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
        path = Path(value)
    }

    public required init(stringLiteral value: StringLiteralType) {
        path = Path(value)
    }

    public required init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
        path = Path(value)
    }

}

Add file creation methods to File

//
//  FileKit.swift
//  FileKit
//
//  Created by Nikolai Vazquez on 9/1/15.
//  Copyright © 2015 Nikolai Vazquez. All rights reserved.
//

import Foundation

public class File: StringLiteralConvertible {

    // MARK: - File

    public var path: Path

    public init(path: Path) {
        self.path = path
    }

    func createFile() -> Bool {
        return NSFileManager.defaultManager().createFileAtPath(
            path._path, contents: nil, attributes: nil)
    }

    func createDirectory() -> Bool {
        return (try? NSFileManager.defaultManager().createDirectoryAtPath(
            path._path, withIntermediateDirectories: true, attributes: nil)) != nil
    }

    func delete() throws {
        try NSFileManager.defaultManager().removeItemAtPath(path._path)
    }

    func moveToPath(path: Path) throws {
        try NSFileManager.defaultManager().moveItemAtPath(path._path, toPath: path._path)
        self.path = path
    }

    // MARK: - StringLiteralConvertible

    public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType

    public typealias UnicodeScalarLiteralType = StringLiteralType

    public required init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
        path = Path(value)
    }

    public required init(stringLiteral value: StringLiteralType) {
        path = Path(value)
    }

    public required init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
        path = Path(value)
    }

}


/*
* Released under the MIT License (MIT), http://opensource.org/licenses/MIT
*
* Copyright (c) 2015 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com)
*
*/

import Foundation

public func runLater (shellcommand: String) -> NSTask {
	let task = NSTask()
	task.arguments = ["-c", shellcommand]
	task.launchPath = "/bin/bash"

	return task
}

/** Print message to standard error and halt execution. */
@noreturn public func printErrorAndExit <T> (errormessage: T, errorcode: Int32 = EXIT_FAILURE) {
	main.stderror.writeln("SwiftShell: \(errormessage)")
	exit(errorcode)
}
}

Add $ method to ShellContextType.

/*
* Released under the MIT License (MIT), http://opensource.org/licenses/MIT
*
* Copyright (c) 2015 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com)
*
*/

import Foundation

/** Print message to standard error and halt execution. */
@noreturn public func printErrorAndExit <T> (errormessage: T, errorcode: Int32 = EXIT_FAILURE) {
	main.stderror.writeln("SwiftShell: \(errormessage)")
	exit(errorcode)
}

extension ShellContextType {

	func runLater (shellcommand: String, args: [String]) -> NSTask {
		let task = NSTask()
		task.arguments = args
		task.launchPath = shellcommand
		task.environment = main.env

		return task
	}

	func runLater (bash bashcommand: String) -> NSTask {
		return runLater("/bin/bash", args: ["-c", bashcommand])
	}

	/** Shortcut for in-line command, returns output as String. */
	public func $ (shellcommand: String, args: String ...) -> String {
		let task = runLater(shellcommand, args: args)

		// avoids implicit reading of the main script's standardInput
		task.standardInput = NSPipe ()

		let output = NSPipe ()
		task.standardOutput = output
		task.standardError = output
		task.launch()
		task.waitUntilExit()

		return output.fileHandleForReading.read(encoding: self.encoding)
	}

}


import XCTest

class DealerSearchTests: UIAutomationTestCase {

    override func setUpWithError() throws {
        try super.setUpWithError()

        controller.app.launch()
        controller.transitionToContent()
        controller.tapTab(.dealers)
        controller.app.swipeDown()
        controller.app.searchFields.firstMatch.tap()
    }

    func testDoesNotCrashWhenDismissingSearch_BUG() {
        controller.app.buttons["Cancel"].firstMatch.tap()
    }

}

Fix dealer test on iPad

import XCTest

class DealerSearchTests: UIAutomationTestCase {

    override func setUpWithError() throws {
        try super.setUpWithError()

        controller.app.launch()
        controller.transitionToContent()
        controller.tapTab(.dealers)
        controller.app.tables.firstMatch.swipeDown()
        controller.app.searchFields.firstMatch.tap()
    }

    func testDoesNotCrashWhenDismissingSearch_BUG() {
        controller.app.buttons["Cancel"].firstMatch.tap()
    }

}


//
//  Created by Pierluigi Cifani on 18/02/2019.
//  Copyright © 2019 TheLeftBit. All rights reserved.
//

#if canImport(UIKit)
#if canImport(MessageUI)

import UIKit
import MessageUI

final public class MessageComposerBehavior: NSObject, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate {
    public static let composer = MessageComposerBehavior()

    public func mailViewController(email: String) -> UIViewController? {
        guard MFMailComposeViewController.canSendMail() else {
            return nil
        }
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients([email])
        return mailVC
    }

    public func smsViewController(phoneNumber: String) -> UIViewController? {
        guard MFMessageComposeViewController.canSendText() else {
            return nil
        }
        let smsVC = MFMessageComposeViewController()
        smsVC.messageComposeDelegate = self
        smsVC.recipients = [phoneNumber]
        return smsVC
    }

    public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true, completion: nil)
    }

    public func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {

        controller.dismiss(animated: true, completion: nil)
    }
}

#endif
#endif

Add contents to Mail share feature

//
//  Created by Pierluigi Cifani on 18/02/2019.
//  Copyright © 2019 TheLeftBit. All rights reserved.
//

#if canImport(UIKit)
#if canImport(MessageUI)

import UIKit
import MessageUI

final public class MessageComposerBehavior: NSObject, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate {
    public static let composer = MessageComposerBehavior()

    public func mailViewController(email: String, contents: MailContents? = nil) -> UIViewController? {
        guard MFMailComposeViewController.canSendMail() else {
            return nil
        }
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients([email])
        if let contents = contents {
            mailVC.setMessageBody(contents.body, isHTML: contents.isHTML)
        }
        return mailVC
    }

    public func smsViewController(phoneNumber: String) -> UIViewController? {
        guard MFMessageComposeViewController.canSendText() else {
            return nil
        }
        let smsVC = MFMessageComposeViewController()
        smsVC.messageComposeDelegate = self
        smsVC.recipients = [phoneNumber]
        return smsVC
    }

    public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true, completion: nil)
    }

    public func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {

        controller.dismiss(animated: true, completion: nil)
    }
}

public extension MessageComposerBehavior {
    struct MailContents {
        public let body: String
        public let isHTML: Bool

        public init(body: String, isHTML: Bool) {
            self.body = body
            self.isHTML = isHTML
        }
    }
}

#endif
#endif


//
//  Operators.swift
//  SwiftCheck
//
//  Created by Robert Widmann on 5/4/15.
//  Copyright (c) 2015 Robert Widmann. All rights reserved.
//

infix operator ==> {}

/// Models implication for properties.  That is, the property holds if the first argument is false
/// (in which case the test case is discarded), or if the given property holds.
public func ==>(b : Bool, p : Testable) -> Property {
	if b {
		return p.property()
	}
	return Discard().property()
}

infix operator ==== {}

/// Like equality but prints a verbose description when it fails.
public func ====<A where A : Equatable, A : Printable>(x : A, y : A) -> Property {
	return counterexample(x.description + "/=" + y.description)(p: x == y)
}

infix operator <?> {}

public func <?>(p : Testable, s : String) -> Property {
	return label(s)(p: p)
}

Add conjunction and disjunction operators

//
//  Operators.swift
//  SwiftCheck
//
//  Created by Robert Widmann on 5/4/15.
//  Copyright (c) 2015 Robert Widmann. All rights reserved.
//

infix operator ==> {}

/// Models implication for properties.  That is, the property holds if the first argument is false
/// (in which case the test case is discarded), or if the given property holds.
public func ==>(b : Bool, p : Testable) -> Property {
	if b {
		return p.property()
	}
	return Discard().property()
}

infix operator ==== {}

/// Like equality but prints a verbose description when it fails.
public func ====<A where A : Equatable, A : Printable>(x : A, y : A) -> Property {
	return counterexample(x.description + "/=" + y.description)(p: x == y)
}

infix operator <?> {}

public func <?>(p : Testable, s : String) -> Property {
	return label(s)(p: p)
}

infix operator ^&&^ {}

public func ^&&^(p1 : Testable, p2 : Testable) -> Property {
	return conjoin([p1.property(), p2.property()])
}

infix operator ^||^ {}

public func ^||^(p1 : Testable, p2 : Testable) -> Property {
	return disjoin([p1.property(), p2.property()])
}


// swift-tools-version: 5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
// TODO: update swift to 5.7

import PackageDescription

let package = Package(
    name: "HealthService",
    platforms: [
        .iOS(.v15),
        .watchOS(.v8)
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "HealthService",
            targets: ["HealthService"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.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 this package depends on.
        .target(
            name: "HealthService",
            dependencies: []),
        .testTarget(
            name: "HealthServiceTests",
            dependencies: ["HealthService"]),
    ]
)

Revert HealthService to use Swift 5.7

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

import PackageDescription

let package = Package(
    name: "HealthService",
    platforms: [
        .iOS(.v15),
        .watchOS(.v8)
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "HealthService",
            targets: ["HealthService"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.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 this package depends on.
        .target(
            name: "HealthService",
            dependencies: []),
        .testTarget(
            name: "HealthServiceTests",
            dependencies: ["HealthService"]),
    ]
)


import UIKit
import ObjectiveC

extension Fleet {
    enum AlertError: FleetErrorDefinition {
        case titleNotFound(title: String)

        var errorMessage: String {
            get {
                switch self {
                case .titleNotFound(let title):
                    return "No action with title '\(title)' found on alert."
                }
            }
        }

        var name: NSExceptionName { get { return NSExceptionName(rawValue: "Fleet.AlertError") } }
    }
}

extension UIAlertController {
    /**
     Mimics a tap on the alert item with the given title,
     firing any associated behavior.

     - parameters:
        - title:  The title of the action to tap

     - throws:
     A `FleetError` if an alert action with the given title cannot be found.
     */
    public func tapAlertAction(withTitle title: String) {
        let filteredActions = actions.filter { action in
            return action.title == title
        }

        var completionHandler: (() -> ())?
        if let actionWithTitle = filteredActions.first {
            if let handler = actionWithTitle.handler {
                completionHandler = {
                    handler(actionWithTitle)
                }
            }

            presentingViewController?.dismiss(animated: true, completion: completionHandler)
        } else {
            FleetError(Fleet.AlertError.titleNotFound(title: title)).raise()
        }
    }
}

Disable dismiss animation in tapAlertAction()

import UIKit
import ObjectiveC

extension Fleet {
    enum AlertError: FleetErrorDefinition {
        case titleNotFound(title: String)

        var errorMessage: String {
            get {
                switch self {
                case .titleNotFound(let title):
                    return "No action with title '\(title)' found on alert."
                }
            }
        }

        var name: NSExceptionName { get { return NSExceptionName(rawValue: "Fleet.AlertError") } }
    }
}

extension UIAlertController {
    /**
     Mimics a tap on the alert item with the given title,
     firing any associated behavior.

     - parameters:
        - title:  The title of the action to tap

     - throws:
     A `FleetError` if an alert action with the given title cannot be found.
     */
    public func tapAlertAction(withTitle title: String) {
        let filteredActions = actions.filter { action in
            return action.title == title
        }

        var completionHandler: (() -> ())?
        if let actionWithTitle = filteredActions.first {
            if let handler = actionWithTitle.handler {
                completionHandler = {
                    handler(actionWithTitle)
                }
            }

            presentingViewController?.dismiss(animated: false, completion: completionHandler)
        } else {
            FleetError(Fleet.AlertError.titleNotFound(title: title)).raise()
        }
    }
}


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

import PackageDescription

let package = Package(
    name: "Fetch",
    products: [
      .library(name: "Fetch", targets: ["Fetch"])
    ],
    dependencies: [],
    targets: [
      .target(name: "Fetch", dependencies: []),
      .testTarget(name: "FetchTests", dependencies: ["Fetch"])
    ]
)

Update package to swift 5

// 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: "Fetch",
    products: [
      .library(name: "Fetch", targets: ["Fetch"])
    ],
    dependencies: [],
    targets: [
      .target(name: "Fetch", dependencies: []),
      .testTarget(name: "FetchTests", dependencies: ["Fetch"])
    ],
    swiftLanguageVersions: [.v5]
)


// swift-tools-version:5.1
//
// Theme.swift
//
// Copyright (c) 2015-2019 Damien (http://delba.io)
//
// 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: "Log",
    products: [
        .library(
            name: "Log",
            targets: ["Log"]),
    ],
    targets: [
        .target(
            name: "Log",
            path: "Source")
    ]
)

Fix filename and swift tools version

// swift-tools-version:5.0
//
// Package.swift
//
// Copyright (c) 2015-2019 Damien (http://delba.io)
//
// 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: "Log",
    products: [
        .library(
            name: "Log",
            targets: ["Log"]),
    ],
    targets: [
        .target(
            name: "Log",
            path: "Source")
    ]
)


//
//  AppDelegate.swift
//  Quotes
//
//  Created by Julian Grosshauser on 09/05/15.
//  Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow? = {
        let window = UIWindow(frame: UIScreen.mainScreen().bounds)

        window.backgroundColor = .whiteColor()
        window.rootViewController = QuotesViewController()

        return window
    }()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window!.makeKeyAndVisible()

        return true
    }
}

Use navigation controller as root view controller

//
//  AppDelegate.swift
//  Quotes
//
//  Created by Julian Grosshauser on 09/05/15.
//  Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

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

        let navigationController = UINavigationController(rootViewController: QuotesViewController())
        window.rootViewController = navigationController

        return window
    }()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window!.makeKeyAndVisible()

        return true
    }
}


import Foundation

protocol MFirebaseDProtocol
{
    static var parent:MFirebaseDProtocol.Type? { get }
    var identifier:String { get }
    var path:String { get }
    var json:Any? { get }

    init?(snapshot:Any)
}

Make parent property not static

import Foundation

protocol MFirebaseDProtocol
{
    var identifier:String { get }
    var parent:MFirebaseDProtocol? { get }
    var path:String { get }
    var json:Any? { get }

    init?(snapshot:Any)
}


//
// Parser+Operators.swift
// FootlessParser
//
// Created by Kåre Morstøl on 31.03.15.
// Copyright (c) 2015 NotTooBad Software. All rights reserved.
//

import Result
import Runes

public func >>- <T,A,B> (p: Parser<T,A>, f: A -> Parser<T,B>) -> Parser<T,B> {
	return Parser { input in
		p.parse(input) >>- { f($0.output).parse($0.nextinput) }
	}
}

/**
	Wrap a value in a minimal context of Parser. Also known as 'return' in Haskell.

	:param: a A value of type A

	:returns: A parser which ignores the input and returns 'a'.
*/
public func pure <A> (a: A) -> Parser<A,A> {
	return Parser { input in .success(output:a, nextinput: input) }
}

Add missing license info to the header.

//
// Parser+Operators.swift
// FootlessParser
//
// Released under the MIT License (MIT), http://opensource.org/licenses/MIT
//
// Copyright (c) 2015 NotTooBad Software. All rights reserved.
//

import Result
import Runes

public func >>- <T,A,B> (p: Parser<T,A>, f: A -> Parser<T,B>) -> Parser<T,B> {
	return Parser { input in
		p.parse(input) >>- { f($0.output).parse($0.nextinput) }
	}
}

/**
	Wrap a value in a minimal context of Parser. Also known as 'return' in Haskell.

	:param: a A value of type A

	:returns: A parser which ignores the input and returns 'a'.
*/
public func pure <A> (a: A) -> Parser<A,A> {
	return Parser { input in .success(output:a, nextinput: input) }
}


// SKIP-THIS-TEST : issue 758

import assert;
import sys;

main {
    updateable_float x = 123;
    float y = x + 321;
    assertEqual(y, 444, "adding updateable and future");
    wait (y) {
      x <incr> := 1;
      // Sleep to make sure above increment occurs
      void signal = sleep(1);
      wait (signal) {
          assertEqual(x, 124, "incremented x");
          float z = x + 100;
          assertEqual(z, 224, "z");
      }
    }
}

Fix 961 so no race condition is possible

// SKIP-THIS-TEST : issue 758

import assert;
import sys;

main {
    updateable_float x = 123;
    float y = x + 321;
    assertEqual(y, 444, "adding updateable and future");
    wait (y) {
      x <incr> := 1;
      // Wait to make sure above increment occurs
      wait (x) {
          assertEqual(x, 124.0, "incremented x");
          float z = x + 100;
          assertEqual(z, 224.0, "z");
      }
    }
}


//
//  Extensions.swift
//  CodeReader
//
//  Created by vulgur on 16/5/11.
//  Copyright © 2016年 MAD. All rights reserved.
//

import UIKit

extension UITableView {
    func reloadDataWithAutoSizingCells() {
        self.reloadData()
        self.setNeedsDisplay()
        self.layoutIfNeeded()
        self.reloadData()
    }
}

extension UIScrollView {
    func resizeContentSize() {
        let contentWidth = self.frame.width
        var contentHeight: CGFloat = 0
        for subview in subviews {
            contentHeight += subview.frame.height
        }
        self.contentSize = CGSize(width: contentWidth, height: contentHeight)
    }
}

extension Date {
    var dateString: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return formatter.string(from: self)
    }
}

Add extension to UITableView to hide empty cells

//
//  Extensions.swift
//  CodeReader
//
//  Created by vulgur on 16/5/11.
//  Copyright © 2016年 MAD. All rights reserved.
//

import UIKit

extension UITableView {
    func reloadDataWithAutoSizingCells() {
        self.reloadData()
        self.setNeedsDisplay()
        self.layoutIfNeeded()
        self.reloadData()
    }
}

extension UIScrollView {
    func resizeContentSize() {
        let contentWidth = self.frame.width
        var contentHeight: CGFloat = 0
        for subview in subviews {
            contentHeight += subview.frame.height
        }
        self.contentSize = CGSize(width: contentWidth, height: contentHeight)
    }
}

extension Date {
    var dateString: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return formatter.string(from: self)
    }
}

extension UITableView {
    func hideEmptyCells() {
        self.tableFooterView = UIView(frame: .zero)
    }
}


import UIKit
import AVFoundation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

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

        return true
    }

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

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

        showBrowser.openShow(at: url)

        return true
    }

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

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

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

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

}

Update isInBackground on applicationDidBecomeActive instead of applicationWillEnterForeground as AVAudioEngine doesn't seem to start before the application is active.

import UIKit
import AVFoundation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

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

        return true
    }

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

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

        showBrowser.openShow(at: url)

        return true
    }

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

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

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

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

}


import Foundation
import RxSwift
import ObjectiveC

public extension NSObject {
    fileprivate struct AssociatedKeys {
        static var DisposeBag = "rx_disposeBag"
    }

    fileprivate func doLocked(_ closure: () -> Void) {
        objc_sync_enter(self); defer { objc_sync_exit(self) }
        closure()
    }

    var rx_disposeBag: DisposeBag {
        get {
            var disposeBag: DisposeBag!
            doLocked {
                let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag
                if let lookup = lookup {
                    disposeBag = lookup
                } else {
                    let newDisposeBag = DisposeBag()
                    self.rx_disposeBag = newDisposeBag
                    disposeBag = newDisposeBag
                }
            }
            return disposeBag
        }

        set {
            doLocked {
                objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
}

Allow usage of rx.disposeBag alongside rx_disposeBag

import Foundation
import RxSwift
import ObjectiveC

public extension NSObject {
    fileprivate struct AssociatedKeys {
        static var DisposeBag = "rx_disposeBag"
    }

    fileprivate func doLocked(_ closure: () -> Void) {
        objc_sync_enter(self); defer { objc_sync_exit(self) }
        closure()
    }

    var rx_disposeBag: DisposeBag {
        get {
            var disposeBag: DisposeBag!
            doLocked {
                let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag
                if let lookup = lookup {
                    disposeBag = lookup
                } else {
                    let newDisposeBag = DisposeBag()
                    self.rx_disposeBag = newDisposeBag
                    disposeBag = newDisposeBag
                }
            }
            return disposeBag
        }

        set {
            doLocked {
                objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
}

extension Reactive where Base: NSObject {
    var disposeBag: DisposeBag {
        return base.rx_disposeBag
    }
}


//
//  AppDelegate.swift
//  RocketWidget
//
//  Created by Suren Khorenyan on 30.09.17.
//  Copyright © 2017 Suren Khorenyan. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

}

Quit after last window closed (for faster debug only)

//
//  AppDelegate.swift
//  RocketWidget
//
//  Created by Suren Khorenyan on 30.09.17.
//  Copyright © 2017 Suren Khorenyan. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

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

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

}


// Sources/SwiftProtobuf/JSONTypeAdditions.swift - JSON format primitive types
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Extend the type definitions from ProtobufTypes.swift with details
/// of protobuf JSON format handling.
///
// -----------------------------------------------------------------------------

import Foundation

///
/// Messages
///
public extension Message {
    func jsonString() throws -> String {
        var visitor = JSONEncodingVisitor(message: self)
        visitor.encoder.startObject()
        try traverse(visitor: &visitor)
        visitor.encoder.endObject()
        return visitor.stringResult
    }

    public init(jsonString: String) throws {
        let data = jsonString.data(using: String.Encoding.utf8)!
        try self.init(jsonUTF8Data: data)
    }

    public init(jsonUTF8Data: Data) throws {
        self.init()
        try jsonUTF8Data.withUnsafeBytes { (bytes:UnsafePointer<UInt8>) in
            var decoder = JSONDecoder(utf8Pointer: bytes,
                                      count: jsonUTF8Data.count)
            if !decoder.scanner.skipOptionalNull() {
                try decoder.decodeFullObject(message: &self)
            }
            if !decoder.scanner.complete {
                throw JSONDecodingError.trailingGarbage
            }
        }
    }
}

Throw an error if we cannot generate a UTF8 version of a string.

// Sources/SwiftProtobuf/JSONTypeAdditions.swift - JSON format primitive types
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Extend the type definitions from ProtobufTypes.swift with details
/// of protobuf JSON format handling.
///
// -----------------------------------------------------------------------------

import Foundation

///
/// Messages
///
public extension Message {
    func jsonString() throws -> String {
        var visitor = JSONEncodingVisitor(message: self)
        visitor.encoder.startObject()
        try traverse(visitor: &visitor)
        visitor.encoder.endObject()
        return visitor.stringResult
    }

    public init(jsonString: String) throws {
        if let data = jsonString.data(using: String.Encoding.utf8) {
            try self.init(jsonUTF8Data: data)
        } else {
            throw JSONDecodingError.truncated
        }
    }

    public init(jsonUTF8Data: Data) throws {
        self.init()
        try jsonUTF8Data.withUnsafeBytes { (bytes:UnsafePointer<UInt8>) in
            var decoder = JSONDecoder(utf8Pointer: bytes,
                                      count: jsonUTF8Data.count)
            if !decoder.scanner.skipOptionalNull() {
                try decoder.decodeFullObject(message: &self)
            }
            if !decoder.scanner.complete {
                throw JSONDecodingError.trailingGarbage
            }
        }
    }
}


import XCTest
@testable import gattaca

class TMSessionLoader:XCTestCase
{
    private let kWaitExpectation:TimeInterval = 3

    func testCreate()
    {
        let sessionExpectation:XCTestExpectation = expectation(
            description:"session created")

        let manager:DManager? = DManager()

        XCTAssertNotNil(
            manager,
            "failed creating manager")

        let session:MSession = MSession()
        session.create(manager:manager!)
        { (session:DSession) in

            sessionExpectation.fulfill()
        }

        waitForExpectations(timeout:kWaitExpectation)
        { (error:Error?) in

        }
    }
}

Test manager is saved on create

import XCTest
@testable import gattaca

class TMSessionLoader:XCTestCase
{
    private let kWaitExpectation:TimeInterval = 3

    func testCreate()
    {
        let sessionExpectation:XCTestExpectation = expectation(
            description:"session created")

        guard

            let manager:DManager = DManager()

        else
        {
            return
        }

        XCTAssertNotNil(
            manager,
            "failed creating manager")

        let session:MSession = MSession()
        session.create(manager:manager)
        { (session:DSession) in

            sessionExpectation.fulfill()
        }

        waitForExpectations(timeout:kWaitExpectation)
        { (error:Error?) in

            let hasChanges:Bool = manager.managedObjectContext.hasChanges

            XCTAssertFalse(
                hasChanges,
                "failed to save changes")
        }
    }
}


//
//  UITableView+RevealingExtensions.swift
//  RevealingTableViewCell
//
//  Created by sovata on 08/04/2017.
//  Copyright © 2017 Nikolay Suvandzhiev. All rights reserved.
//

import Foundation
import UIKit

public extension UITableView
{
    public func closeAllCells(exceptThisOne: RevealingTableViewCell? = nil)
    {
        for visibleCell in self.visibleCells as! [RevealingTableViewCell]
        {
            if let exceptThisOne = exceptThisOne
            {
                if visibleCell != exceptThisOne
                {
                    visibleCell.setRevealingState(.closed, animated: true)
                }
            }
            else
            {
                visibleCell.setRevealingState(.closed, animated: true)
            }
        }
    }
}

Tweak in the closeAllCells logic to avoid forcing the whole tableView to only have cells of type `RevealingTableViewCell `.

//
//  UITableView+RevealingExtensions.swift
//  RevealingTableViewCell
//
//  Created by sovata on 08/04/2017.
//  Copyright © 2017 Nikolay Suvandzhiev. All rights reserved.
//

import Foundation
import UIKit

public extension UITableView
{
    /// If you leave `exceptThisOne` as `nil`, then all cells will be closed.
    /// Otherwise all cells except of the cell specified will be closed
    public func closeAllCells(exceptThisOne cellThatShouldNotBeClosed: RevealingTableViewCell? = nil)
    {
        for visibleCell in self.visibleCells
        {
            if let revealingTableViewCell = visibleCell as? RevealingTableViewCell
            {
                if let cellThatShouldNotBeClosed = cellThatShouldNotBeClosed
                {
                    if visibleCell != cellThatShouldNotBeClosed
                    {
                        revealingTableViewCell.setRevealingState(.closed, animated: true)
                    }
                }
                else
                {
                    revealingTableViewCell.setRevealingState(.closed, animated: true)
                }
            }
        }
    }
}


// RUN: %empty-directory(%t)
// RUN: %target-build-swift -module-name main -Xfrontend -enable-experimental-distributed -Xfrontend -disable-availability-checking -j2 -parse-as-library -I %t %s -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s --color

// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: distributed

// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime

// rdar://90373022
// UNSUPPORTED: OS=watchos

import Distributed

distributed actor Worker {
  typealias ActorSystem = LocalTestingDistributedActorSystem

  distributed func hi() {
    print("hi!")
  }

  nonisolated var description: Swift.String {
    "Worker(\(id))"
  }
}

// ==== Execute ----------------------------------------------------------------
@main struct Main {
  static func main() async throws {
    let system = LocalTestingDistributedActorSystem()

    let actor = Worker(system: system)
    try await actor.hi() // local calls should still just work
    // CHECK: hi!
  }
}

Disable test while we investigte

// RUN: %empty-directory(%t)
// RUN: %target-build-swift -module-name main -Xfrontend -enable-experimental-distributed -Xfrontend -disable-availability-checking -j2 -parse-as-library -I %t %s -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s --color

// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: distributed

// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime

// rdar://90373022
// UNSUPPORTED: OS=watchos

// FIXME(distributed): seems to fail also on simulator on x86_64?
// REQUIRES: rdar90373022

import Distributed

distributed actor Worker {
  typealias ActorSystem = LocalTestingDistributedActorSystem

  distributed func hi() {
    print("hi!")
  }

  nonisolated var description: Swift.String {
    "Worker(\(id))"
  }
}

// ==== Execute ----------------------------------------------------------------
@main struct Main {
  static func main() async throws {
    let system = LocalTestingDistributedActorSystem()

    let actor = Worker(system: system)
    try await actor.hi() // local calls should still just work
    // CHECK: hi!
  }
}