//
//  FavoritesList.swift
//  Fonts
//
//  Created by Domenico on 23.04.15.
//

import UIKit
import Foundation

class FavoritesList{

    //  Swift does not support class properties unless they are of the computed type. (...yet!)
    class var sharedFavoriteList : FavoritesList {
        struct Singleton {
            static let instance = FavoritesList()
        }
        return Singleton.instance;
    }

    // We want external classed to be able to get this variables, but not modifying it.
    // private(set)
    private(set) var favorites: [String]

    init(){
        // Open the user defaults
        let defaults = NSUserDefaults.standardUserDefaults()
        // Look for the key 'favorites'
        let storedFavorites = defaults.objectForKey("favorites") as? [String]
        favorites = storedFavorites != nil ? storedFavorites! : []
    }

    private func saveFavorites(){
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(favorites, forKey: "favorites")
        defaults.synchronize()
    }

    func addFavorite(fontName: String) {
        if (!contains(favorites, fontName)) {
            favorites.append(fontName)
            saveFavorites()
        }
    }

    func removeFavorite(fontName: String) {
        if let index = find(favorites, fontName) {
            favorites.removeAtIndex(index)
            saveFavorites()
        }
    }
}

Move item in favorite list

//
//  FavoritesList.swift
//  Fonts
//
//  Created by Domenico on 23.04.15.
//

import UIKit
import Foundation

class FavoritesList{

    //  Swift does not support class properties unless they are of the computed type. (...yet!)
    class var sharedFavoriteList : FavoritesList {
        struct Singleton {
            static let instance = FavoritesList()
        }
        return Singleton.instance;
    }

    // We want external classed to be able to get this variables, but not modifying it.
    // private(set)
    private(set) var favorites: [String]

    init(){
        // Open the user defaults
        let defaults = NSUserDefaults.standardUserDefaults()
        // Look for the key 'favorites'
        let storedFavorites = defaults.objectForKey("favorites") as? [String]
        favorites = storedFavorites != nil ? storedFavorites! : []
    }

    private func saveFavorites(){
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(favorites, forKey: "favorites")
        defaults.synchronize()
    }

    func addFavorite(fontName: String) {
        if (!contains(favorites, fontName)) {
            favorites.append(fontName)
            saveFavorites()
        }
    }

    func removeFavorite(fontName: String) {
        if let index = find(favorites, fontName) {
            favorites.removeAtIndex(index)
            saveFavorites()
        }
    }

    func moveItem(fromIndex from: Int, toIndex to: Int) {
        let item = favorites[from]
        favorites.removeAtIndex(from)
        favorites.insert(item, atIndex: to)
        saveFavorites()
    }
}


//
// Created by Lucas Nelaupe on 29/10/2017.
//

import Foundation

internal class UniqueUUIDConstraint: JobConstraint {

    class TaskAlreadyExist: ConstraintError {}

    func willSchedule(queue: SwiftQueue, operation: SwiftQueueJob) throws {
        let exist = queue.operations.contains {
            if let op = $0 as? SwiftQueueJob {
                return op.uuid == operation.uuid
            }
            return false
        }
        if exist {
            throw TaskAlreadyExist()
        }
    }

    func willRun(operation: SwiftQueueJob) throws {
        // Nothing to check
    }

    func run(operation: SwiftQueueJob) -> Bool {
        // Nothing to check
        return true
    }
}

Check unique name with non SwiftQueueJob

//
// Created by Lucas Nelaupe on 29/10/2017.
//

import Foundation

internal class UniqueUUIDConstraint: JobConstraint {

    class TaskAlreadyExist: ConstraintError {}

    func willSchedule(queue: SwiftQueue, operation: SwiftQueueJob) throws {
        for op in queue.operations where op.name == operation.uuid {
            throw TaskAlreadyExist()
        }
    }

    func willRun(operation: SwiftQueueJob) throws {
        // Nothing to check
    }

    func run(operation: SwiftQueueJob) -> Bool {
        // Nothing to check
        return true
    }
}


//
//  BatchUpdates.swift
//  DataModel
//
//  Created by Brent Simmons on 9/12/16.
//  Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//

import Foundation

public typealias BatchUpdateBlock = () -> Void

public extension Notification.Name {

	public static let BatchUpdateDidFinish = Notification.Name(rawValue: "BatchUpdateDidFinish")
}

final class BatchUpdate {

	static let shared = BatchUpdate()

	private var count = 0

	var isPerforming: Bool {
		get {
			return count > 0
		}
	}

	func perform(_ batchUpdateBlock: BatchUpdateBlock) {

		incrementCount()
		batchUpdateBlock()
		decrementCount()
	}
}

private extension BatchUpdate {

	func incrementCount() {

		count = count + 1
	}

	func decrementCount() {

		count = count - 1

		if count < 1 {

			if count < 0 {
				assertionFailure("Batch updates count should never be below 0.")
				count = 0
			}

			count = 0
			postBatchUpdateDidPerform()
		}
	}

	func postBatchUpdateDidPerform() {

		NotificationCenter.default.post(name: .BatchUpdateDidFinish, object: nil, userInfo: nil)
	}
}

Rewrite assertionFailure using “Expected…” form.

//
//  BatchUpdates.swift
//  DataModel
//
//  Created by Brent Simmons on 9/12/16.
//  Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//

import Foundation

public typealias BatchUpdateBlock = () -> Void

public extension Notification.Name {

	public static let BatchUpdateDidFinish = Notification.Name(rawValue: "BatchUpdateDidFinish")
}

final class BatchUpdate {

	static let shared = BatchUpdate()

	private var count = 0

	var isPerforming: Bool {
		get {
			return count > 0
		}
	}

	func perform(_ batchUpdateBlock: BatchUpdateBlock) {

		incrementCount()
		batchUpdateBlock()
		decrementCount()
	}
}

private extension BatchUpdate {

	func incrementCount() {

		count = count + 1
	}

	func decrementCount() {

		count = count - 1

		if count < 1 {

			if count < 0 {
				assertionFailure("Expected batch updates count to be 0 or greater.")
				count = 0
			}

			count = 0
			postBatchUpdateDidPerform()
		}
	}

	func postBatchUpdateDidPerform() {

		NotificationCenter.default.post(name: .BatchUpdateDidFinish, object: nil, userInfo: nil)
	}
}


// RUN: %empty-directory(%t)
// RUN: %incparse-test %s --test-case REPLACE
// RUN: %incparse-test %s --test-case REPLACE_BY_LONGER
// RUN: %incparse-test %s --test-case REPLACE_BY_SHORTER
// RUN: %incparse-test %s --test-case INSERT
// RUN: %incparse-test %s --test-case REMOVE
// RUN: %incparse-test %s --test-case ATTACH_TO_PREV_NODE

func foo() {
}

_ = <<REPLACE<6|||7>>>
_ = <<REPLACE_BY_LONGER<6|||"Hello World">>>
_ = <<REPLACE_BY_SHORTER<"Hello again"|||"a">>>
<<INSERT<|||foo()>>>
<<REMOVE<print("abc")|||>>>
foo()
<<ATTACH_TO_PREV_NODE<|||{}>>>
_ = 1

Add some more passing tests

// RUN: %empty-directory(%t)
// RUN: %incparse-test %s --test-case REPLACE
// RUN: %incparse-test %s --test-case REPLACE_BY_LONGER
// RUN: %incparse-test %s --test-case REPLACE_BY_SHORTER
// RUN: %incparse-test %s --test-case INSERT
// RUN: %incparse-test %s --test-case REMOVE
// RUN: %incparse-test %s --test-case ATTACH_TO_PREV_NODE
// RUN: %incparse-test %s --test-case CLASS_SURROUNDING
// RUN: %incparse-test %s --test-case MULTI_EDIT

func foo() {
}

_ = <<REPLACE<6|||7>>>
_ = <<REPLACE_BY_LONGER<6|||"Hello World">>>
_ = <<REPLACE_BY_SHORTER<"Hello again"|||"a">>>
<<INSERT<|||foo()>>>
<<REMOVE<print("abc")|||>>>
foo()
<<ATTACH_TO_PREV_NODE<|||{}>>>
_ = 1

<<CLASS_SURROUNDING<|||class C {>>>
  func method1() {}

<<MULTI_EDIT<|||class C {>>>
  func method1() {}
<<MULTI_EDIT<|||}>>>


//
//  UIImage+Haneke.swift
//  Haneke
//
//  Created by Hermes Pique on 8/10/14.
//  Copyright (c) 2014 Haneke. All rights reserved.
//

import UIKit

extension UIImage {

    func hnk_imageByScalingToSize(toSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(toSize, !hnk_hasAlpha(), 0.0);
        drawInRect(CGRectMake(0, 0, toSize.width, toSize.height))
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return resizedImage
    }

    func hnk_hasAlpha() -> Bool {
        let alpha = CGImageGetAlphaInfo(self.CGImage)
        switch alpha {
        case .First, .Last, .PremultipliedFirst, .PremultipliedLast, .Only:
            return true
        case .None, .NoneSkipFirst, .NoneSkipLast:
            return false
        }
    }

    func hnk_data() -> NSData? {
        let hasAlpha = self.hnk_hasAlpha()
        let data = hasAlpha ? UIImagePNGRepresentation(self) : UIImageJPEGRepresentation(self, 1)
        return data
    }

}

Use implicitly unwrapped optional like in UIImagePNGRepresentation

//
//  UIImage+Haneke.swift
//  Haneke
//
//  Created by Hermes Pique on 8/10/14.
//  Copyright (c) 2014 Haneke. All rights reserved.
//

import UIKit

extension UIImage {

    func hnk_imageByScalingToSize(toSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(toSize, !hnk_hasAlpha(), 0.0);
        drawInRect(CGRectMake(0, 0, toSize.width, toSize.height))
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return resizedImage
    }

    func hnk_hasAlpha() -> Bool {
        let alpha = CGImageGetAlphaInfo(self.CGImage)
        switch alpha {
        case .First, .Last, .PremultipliedFirst, .PremultipliedLast, .Only:
            return true
        case .None, .NoneSkipFirst, .NoneSkipLast:
            return false
        }
    }

    func hnk_data() -> NSData! {
        let hasAlpha = self.hnk_hasAlpha()
        let data = hasAlpha ? UIImagePNGRepresentation(self) : UIImageJPEGRepresentation(self, 1)
        return data
    }

}


//
//  ImgurImageCell.swift
//  Swimgur
//
//  Created by Joseph Neuman on 11/2/14.
//  Copyright (c) 2014 Joseph Neuman. All rights reserved.
//

import Foundation
import UIKit
import SWNetworking

class ImgurImageCell: UITableViewCell {
  @IBOutlet var imgurImage:UIImageView!

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

  func setup() {

  }

  override func prepareForReuse() {
    super.prepareForReuse()
    SWNetworking.sharedInstance.cancelImageviewLoad(imageView)
    imageView.image = nil
  }
}

Reset imgurImage instead of ImageView in cell

//
//  ImgurImageCell.swift
//  Swimgur
//
//  Created by Joseph Neuman on 11/2/14.
//  Copyright (c) 2014 Joseph Neuman. All rights reserved.
//

import Foundation
import UIKit
import SWNetworking

class ImgurImageCell: UITableViewCell {
  @IBOutlet var imgurImage:UIImageView!

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

  func setup() {

  }

  override func prepareForReuse() {
    super.prepareForReuse()
    SWNetworking.sharedInstance.cancelImageviewLoad(imageView)
    imgurImage.image = nil
  }
}


import Cocoa
import Alamofire

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    let api_url = "https://slack.com/api/chat.postMessage"
    let api_channel = "#music" // channel to post
    let api_token = "xoxp-your-api-token" // your slack token

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        startServices()
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        stopServices()
    }

    private func startServices() {
        PlayerListeningService.sharedService().start()
        SlackPostingService.sharedService().start()
    }

    private func stopServices() {
        PlayerListeningService.sharedService().stop()
        SlackPostingService.sharedService().stop()
    }

    func update(notification: NSNotification?) {
        if (notification?.userInfo?["Player State"] as? String ?? "none") != "Playing"
        {
            return
        }
        let name   = notification?.userInfo?["Name"] as? String ?? "none"
        let artist = notification?.userInfo?["Artist"] as? String ?? "none"
        let moodMessage = "listening... " + name + " - " + artist

        var params: [String: AnyObject] = [
            "channel" : api_channel,
            "token" : api_token,
            "as_user" : true,
            "text" : moodMessage
        ]

        Alamofire
            .request(.POST, api_url, parameters: params, encoding: ParameterEncoding.URL, headers: nil)
            .response { (request, response, data, error) -> Void in
                println(response)
        }
    }
}

Remove unused variables and methods

import Cocoa
import Alamofire

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(aNotification: NSNotification) {
        startServices()
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        stopServices()
    }

    private func startServices() {
        PlayerListeningService.sharedService().start()
        SlackPostingService.sharedService().start()
    }

    private func stopServices() {
        PlayerListeningService.sharedService().stop()
        SlackPostingService.sharedService().stop()
    }
}


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

final class TagTests: XCTestCase {
	func testTagTypechecksAsFunction() {
		let expected = Expression.FunctionType([ Enumeration, Term(.Type(0)) ])
		let actual = Tag.out.checkType(expected, context: context)
		assert(actual.left, ==, nil)
		assert(actual.right, ==, expected)
	}

	func testBranchesProducesAType() {
		assert(Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.UnitType))))].out.checkType(.Type(0), context: context).right, ==, .Type(0))
	}

	func testBranchesOfEmptyEnumerationIsUnitType() {
		assert(Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.BooleanType))))].out.evaluate(environment), ==, .UnitType)
	}
}

private let Enumeration = Term("Enumeration")
private let Branches = Term("Branches")
private let `nil` = Term("[]")
private let Tag = Term("Tag")
private let Empty = `nil`[Term("String")]

private let module = Expression<Term>.tag
private let context = module.context
private let environment = module.environment

import Assertions
@testable import Manifold
import Prelude
import XCTest

Expand the Branches/Type test out a little.

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

final class TagTests: XCTestCase {
	func testTagTypechecksAsFunction() {
		let expected = Expression.FunctionType([ Enumeration, Term(.Type(0)) ])
		let actual = Tag.out.checkType(expected, context: context)
		assert(actual.left, ==, nil)
		assert(actual.right, ==, expected)
	}

	func testBranchesProducesAType() {
		let branches = Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.UnitType))))].out.checkType(.Type(0), context: context)
		assert(branches.left, ==, nil)
		assert(branches.right, ==, .Type(0))
	}

	func testBranchesOfEmptyEnumerationIsUnitType() {
		assert(Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.BooleanType))))].out.evaluate(environment), ==, .UnitType)
	}
}

private let Enumeration = Term("Enumeration")
private let Branches = Term("Branches")
private let `nil` = Term("[]")
private let Tag = Term("Tag")
private let Empty = `nil`[Term("String")]

private let module = Expression<Term>.tag
private let context = module.context
private let environment = module.environment

import Assertions
@testable import Manifold
import Prelude
import XCTest


// RUN: rm -rf %t && mkdir -p %t/stats-pre && mkdir -p %t/stats-post
//
// Compile swiftmodule with decl member name tables
// RUN: %target-swift-frontend -emit-module -o %t/NamedLazyMembers.swiftmodule %S/Inputs/NamedLazyMembers/NamedLazyMembers.swift
//
// Check that named-lazy-member-loading reduces the number of Decls deserialized
// RUN: %target-swift-frontend -typecheck -I %t -disable-named-lazy-member-loading -typecheck -stats-output-dir %t/stats-pre %s
// RUN: %target-swift-frontend -typecheck -I %t -stats-output-dir %t/stats-post %s
// RUN: %utils/process-stats-dir.py --evaluate-delta 'NumDeclsDeserialized < -5' %t/stats-pre %t/stats-post

// REQUIRES: rdar_35639403

import NamedLazyMembers

public func test(b: BaseStruct) {
  let _ = b.memberFunc1()
}

Reduce threshold on test case, rdar://35639403

// RUN: rm -rf %t && mkdir -p %t/stats-pre && mkdir -p %t/stats-post
//
// Compile swiftmodule with decl member name tables
// RUN: %target-swift-frontend -emit-module -o %t/NamedLazyMembers.swiftmodule %S/Inputs/NamedLazyMembers/NamedLazyMembers.swift
//
// Check that named-lazy-member-loading reduces the number of Decls deserialized
// RUN: %target-swift-frontend -typecheck -I %t -disable-named-lazy-member-loading -typecheck -stats-output-dir %t/stats-pre %s
// RUN: %target-swift-frontend -typecheck -I %t -stats-output-dir %t/stats-post %s
// RUN: %utils/process-stats-dir.py --evaluate-delta 'NumDeclsDeserialized < -4' %t/stats-pre %t/stats-post

import NamedLazyMembers

public func test(b: BaseStruct) {
  let _ = b.memberFunc1()
}


import UIKit

class StingCell: UICollectionViewCell {

    @IBOutlet weak var playbackIndicator: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var loopIndicator: UIImageView!

    var color = Color.default {
        didSet {
            backgroundColor = color.value
        }
    }

    var loops = false {
        didSet {
            loopIndicator.isHidden = !loops
        }
    }

    var isPlaying = false {
        didSet {
            if isPlaying {
                playbackIndicator.image = UIImage(systemName: "play.circle.fill")
                playbackIndicator.tintColor = .white
            } else {
                playbackIndicator.image = UIImage(systemName: "circle")
                playbackIndicator.tintColor = .backgroundColor
            }
        }
    }

    var isCued = false {
        didSet {
            layer.borderColor = isCued ? UIColor.borderColor.cgColor : color.value.cgColor
        }
    }

}

Use a pause symbol for the cued sting instead of altering its border.

import UIKit

class StingCell: UICollectionViewCell {

    @IBOutlet weak var playbackIndicator: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var loopIndicator: UIImageView!

    var color = Color.default {
        didSet {
            backgroundColor = color.value
            layer.borderColor = color.value.cgColor
        }
    }

    var loops = false {
        didSet {
            loopIndicator.isHidden = !loops
        }
    }

    var isPlaying = false {
        didSet {
            updatePlaybackIndicator()
        }
    }

    var isCued = false {
        didSet {
            updatePlaybackIndicator()
        }
    }

    func updatePlaybackIndicator() {
        if isPlaying {
            playbackIndicator.image = UIImage(systemName: "play.circle.fill")
            playbackIndicator.tintColor = .white
        } else if isCued{
            playbackIndicator.image = UIImage(systemName: "pause.circle")
            playbackIndicator.tintColor = .white
        } else {
            playbackIndicator.image = UIImage(systemName: "circle")
            playbackIndicator.tintColor = .backgroundColor
        }
    }

}


//
//  UIApplication+NetworkIndicator.swift
//  InfiniteScrollViewDemoSwift
//
//  Created by pronebird on 5/3/15.
//  Copyright (c) 2015 pronebird. All rights reserved.
//

import Foundation

private var networkActivityCount = 0

extension UIApplication {

    func startNetworkActivity() {
        networkActivityCount++
        networkActivityIndicatorVisible = true
    }

    func stopNetworkActivity() {
        if networkActivityCount < 1 {
            return;
        }

        if --networkActivityCount == 0 {
            networkActivityIndicatorVisible = false
        }
    }

}

Remove the ++ and -- operators

//
//  UIApplication+NetworkIndicator.swift
//  InfiniteScrollViewDemoSwift
//
//  Created by pronebird on 5/3/15.
//  Copyright (c) 2015 pronebird. All rights reserved.
//

import Foundation

private var networkActivityCount = 0

extension UIApplication {

    func startNetworkActivity() {
        networkActivityCount += 1
        networkActivityIndicatorVisible = true
    }

    func stopNetworkActivity() {
        if networkActivityCount < 1 {
            return;
        }

        networkActivityCount -= 1
        if networkActivityCount == 0 {
            networkActivityIndicatorVisible = false
        }
    }

}


import Foundation

@objc(TRSettingsController) final class SettingsController: NSObject {
    private let locale: NSLocale

    var unitSystem: UnitSystem {
        get {
            let rawUnitSystem = NSUserDefaults.standardUserDefaults().integerForKey(TRSettingsUnitSystemKey)
            return UnitSystem(rawValue: rawUnitSystem)!
        }
        set {
            NSUserDefaults.standardUserDefaults().setInteger(newValue.rawValue, forKey: TRSettingsUnitSystemKey)
        }
    }

    init(locale: NSLocale) {
        self.locale = locale
    }

    convenience override init() {
        self.init(locale: .autoupdatingCurrentLocale())
    }

    func registerSettings() {
        registerUnitSystem()
        registerLastVersion()
    }

    private func registerUnitSystem() {
        let localeUsesMetric = locale.objectForKey(NSLocaleUsesMetricSystem)?.boolValue ?? false
        let unitSystem: UnitSystem = localeUsesMetric ? .Metric : .Imperial
        NSUserDefaults.standardUserDefaults().registerDefaults([TRSettingsUnitSystemKey: unitSystem.rawValue])
    }

    private func registerLastVersion() {
        let version = NSBundle.mainBundle().versionNumber
        NSUserDefaults.standardUserDefaults().registerDefaults([TRSettingsLastVersionKey: version])
        NSUserDefaults.standardUserDefaults().setObject(version, forKey: TRSettingsLastVersionKey)
    }
}

Remove redundant call to `NSUserDefaults.setObject(_:forKey:)`

import Foundation

@objc(TRSettingsController) final class SettingsController: NSObject {
    private let locale: NSLocale

    var unitSystem: UnitSystem {
        get {
            let rawUnitSystem = NSUserDefaults.standardUserDefaults().integerForKey(TRSettingsUnitSystemKey)
            return UnitSystem(rawValue: rawUnitSystem)!
        }
        set {
            NSUserDefaults.standardUserDefaults().setInteger(newValue.rawValue, forKey: TRSettingsUnitSystemKey)
        }
    }

    init(locale: NSLocale) {
        self.locale = locale
    }

    convenience override init() {
        self.init(locale: .autoupdatingCurrentLocale())
    }

    func registerSettings() {
        registerUnitSystem()
        registerLastVersion()
    }

    private func registerUnitSystem() {
        let localeUsesMetric = locale.objectForKey(NSLocaleUsesMetricSystem)?.boolValue ?? false
        let unitSystem: UnitSystem = localeUsesMetric ? .Metric : .Imperial
        NSUserDefaults.standardUserDefaults().registerDefaults([TRSettingsUnitSystemKey: unitSystem.rawValue])
    }

    private func registerLastVersion() {
        let version = NSBundle.mainBundle().versionNumber
        NSUserDefaults.standardUserDefaults().registerDefaults([TRSettingsLastVersionKey: version])
    }
}


//
//  ClearPinPadCell.swift
//  breadwallet
//
//  Created by Adrian Corscadden on 2017-01-23.
//  Copyright © 2017 breadwallet LLC. All rights reserved.
//

import UIKit

class ClearPinPadCell : PinPadCell {

    override func setColors() {
        if isHighlighted {
            label.backgroundColor = .secondaryShadow
            label.textColor = .darkText
        } else {
            if text == "" || text == deleteKeyIdentifier {
                label.backgroundColor = .clear
                imageView.image = imageView.image?.withRenderingMode(.alwaysTemplate)
                imageView.tintColor = .white
            } else {
                label.backgroundColor = UIColor(white: 1.0, alpha: 0.3)
                label.textColor = .white
            }
        }
    }
}

Make login pinpad highlighted colors better

//
//  ClearPinPadCell.swift
//  breadwallet
//
//  Created by Adrian Corscadden on 2017-01-23.
//  Copyright © 2017 breadwallet LLC. All rights reserved.
//

import UIKit

class ClearPinPadCell : PinPadCell {

    override func setColors() {
        if isHighlighted {
            label.backgroundColor = UIColor(white: 0.0, alpha: 0.3)
            label.textColor = .white
        } else {
            if text == "" || text == deleteKeyIdentifier {
                label.backgroundColor = .clear
                imageView.image = imageView.image?.withRenderingMode(.alwaysTemplate)
                imageView.tintColor = .white
            } else {
                label.backgroundColor = UIColor(white: 1.0, alpha: 0.3)
                label.textColor = .white
            }
        }
    }
}


//
//  Constants.swift
//  NodeExtension
//
//  Created by Linzh on 8/20/17.
//  Copyright (c) 2017 Daniel Lin. All rights reserved.
//

public struct DLFrameSize {

    /// The scaled value of screen
    public static let screenScale: CGFloat = UIScreen.main.scale

    /// The width of screen
    public static let screenWidth: CGFloat = UIScreen.main.bounds.size.width

    /// The height of screen
    public static let screenHeight: CGFloat = UIScreen.main.bounds.size.height

    /// The height of status bar
    public static let statusBarHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height

}

extension UIColor {

    /// Tint color of application window
    public static var dl_windowTintColor: UIColor {
        return UIApplication.shared.delegate!.window!!.tintColor
    }
}

Add enum of device screen size with inch

//
//  Constants.swift
//  NodeExtension
//
//  Created by Linzh on 8/20/17.
//  Copyright (c) 2017 Daniel Lin. All rights reserved.
//

public struct DLFrameSize {

    /// The scaled value of screen
    public static let screenScale: CGFloat = UIScreen.main.scale

    /// The width of screen
    public static let screenWidth: CGFloat = UIScreen.main.bounds.size.width

    /// The height of screen
    public static let screenHeight: CGFloat = UIScreen.main.bounds.size.height

    /// The height of status bar
    public static let statusBarHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height

}

public enum DLScreenInch {
    case iPhone_3_5
    case iPhone_4
    case iPhone_4_7
    case iPhone_5_5
    case iPhone_5_8
    case unspecified

    public static func currentDevice() -> DLScreenInch {
        if UIDevice().userInterfaceIdiom != .phone {
            return .unspecified
        }

        if UIScreen.main.nativeBounds.width == 640 && UIScreen.main.nativeBounds.height == 960 {
            return .iPhone_3_5
        } else if UIScreen.main.nativeBounds.width == 640 && UIScreen.main.nativeBounds.height == 1136 {
            return .iPhone_4
        } else if UIScreen.main.nativeBounds.width == 750 && UIScreen.main.nativeBounds.height == 1334 {
            return .iPhone_4_7
        } else if UIScreen.main.nativeBounds.width == 1242 && UIScreen.main.nativeBounds.height == 2208 {
            return .iPhone_5_5
        } else if UIScreen.main.nativeBounds.width == 1125 && UIScreen.main.nativeBounds.height == 2436 {
            return .iPhone_5_8
        } else {
            return .unspecified
        }
    }
}

extension UIColor {

    /// Tint color of application window
    public static var dl_windowTintColor: UIColor {
        return UIApplication.shared.delegate!.window!!.tintColor
    }
}


//
//  VabeStoreError.swift
//  VabeArchitecture
//
//  Created by Valentin Bercot on 13/02/2017.
//
//

import Foundation

/**
 `Error` enum used to represent error cases throw by `VabeStore` extended classes.

 - authors: Valentin Bercot
 */
public enum VabeStoreError: Error
{
    case alreadyExist(id: String)
    case notFound(id: String)
    case notSingle(id: String)
}

Add error cases for VabeStoreOptions

//
//  VabeStoreError.swift
//  VabeArchitecture
//
//  Created by Valentin Bercot on 13/02/2017.
//
//

import Foundation

/**
 `Error` enum used to represent error cases throw by `VabeStore` extended classes.

 - authors: Valentin Bercot
 */
public enum VabeStoreError: Error
{
    case alreadyExist(identifier: String)
    case badFormat(parameter: String)
    case identifiersNotEmpty(identifiers: [String])
    case limitReached(limit: UInt8)
    case notFound(identifier: String)
    case notSingle(identifier: String)
}


//
//  WebSocketTransport.swift
//  WebSocketTransport
//
//  Created by Paul Young on 28/08/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Transport
import JSONLib

public struct WebSocketTransport: Transport {

    private let webSocketServer = BLWebSocketsServer.sharedInstance()

    // TODO: Make port option in protocol
    public init() {
        self.webSocketServer.setHandleRequestBlock { (data) -> NSData! in
            let jsonString = NSString(data: data, encoding: UInt())

            if let json = JSON.parse(jsonString).value {
                let channel = json["protocol"].string
                let topic = json["command"].string
                let jsonPayload: JSON = json["payload"]
                let payload = jsonPayload.object

                switch (channel, topic, payload) {
                case let (.Some(channel), .Some(topic), .Some(payload)):
                    println(channel)
                    println(topic)
                    println(jsonPayload)
                default:
                    break
                }
            }

            // FIXME - transport has no knowledge of the runtime so can't call runtime.receive()

            // TODO: Determine if returning nil is valid - "Attempt to write empty data on the websocket"
            return nil
        }

        self.webSocketServer.startListeningOnPort(3569, withProtocolName: nil) { (error) in
            if (error != nil) {
                println(error)
            }
        }
    }

    public func send(channel: String, _ topic: String, _ payload: JSON) {
        // TODO
    }
}

Update transport as a message receiver.

//
//  WebSocketTransport.swift
//  WebSocketTransport
//
//  Created by Paul Young on 28/08/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Transport
import MessageTransfer
import JSONLib

public struct WebSocketTransport: Transport {

    private let webSocketServer = BLWebSocketsServer.sharedInstance()
    public var messageReceiver: MessageReceiver?

    // TODO: Make port option in protocol
    public init() {
    public init(var _ messageReceiver: MessageReceiverWorkaround) {
        self.webSocketServer.setHandleRequestBlock { (data) -> NSData! in
            let jsonString = NSString(data: data, encoding: UInt())

            if let json = JSON.parse(jsonString).value {
                let channel = json["protocol"].string
                let topic = json["command"].string
                let jsonPayload: JSON = json["payload"]
                let payload = jsonPayload.object

                switch (channel, topic, payload) {
                case let (.Some(channel), .Some(topic), .Some(payload)):
                    println(channel)
                    println(topic)
                    println(jsonPayload)
                default:
                    break
                }
            }

            // FIXME - transport has no knowledge of the runtime so can't call runtime.receive()

            // TODO: Determine if returning nil is valid - "Attempt to write empty data on the websocket"
            return nil
        }

        self.webSocketServer.startListeningOnPort(3569, withProtocolName: nil) { (error) in
            if (error != nil) {
                println(error)
            }
        }
    }

    public func send(channel: String, _ topic: String, _ payload: JSON) {
        // TODO
    }
}


//
//  SwiftRadio-Settings.swift
//  Swift Radio
//
//  Created by Matthew Fecher on 7/2/15.
//  Copyright (c) 2015 MatthewFecher.com. All rights reserved.
//

import Foundation

//**************************************
// GENERAL SETTINGS
//**************************************

// Display Comments
let kDebugLog = true

//**************************************
// STATION JSON
//**************************************

// If this is set to "true", it will use the JSON file in the app
// Set it to "false" to use the JSON file at the stationDataURL

let useLocalStations = true
let stationDataURL   = "http://yoururl.com/json/stations.json"

//**************************************
// SEARCH BAR
//**************************************

// Set this to "true" to enable the search bar
let searchable = false

//**************************************
// NEXT / PREVIOUS BUTTONS
//**************************************

let hideNextPreviousButtons = false

Hide Next / Previous button by default

//
//  SwiftRadio-Settings.swift
//  Swift Radio
//
//  Created by Matthew Fecher on 7/2/15.
//  Copyright (c) 2015 MatthewFecher.com. All rights reserved.
//

import Foundation

//**************************************
// GENERAL SETTINGS
//**************************************

// Display Comments
let kDebugLog = true

//**************************************
// STATION JSON
//**************************************

// If this is set to "true", it will use the JSON file in the app
// Set it to "false" to use the JSON file at the stationDataURL

let useLocalStations = true
let stationDataURL   = "http://yoururl.com/json/stations.json"

//**************************************
// SEARCH BAR
//**************************************

// Set this to "true" to enable the search bar
let searchable = false

//**************************************
// NEXT / PREVIOUS BUTTONS
//**************************************

let hideNextPreviousButtons = true


#if os(iOS)
    import UIKit
#endif

public class NetworkActivityIndicator {

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

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

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

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

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

            #if os(iOS)
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
                    UIApplication.sharedApplication().networkActivityIndicatorVisible = (self.activitiesCount > 0)
                })
            #endif
        }
    }
}

Disable throttle in debug mode

#if os(iOS)
    import UIKit
#endif

public class NetworkActivityIndicator {

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

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

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

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

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

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

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


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

import PackageDescription

let package = Package(
    name: "LittleCMS",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "LittleCMS",
            targets: ["LittleCMS"]),
    ],
    dependencies: [
        .package(url: "https://github.com/PureSwift/CLCMS.git", .branch("master"))
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "LittleCMS",
            dependencies: ["CLCMS"]),
        .testTarget(
            name: "LittleCMSTests",
            dependencies: ["LittleCMS"]),
    ]
)

Revert "Updated for Swift 4"

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

import PackageDescription

let package = Package(
    name: "LittleCMS",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "LittleCMS",
            targets: ["LittleCMS"]),
    ],
    dependencies: [
        .package(url: "https://github.com/PureSwift/CLCMS.git", .branch("master"))
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "LittleCMS",
            dependencies: []),
        .testTarget(
            name: "LittleCMSTests",
            dependencies: ["LittleCMS"]),
    ]
)


// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "Moya",
    products: [
        .library(name: "Moya", targets: ["Moya"]),
        .library(name: "ReactiveMoya", targets: ["ReactiveMoya"]),
        .library(name: "RxMoya", targets: ["RxMoya"]),
    ],
    dependencies: [
        .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "4.1.0")),
        .package(url: "https://github.com/antitypical/Result.git", .upToNextMajor(from: "3.2.0")),
        .package(url: "https://github.com/ReactiveCocoa/ReactiveSwift.git", .upToNextMajor(from: "2.0.0")),
        .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact(Version(4, 0, 0, prereleaseIdentifiers: ["alpha", "1"]))),
    ],
    targets: [
         .target(
            name: "Moya",
            dependencies: [
                "Alamofire",
                "Result"]),
        .target(
            name: "ReactiveMoya",
            dependencies: [
                "Moya",
                "ReactiveSwift"]),
        .target(
            name: "RxMoya",
            dependencies: [
                "Moya",
                "RxSwift"]),
    ],
    exclude: [
        "Tests",
        "Sources/Supporting Files",
	    "Examples"
    ],
    swiftLanguageVersions: [4]
)

Synchronize SPM dependency versions with CocoaPods

// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "Moya",
    products: [
        .library(name: "Moya", targets: ["Moya"]),
        .library(name: "ReactiveMoya", targets: ["ReactiveMoya"]),
        .library(name: "RxMoya", targets: ["RxMoya"]),
    ],
    dependencies: [
        .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "4.1.0")),
        .package(url: "https://github.com/antitypical/Result.git", .upToNextMajor(from: "3.0.0")),
        .package(url: "https://github.com/ReactiveCocoa/ReactiveSwift.git", .upToNextMajor(from: "2.0.0")),
        .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact(Version(4, 0, 0, prereleaseIdentifiers: ["alpha", "1"]))),
    ],
    targets: [
         .target(
            name: "Moya",
            dependencies: [
                "Alamofire",
                "Result"]),
        .target(
            name: "ReactiveMoya",
            dependencies: [
                "Moya",
                "ReactiveSwift"]),
        .target(
            name: "RxMoya",
            dependencies: [
                "Moya",
                "RxSwift"]),
    ],
    exclude: [
        "Tests",
        "Sources/Supporting Files",
	    "Examples"
    ],
    swiftLanguageVersions: [4]
)


import PackageDescription

let package = Package(
    name: "SRP",
    dependencies: [
        .Package(url: "https://github.com/IBM-Swift/BlueCryptor.git", majorVersion: 0, minor: 8),
        .Package(url: "https://github.com/lorentey/BigInt.git", majorVersion: 2, minor: 1),
    ]
)

Update manifest for 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", .branch("swift4")),
    ],
    targets: [
        .target(name: "SRP", dependencies: ["Cryptor", "BigInt"], path: "Sources"),
        .testTarget(name: "SRPTests", dependencies: ["Cryptor", "SRP"]),
    ],
    swiftLanguageVersions: [4]
)


//
//  KeywordReplacementTransformer.swift
//  SwiftKotlinFramework
//
//  Created by Angel Garcia on 20/10/16.
//  Copyright © 2016 Angel G. Olloqui. All rights reserved.
//

import Foundation

class KeywordReplacementTransformer: Transformer {
    let replacementKeywordMap = [
        "protocol": "interface",
        "let": "val",
        "func": "fun",
        "fileprivate": "private"
    ]

    let replacementIndetifierMap = [
        "self": "this",
        "$0": "it",
        "nil": "null",
    ]

    let replacementSymbolMap = [
        "??": "?:",
        "...": ".."
    ]

    func transform(formatter: Formatter) throws {
        formatter.forEachToken { (i, token) in
            let replace: String?
            switch token {
            case .keyword(let string):
                replace = self.replacementKeywordMap[string]
            case .identifier(let string):
                replace = self.replacementIndetifierMap[string]
            case .symbol(let string, _):
                replace = self.replacementSymbolMap[string]
            default:
                replace = nil
            }
            if let replace = replace {
                formatter.replaceToken(at: i, with: token.with(string: replace))
            }
        }
    }
}

Remove @escaping, @noescape, @discardableResult annotations

//
//  KeywordReplacementTransformer.swift
//  SwiftKotlinFramework
//
//  Created by Angel Garcia on 20/10/16.
//  Copyright © 2016 Angel G. Olloqui. All rights reserved.
//

import Foundation

class KeywordReplacementTransformer: Transformer {
    let replacementKeywordMap = [
        "protocol": "interface",
        "let": "val",
        "func": "fun",
        "fileprivate": "private",
        "@escaping": "",
        "@noescape": "",
        "@discardableResult": "",
    ]

    let replacementIndetifierMap = [
        "self": "this",
        "$0": "it",
        "nil": "null",
    ]

    let replacementSymbolMap = [
        "??": "?:",
        "...": ".."
    ]

    func transform(formatter: Formatter) throws {
        formatter.forEachToken { (i, token) in

            let replace: String?
            switch token {
            case .keyword(let string):
                replace = self.replacementKeywordMap[string]
            case .identifier(let string):
                replace = self.replacementIndetifierMap[string]
            case .symbol(let string, _):
                replace = self.replacementSymbolMap[string]
            default:
                replace = nil
            }
            if let replace = replace {
                formatter.replaceToken(at: i, with: token.with(string: replace))
            }
        }
    }
}


import Foundation

@discardableResult
func shell(_ args: [String]) -> Int32 {
    let task = Process()
    task.launchPath = "/usr/bin/env"
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

func loadJS(_ path: String) -> String {
    let bundlePath = Bundle.main.path(forResource: path, ofType: nil)!
    return try! String(contentsOfFile: bundlePath, encoding: String.Encoding.utf8)
}

func getModificationDate(fileManager: FileManager = FileManager.default, atPath: String) -> Date? {
    do {
        let fileManager = FileManager()
        let attributes = try fileManager.attributesOfItem(atPath: atPath)
        return attributes[FileAttributeKey.modificationDate] as? Date
    } catch {
        print("Error message: \(error.localizedDescription)")
        return nil
    }
}

let defaultUrlShorteners = [
    "adf.ly",
    "bit.do",
    "bit.ly",
    "buff.ly",
    "deck.ly",
    "fur.ly",
    "goo.gl",
    "is.gd",
    "mcaf.ee",
    "ow.ly",
    "spoti.fi",
    "su.pr",
    "t.co",
    "tiny.cc",
    "tinyurl.com",
]

Add shortener for MS Teams to defaultUrlShorteners

import Foundation

@discardableResult
func shell(_ args: [String]) -> Int32 {
    let task = Process()
    task.launchPath = "/usr/bin/env"
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

func loadJS(_ path: String) -> String {
    let bundlePath = Bundle.main.path(forResource: path, ofType: nil)!
    return try! String(contentsOfFile: bundlePath, encoding: String.Encoding.utf8)
}

func getModificationDate(fileManager: FileManager = FileManager.default, atPath: String) -> Date? {
    do {
        let fileManager = FileManager()
        let attributes = try fileManager.attributesOfItem(atPath: atPath)
        return attributes[FileAttributeKey.modificationDate] as? Date
    } catch {
        print("Error message: \(error.localizedDescription)")
        return nil
    }
}

let defaultUrlShorteners = [
    "adf.ly",
    "bit.do",
    "bit.ly",
    "buff.ly",
    "deck.ly",
    "fur.ly",
    "goo.gl",
    "is.gd",
    "mcaf.ee",
    "ow.ly",
    "spoti.fi",
    "su.pr",
    "t.co",
    "tiny.cc",
    "tinyurl.com",
    "urlshortener.teams.microsoft.com",
]


//
//  GaugesDemoTests.swift
//  GaugesDemoTests
//
//  Created by Ron Lisle on 4/5/15.
//  Copyright (c) 2015 Ron Lisle. All rights reserved.
//

import UIKit
import XCTest

class GaugesDemoTests: XCTestCase {

    var application: UIApplication!
    var window: UIWindow!
    var tabBarController: UITabBarController!
    var tabBar: UITabBar!

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
        application = UIApplication.sharedApplication()
        window = application.keyWindow
        tabBarController = window.rootViewController as! UITabBarController
        tabBar = tabBarController.tabBar
    }

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

    func testApplicationCreated() {
        XCTAssertNotNil(application, "UIApplication not instantiated")
    }

    func testWindowCreated() {
        XCTAssertNotNil(window, "UIWindow not instantiated")
    }

    func testTabBarControllerCreated() {
        XCTAssertNotNil(tabBarController, "UITabBarController not instantiated")
    }

    func testTabBarCreated() {
        XCTAssertNotNil(tabBar, "UITabBar not instantiated")
    }

}

Add failing test that 1st tab is titled Fuel. 5 tests, 1 failing.

//
//  GaugesDemoTests.swift
//  GaugesDemoTests
//
//  Created by Ron Lisle on 4/5/15.
//  Copyright (c) 2015 Ron Lisle. All rights reserved.
//

import UIKit
import XCTest

class GaugesDemoTests: XCTestCase {

    var application: UIApplication!
    var window: UIWindow!
    var tabBarController: UITabBarController!
    var tabBar: UITabBar!

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
        application = UIApplication.sharedApplication()
        window = application.keyWindow
        tabBarController = window.rootViewController as! UITabBarController
        tabBar = tabBarController.tabBar
    }

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

    func testApplicationCreated() {
        XCTAssertNotNil(application, "UIApplication not instantiated")
    }

    func testWindowCreated() {
        XCTAssertNotNil(window, "UIWindow not instantiated")
    }

    func testTabBarControllerCreated() {
        XCTAssertNotNil(tabBarController, "UITabBarController not instantiated")
    }

    func testTabBarCreated() {
        XCTAssertNotNil(tabBar, "UITabBar not instantiated")
    }

    func testFirstItemIsFuelGauge() {
        let items = tabBar.items as! [UITabBarItem]
        let firstItem = items[0]
        let firstTitle = firstItem.title!
        XCTAssertEqual(firstTitle, "Fuel", "First item title expected to be Fuel but is \(firstTitle)")
    }

}


// swift-tools-version:5.0
import PackageDescription

let package = Package(name: "Bluetooth",
                      products: [
                        .library(
                            name: "Bluetooth",
                            targets: ["Bluetooth"]
                        )
                      ],
                      targets: [
                        .target(name: "Bluetooth", path: "./Sources"),
                        .testTarget(name: "BluetoothTests", dependencies: ["Bluetooth"])
                      ],
                      swiftLanguageVersions: [.v4, .v4_2, .v5])

Build dynamic framework with SwiftPM

// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "Bluetooth",
    products: [
        .library(
            name: "Bluetooth",
            type: .dynamic,
            targets: ["Bluetooth"]
        )
    ],
    targets: [
        .target(name: "Bluetooth", path: "./Sources"),
        .testTarget(name: "BluetoothTests", dependencies: ["Bluetooth"])
    ],
    swiftLanguageVersions: [.v5]
)


//
//  Options.swift
//  Sword
//
//  Created by Alejandro Alonso
//  Copyright © 2017 Alejandro Alonso. All rights reserved.
//

/// Sword Options structure
public struct SwordOptions {

  // MARK: Properties

  /// Array of event names to disable
  public var disabledEvents: [Event] = []

  /// Whether or not caching offline members is allowed
  public var isCachingAllMembers = false

  /// Whether or not this bot is sharded
  public var isSharded = true

  /// Max amount of messages to cache in channels
  public var messageLimit = 50

}

/// Shield Options structure
public struct ShieldOptions {

  // MARK: Properties

  /// Whether or not to ignore commands from bots
  public var ignoreBots = true

  /// Array of prefixes commands should start with
  public var prefixes = ["@bot"]

  /// Default requirement for commands
  public var requirements = CommandRequirements()

}

/// Command Options structure
public struct CommandOptions {

  // MARK: Properties

  /// Array of command aliases
  public var aliases: [String] = []

  /// Required command options
  public var requirements = CommandRequirements()

}

/// Command requirements, such as permissions, users, roles, etc
public struct CommandRequirements {

  /// Array of required permissions in order to use command
  public var permissions: [Permission] = []

  /// Array of users that can use this command
  public var users: [String] = []

}

Add public option initializers again

//
//  Options.swift
//  Sword
//
//  Created by Alejandro Alonso
//  Copyright © 2017 Alejandro Alonso. All rights reserved.
//

/// Sword Options structure
public struct SwordOptions {

  // MARK: Properties

  /// Array of event names to disable
  public var disabledEvents: [Event] = []

  /// Whether or not caching offline members is allowed
  public var isCachingAllMembers = false

  /// Whether or not this bot is sharded
  public var isSharded = true

  /// Max amount of messages to cache in channels
  public var messageLimit = 50

  /// MARK: Initializer

  /// Creates a default SwordOptions
  public init() {}

}

/// Shield Options structure
public struct ShieldOptions {

  // MARK: Properties

  /// Whether or not to ignore commands from bots
  public var ignoreBots = true

  /// Array of prefixes commands should start with
  public var prefixes = ["@bot"]

  /// Default requirement for commands
  public var requirements = CommandRequirements()

  // MARK: Initializer

  /// Creates a default ShieldOptions
  public init() {}

}

/// Command Options structure
public struct CommandOptions {

  // MARK: Properties

  /// Array of command aliases
  public var aliases: [String] = []

  /// Required command options
  public var requirements = CommandRequirements()

  // MARK: Initializer

  /// Creates a default CommandOptions
  public init() {}

}

/// Command requirements, such as permissions, users, roles, etc
public struct CommandRequirements {

  /// Array of required permissions in order to use command
  public var permissions: [Permission] = []

  /// Array of users that can use this command
  public var users: [String] = []

}


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

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

import Cocoa

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

class B: NSObject {
}

extension NSControl: A {}

Annotate a crash test that depends on AppKit

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

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

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

import Cocoa

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

class B: NSObject {
}

extension NSControl: A {}


import Foundation

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

Replace string literal for domain with Constants static member

import Foundation

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).\(Constants.API.pusherDomain)"
        }
    }
}


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

import Prelude
import Tesseract
import XCTest

final class ValueTests: XCTestCase {
	func testConstantValueDestructuresToSomeOfSameType() {
		assertEqual(Value(constant: 1).constant(), 1)
	}

	func testConstantValueDestructuresToNoneOfDifferentType() {
		assertNil(Value(constant: 1).constant() as ()?)
	}

	func testFunctionValueDestructuresAsConstantToNone() {
		assertNil(Value(function: id as Any -> Any).constant() as Any?)
	}

	func testFunctionValueDestructuresToSomeOfSameType() {
		assertNotNil(Value(function: id as Any -> Any).function() as (Any -> Any)?)
	}

	func testFunctionValueDestructuresToNoneOfDifferentType() {
		assertNil(Value(function: id as Any -> Any).function() as (Int -> Int)?)
	}

	func testConstantValueDestructuresAsFunctionToNone() {
		assertNil(Value(constant: ()).function() as (Any -> Any)?)
	}
}

Test that applying nonfunctions yields nil.

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

import Prelude
import Tesseract
import XCTest

final class ValueTests: XCTestCase {
	func testConstantValueDestructuresToSomeOfSameType() {
		assertEqual(Value(constant: 1).constant(), 1)
	}

	func testConstantValueDestructuresToNoneOfDifferentType() {
		assertNil(Value(constant: 1).constant() as ()?)
	}

	func testFunctionValueDestructuresAsConstantToNone() {
		assertNil(Value(function: id as Any -> Any).constant() as Any?)
	}

	func testFunctionValueDestructuresToSomeOfSameType() {
		assertNotNil(Value(function: id as Any -> Any).function() as (Any -> Any)?)
	}

	func testFunctionValueDestructuresToNoneOfDifferentType() {
		assertNil(Value(function: id as Any -> Any).function() as (Int -> Int)?)
	}

	func testConstantValueDestructuresAsFunctionToNone() {
		assertNil(Value(constant: ()).function() as (Any -> Any)?)
	}

	func testApplicationOfConstantIsNil() {
		let value = Value(constant: ())
		assertNil(value.apply(value))
	}
}


//
//  Copyright © 2020 Square Inc. All rights reserved.
//

import Foundation

public protocol Redactable: CustomStringConvertible {

    associatedtype RedactedKeys: RedactedKey

}

public protocol RedactedKey {

    /**
     Returns a value if a given raw string represents a redacted key,
     and returns `nil` if a given string does not represent a redacted key.
     */
    init?(rawValue: String)

}

extension Redactable {

    /**
     Prints a redacted summary of the object.
     */
    public var description: String {
        let mirror = Mirror(reflecting: self)

        let fields = mirror.children.map {
            (label: String?, value: Any) -> String in
            guard let label = label else {
                return "\(value)"
            }
            if RedactedKeys(rawValue: label) != nil {
                // This is a redacted field, but if it's nil then that's ok to print
                if "\(value)" != "nil" {
                    return "\(label): <redacted>"
                }
            }
            if value is String {
                return "\(label): \"\(value)\""
            }
            return "\(label): \(value)"
        }

        if fields.count > 0 {
            let allFields = fields.joined(separator: ", ")
            return "\(mirror.subjectType)(\(allFields))"
        } else {
            return "\(self)"
        }
    }

}

Remove underscore when printing out internal storage type

//
//  Copyright © 2020 Square Inc. All rights reserved.
//

import Foundation

public protocol Redactable: CustomStringConvertible {

    associatedtype RedactedKeys: RedactedKey

}

public protocol RedactedKey {

    /**
     Returns a value if a given raw string represents a redacted key,
     and returns `nil` if a given string does not represent a redacted key.
     */
    init?(rawValue: String)

}

extension Redactable {

    /**
     Prints a redacted summary of the object.
     */
    public var description: String {
        let mirror = Mirror(reflecting: self)

        let fields = mirror.children.map {
            (label: String?, value: Any) -> String in
            guard let label = label else {
                return "\(value)"
            }
            if RedactedKeys(rawValue: label) != nil {
                // This is a redacted field, but if it's nil then that's ok to print
                if "\(value)" != "nil" {
                    return "\(label): <redacted>"
                }
            }
            if value is String {
                return "\(label): \"\(value)\""
            }
            return "\(label): \(value)"
        }

        if fields.count > 0 {
            var typeName = String(describing: mirror.subjectType)
            if typeName.hasPrefix("_") {
                typeName = String(typeName.dropFirst(1))
            }
            let allFields = fields.joined(separator: ", ")
            return "\(typeName)(\(allFields))"
        } else {
            return "\(self)"
        }
    }

}


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

final class IgnoreTests: XCTestCase {
	let ignored = %"x"

	func testIgnoredInputDoesNotGetConcatenatedAtLeft() {
		assertTree(ignored *> %"y", "xy", ==, "y")
	}

	func testIgnoredInputDoesNotGetConcatenatedAtRight() {
		assertTree(%"y" <* ignored, "yx", ==, "y")
	}

	func testIgnoredInputIsDroppedFromAlternationsAtLeft() {
		assertTree(ignored ||> %"y", "y", ==, "y")
	}

	func testIgnoredInputIsDroppedFromAlternationsAtRight() {
		assertTree(%"y" <|| ignored, "y", ==, "y")
	}

	func testRepeatedIgnoredEmptyParsesAreDropped() {
		assertTree(ignored* *> %"y", "y", ==, "y")
	}

	func testRepeatedIgnoredParsesAreDropped() {
		assertTree(ignored* *> %"y", "xxy", ==, "y")
	}
}

// MARK: - Imports

import Assertions
import Madness
import XCTest

Remove the tests of half-dropped alternation.

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

final class IgnoreTests: XCTestCase {
	let ignored = %"x"

	func testIgnoredInputDoesNotGetConcatenatedAtLeft() {
		assertTree(ignored *> %"y", "xy", ==, "y")
	}

	func testIgnoredInputDoesNotGetConcatenatedAtRight() {
		assertTree(%"y" <* ignored, "yx", ==, "y")
	}

	func testRepeatedIgnoredEmptyParsesAreDropped() {
		assertTree(ignored* *> %"y", "y", ==, "y")
	}

	func testRepeatedIgnoredParsesAreDropped() {
		assertTree(ignored* *> %"y", "xxy", ==, "y")
	}
}

// MARK: - Imports

import Assertions
import Madness
import XCTest


import XCTest
@testable import AroundTheTable

class CodableExtensionsTests: XCTestCase {

    static var allTests: [(String, (CodableExtensionsTests) -> () throws -> Void)] {
        return [
            ("testEncodeCountableClosedRange", testEncodeCountableClosedRange),
            ("testDecodeCountableClosedRange", testDecodeCountableClosedRange)
        ]
    }

    /* CountableClosedRange */

    func testEncodeCountableClosedRange() throws {
        let input = 2...4
        let result = try JSONEncoder().encode(input)
        let expected = try JSONEncoder().encode([
            "lowerBound": 2,
            "upperBound": 4
        ])
        XCTAssert(result == expected)
    }

    func testDecodeCountableClosedRange() throws {
        let input = try JSONEncoder().encode([
            "lowerBound": 2,
            "upperBound": 4
        ])
        let result = try JSONDecoder().decode(CountableClosedRange<Int>.self, from: input)
        XCTAssert(result == 2...4)
    }
}

Fix JSON encoding test for CountableClosedRange.

import XCTest
@testable import AroundTheTable

class CodableExtensionsTests: XCTestCase {

    static var allTests: [(String, (CodableExtensionsTests) -> () throws -> Void)] {
        return [
            ("testEncodeCountableClosedRange", testEncodeCountableClosedRange),
            ("testDecodeCountableClosedRange", testDecodeCountableClosedRange)
        ]
    }

    /* CountableClosedRange */

    func testEncodeCountableClosedRange() throws {
        let input = 2...4
        let result = try JSONEncoder().encode(input)
        let resultAsDictionary = try JSONDecoder().decode([String: Int].self, from: result)
        let expected = [
            "lowerBound": 2,
            "upperBound": 4
        ]
        XCTAssert(resultAsDictionary == expected)
    }

    func testDecodeCountableClosedRange() throws {
        let input = try JSONEncoder().encode([
            "lowerBound": 2,
            "upperBound": 4
        ])
        let result = try JSONDecoder().decode(CountableClosedRange<Int>.self, from: input)
        XCTAssert(result == 2...4)
    }
}


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

final class CollectionTests: XCTestCase {
	let empty: Stream<Int> = nil
	let finite: Stream<Int> = [ 1, 2, 3 ]

	func testCountingFiniteStreams() {
		XCTAssertEqual(count(finite), 3)
	}

	func testCountingEmptyStreams() {
		XCTAssertEqual(count(empty), 0)
	}

	func testCanConstructRangesOverFiniteStreams() {
		XCTAssertEqual(count(indices(finite)), 3)
	}

	func testFindOverFiniteStreams() {
		XCTAssertTrue(find(finite, 2) != nil)
	}

	func testIsEmptyOverEmptyStreams() {
		XCTAssertTrue(isEmpty(empty))
	}
}

// MARK: - Imports

import Traversal
import XCTest

Test ranges over infinite streams.

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

final class CollectionTests: XCTestCase {
	let empty: Stream<Int> = nil
	let finite: Stream<Int> = [ 1, 2, 3 ]
	let infinite: Stream<Int> = Stream { 0 }

	func testCountingFiniteStreams() {
		XCTAssertEqual(count(finite), 3)
	}

	func testCountingEmptyStreams() {
		XCTAssertEqual(count(empty), 0)
	}

	func testRangesOverFiniteStreams() {
		XCTAssertEqual(count(indices(finite)), 3)
	}

	func testRangesOverInfiniteStreams() {
		let i = indices(infinite)
		XCTAssertEqual(i.endIndex, i.endIndex.successor())
	}

	func testFindOverFiniteStreams() {
		XCTAssertTrue(find(finite, 2) != nil)
	}

	func testIsEmptyOverEmptyStreams() {
		XCTAssertTrue(isEmpty(empty))
	}
}

// MARK: - Imports

import Traversal
import XCTest


//
//  PrefWindowController.swift
//  Highlight
//
//  Created by Taegon Kim on 18/01/2017.
//  Copyright © 2017 Taegon Kim. All rights reserved.
//

import Cocoa

class PrefWindowController: NSWindowController, NSToolbarDelegate {

    @IBOutlet weak var toolbar: NSToolbar!

    override func windowDidLoad() {
        super.windowDidLoad()

        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.

    }

}

Make the pref dialog bigger

//
//  PrefWindowController.swift
//  Highlight
//
//  Created by Taegon Kim on 18/01/2017.
//  Copyright © 2017 Taegon Kim. All rights reserved.
//

import Cocoa

class PrefWindowController: NSWindowController, NSToolbarDelegate {

    @IBOutlet weak var toolbar: NSToolbar!

    override func windowDidLoad() {
        super.windowDidLoad()

        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.

    }

    override func showWindow(_ sender: Any?) {
        var frame = window?.frame

        if frame != nil {
            frame?.size.width = CGFloat( 550 )
            frame?.size.height = CGFloat( 500 )
            window?.setFrame(frame!, display: false)
        }

        super.showWindow(self)
    }

}


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

extension NSRange : _ObjectiveCBridgeable {
  public static func _isBridgedToObjectiveC() -> Bool {
    return true
  }

  public func _bridgeToObjectiveC() -> NSValue {
    return NSValue(range: self)
  }

  public static func _forceBridgeFromObjectiveC(
    x: NSValue,
    result: inout NSRange?
  ) {
    result = x.rangeValue
  }

  public static func _conditionallyBridgeFromObjectiveC(
    x: NSValue,
    result: inout NSRange?
  ) -> Bool {
    self._forceBridgeFromObjectiveC(x, result: &result)
    return true
  }
}

Remove the default implementation of _ObjectiveCBridgeable._unconditionallyBridgeFromObjectiveC.

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

extension NSRange : _ObjectiveCBridgeable {
  public static func _isBridgedToObjectiveC() -> Bool {
    return true
  }

  public func _bridgeToObjectiveC() -> NSValue {
    return NSValue(range: self)
  }

  public static func _forceBridgeFromObjectiveC(
    x: NSValue,
    result: inout NSRange?
  ) {
    result = x.rangeValue
  }

  public static func _conditionallyBridgeFromObjectiveC(
    x: NSValue,
    result: inout NSRange?
  ) -> Bool {
    self._forceBridgeFromObjectiveC(x, result: &result)
    return true
  }

  public static func _unconditionallyBridgeFromObjectiveC(source: NSValue?)
      -> NSRange {
    var result: NSRange?
    _forceBridgeFromObjectiveC(source!, result: &result)
    return result!
  }
}


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

public protocol Loggable {

}

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

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

    fileprivate static func logRemaining(_ strArr: [String]?) {
        strArr?.dropFirst().forEach({ print($0) })
    }

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

Remove redundant public modifier on function

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

public protocol Loggable {

}

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

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

    fileprivate static func logRemaining(_ strArr: [String]?) {
        strArr?.dropFirst().forEach({ print($0) })
    }

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


import Foundation
import XCTest

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

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

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

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

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

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

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

Rename capturedArguments; add timesCalled property

import Foundation
import XCTest

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

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

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

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

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

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

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

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


import Foundation
import JSONUtilities
import PathKit
import Yams

extension Project {

    public init(path: Path) throws {
        let basePath = path.parent()
        let template = try Spec(filename: path.lastComponent, basePath: basePath)
        try self.init(spec: template, basePath: basePath)
    }
}

Add a PathContaining protocol for expanding paths to the source file's directory

import Foundation
import JSONUtilities
import PathKit
import Yams

extension Project {

    public init(path: Path) throws {
        let basePath = path.parent()
        let template = try Spec(filename: path.lastComponent, basePath: basePath)
        try self.init(spec: template, basePath: basePath)
    }
}

protocol PathContaining {

    associatedtype JSONSourceType
    static func expandPaths(for source: JSONSourceType, relativeTo path: Path) -> JSONSourceType
}

extension PathContaining {

    static func expandStringPaths(from source: JSONDictionary, forKey key: String, relativeTo path: Path) -> JSONDictionary {
        var result = source

        if let source = result[key] as? String {
            result[key] = (path + source).string
        } else if let source = result[key] as? [String] {
            result[key] = source.map { (path + $0).string }
        } else if let source = result[key] as? [String: String] {
            result[key] = source.mapValues { (path + $0).string }
        }
        return result
    }

    static func expandChildPaths<T: PathContaining>(from source: JSONDictionary, forKey key: String, relativeTo path: Path, type: T.Type) -> JSONDictionary {
        var result = source

        if let source = result[key] as? T.JSONSourceType {
            result[key] = T.expandPaths(for: source, relativeTo: path)
        } else if let source = result[key] as? [T.JSONSourceType] {
            result[key] = source.map { T.expandPaths(for: $0, relativeTo: path) }
        } else if let source = result[key] as? [String: T.JSONSourceType] {
            result[key] = source.mapValues { T.expandPaths(for: $0, relativeTo: path) }
        }
        return result
    }

    static func expandChildPaths<T: PathContaining>(from source: JSONDictionary, forPotentialKeys keys: [String], relativeTo path: Path, type: T.Type) -> JSONDictionary {
        var result = source

        for key in keys {
            result = expandChildPaths(from: result, forKey: key, relativeTo: path, type: type)
        }
        return result
    }
}


// Sources/PluginLibrary/Array+Extensions.swift - Additions to Arrays
//
// Copyright (c) 2014 - 2017 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
//
// -----------------------------------------------------------------------------

import Foundation

extension Array {
  /// Like map, but calls the transform with the index and value.
  func enumeratedMap<T>(_ transform: (Int, Element) throws -> T) rethrows -> [T] {
    var i: Int = -1
    return try map {
      i += 1
      return try transform(i, $0)
    }
  }
}

Add note about performance as to why enumerated().map() wasn't used.

// Sources/PluginLibrary/Array+Extensions.swift - Additions to Arrays
//
// Copyright (c) 2014 - 2017 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
//
// -----------------------------------------------------------------------------

import Foundation

extension Array {

  /// Like map, but calls the transform with the index and value.
  ///
  /// NOTE: It would seem like doing:
  ///   return self.enumerated().map {
  ///     return try transform($0.index, $0.element)
  ///   }
  /// would seem like a simple thing to avoid extension. However as of Xcode 8.3.2
  /// (Swift 3.1), building/running 5000000 interation test (macOS) of the differences
  /// are rather large -
  ///   Release build:
  ///     Using enumerated: 3.694987967
  ///     Using enumeratedMap: 0.961241992
  ///   Debug build:
  ///     Using enumerated: 20.038512905
  ///     Using enumeratedMap: 8.521299144
  func enumeratedMap<T>(_ transform: (Int, Element) throws -> T) rethrows -> [T] {
    var i: Int = -1
    return try map {
      i += 1
      return try transform(i, $0)
    }
  }
}


//
//  PasteViewController.swift
//  iCopyPasta
//
//  Created by Agnes Vasarhelyi on 05/01/16.
//  Copyright © 2016 Agnes Vasarhelyi. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class PasteViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    let pasteViewModel = PasteViewModel()
    var disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        let items = Observable.just([
            pasteViewModel.pasteboardService.pasteboard.string
            ])

        items
            .bindTo(tableView.rx_itemsWithCellIdentifier("pasteCell", cellType: UITableViewCell.self)) { (row, element, cell) in
                if let paste = element {
                    cell.textLabel?.text = "\(paste as String) @ row \(row)"
                }
            }.addDisposableTo(disposeBag)

        tableView
            .rx_modelSelected(String)
            .subscribeNext { value in

            }.addDisposableTo(disposeBag)
    }

}

Add comment for selecting table view item

//
//  PasteViewController.swift
//  iCopyPasta
//
//  Created by Agnes Vasarhelyi on 05/01/16.
//  Copyright © 2016 Agnes Vasarhelyi. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class PasteViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    let pasteViewModel = PasteViewModel()
    var disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        let items = Observable.just([
            pasteViewModel.pasteboardService.pasteboard.string
            ])

        items
            .bindTo(tableView.rx_itemsWithCellIdentifier("pasteCell", cellType: UITableViewCell.self)) { (row, element, cell) in
                if let paste = element {
                    cell.textLabel?.text = "\(paste as String) @ row \(row)"
                }
            }.addDisposableTo(disposeBag)

        tableView
            .rx_modelSelected(String)
            .subscribeNext { value in
                // item selected
            }.addDisposableTo(disposeBag)
    }

}


import XCTest

// NOTE: This file is not intended to be included in the Xcode project or CocoaPods.
//       It is picked up by the Swift Package Manager during its build process.

@noreturn public func QCKMain(specs: [XCTestCase], configurations: [QuickConfiguration.Type] = []) {
    // Perform all configuration (ensures that shared examples have been discovered)
    World.sharedWorld.configure { configuration in
        for configurationClass in configurations {
            configurationClass.configure(configuration)
        }
    }
    World.sharedWorld.finalizeConfiguration()

    // Gather all examples (ensures suite hooks have been discovered)
    for case let spec as QuickSpec in specs {
        spec.gatherExamplesIfNeeded()
    }

    XCTMain(specs)
}

Add basic documentation for QCKMain

import XCTest

// NOTE: This file is not intended to be included in the Xcode project or CocoaPods.
//       It is picked up by the Swift Package Manager during its build process.

/// When using Quick with swift-corelibs-xctest, automatic discovery of specs and
/// configurations is not available. Instead, you should create a standalone
/// executable and call this function from its main.swift file. This will execute
/// the specs and then terminate the process with an exit code of 0 if the tests
/// passed, or 1 if there were any failures.
///
/// Quick is known to work with the DEVELOPMENT-SNAPSHOT-2016-02-03-a Swift toolchain
@noreturn public func QCKMain(specs: [XCTestCase], configurations: [QuickConfiguration.Type] = []) {
    // Perform all configuration (ensures that shared examples have been discovered)
    World.sharedWorld.configure { configuration in
        for configurationClass in configurations {
            configurationClass.configure(configuration)
        }
    }
    World.sharedWorld.finalizeConfiguration()

    // Gather all examples (ensures suite hooks have been discovered)
    for case let spec as QuickSpec in specs {
        spec.gatherExamplesIfNeeded()
    }

    XCTMain(specs)
}


//
//  Store+Subscribe.swift
//  TDRedux
//
//  Created by Nicholas Tian on 18/10/2016.
//  Copyright © 2016 nicktd. All rights reserved.
//

extension Store {

    /// Subcribes a *StateSubscriber* (takes a *State* rather than a *Store*)
    /// to the changes of a *Store*'s *State*
    ///
    /// - parameter subscriber: A StateSubscriber function
    public func subscribe(with subscriber: @escaping StateSubscriber) {
        self.subscribe { store in
            subscriber(store.state)
        }
    }

    public func subscribe(with subscriber: @escaping UpdateSubscriber) {
        self.subscribe { (store: Store) in
            subscriber()
        }
    }

    /// Subcribes a *SpecificStateSubscriber* (takes a *SpecificState*)
    /// to the changes of a *Store*'s *State*
    /// with the help of a `Converter`
    ///
    /// - parameter converter:  A function converts State to SpecificState
    /// - parameter subscriber: A SpecificStateSubscriber function
    public func subscribe<SpecificState>(
        withConverter converter: @escaping (State) -> SpecificState,
        subscriber: @escaping (SpecificState) -> ()
    ) {
        self.subscribe { state in
            subscriber(converter(state))
        }
    }
}

Add doc for subscribe(with: UpdateSubscriber)

//
//  Store+Subscribe.swift
//  TDRedux
//
//  Created by Nicholas Tian on 18/10/2016.
//  Copyright © 2016 nicktd. All rights reserved.
//

extension Store {

    /// Subcribes a *StateSubscriber* (takes a *State* rather than a *Store*)
    /// to the changes of a *Store*'s *State*
    ///
    /// - parameter subscriber: A StateSubscriber function
    public func subscribe(with subscriber: @escaping StateSubscriber) {
        self.subscribe { store in
            subscriber(store.state)
        }
    }

    /// The given *UpdateSubscriber* will be called
    /// when the *State* of a *Store* changes
    ///
    /// - parameter subscriber: An UpdateSubscriber
    public func subscribe(with subscriber: @escaping UpdateSubscriber) {
        self.subscribe { (store: Store) in
            subscriber()
        }
    }

    /// Subcribes a *SpecificStateSubscriber* (takes a *SpecificState*)
    /// to the changes of a *Store*'s *State*
    /// with the help of a `Converter`
    ///
    /// - parameter converter:  A function converts State to SpecificState
    /// - parameter subscriber: A SpecificStateSubscriber function
    public func subscribe<SpecificState>(
        withConverter converter: @escaping (State) -> SpecificState,
        subscriber: @escaping (SpecificState) -> ()
    ) {
        self.subscribe { state in
            subscriber(converter(state))
        }
    }
}


import Foundation
import DateToolsSwift

extension EventDescriptor {
  var datePeriod: TimePeriod {
    return TimePeriod(beginning: startDate, end: endDate)
  }
}

Add note about DateTools bridge

import Foundation
import DateToolsSwift

/**
 A bridge between CalendarKit and underlying date processing library.
 Allows using any third-party library for the date processing,
 without exposing it to the client.
 */
extension EventDescriptor {
  var datePeriod: TimePeriod {
    return TimePeriod(beginning: startDate, end: endDate)
  }
}


// RUN: not %target-swift-frontend -typecheck -verify -I %S/Inputs/custom-modules -F %S/Inputs/custom-frameworks -swift-version 3 %s
// RUN: %target-swift-frontend -typecheck -verify -I %S/Inputs/custom-modules -F %S/Inputs/custom-frameworks -swift-version 4.2 %s
// RUN: %target-swift-frontend -typecheck -verify -I %S/Inputs/custom-modules -F %S/Inputs/custom-frameworks -swift-version 5 %s
import ObsoletedAPINotesTest

let _: FooID // expected-error{{'FooID' has been renamed to 'Foo_ID'}}
let _: Foo_ID

Mark test as requiring Objective-C interoperability.

// RUN: not %target-swift-frontend -typecheck -verify -I %S/Inputs/custom-modules -F %S/Inputs/custom-frameworks -swift-version 3 %s
// RUN: %target-swift-frontend -typecheck -verify -I %S/Inputs/custom-modules -F %S/Inputs/custom-frameworks -swift-version 4.2 %s
// RUN: %target-swift-frontend -typecheck -verify -I %S/Inputs/custom-modules -F %S/Inputs/custom-frameworks -swift-version 5 %s
// REQUIRES: objc_interop
import ObsoletedAPINotesTest

let _: FooID // expected-error{{'FooID' has been renamed to 'Foo_ID'}}
let _: Foo_ID


//
//  CommandsClient.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 11/27/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//

import RealmSwift

struct CommandsClient: APIClient {
    let api: AnyAPIFetcher

    func fetchCommands(realm: Realm? = Realm.current) {
        api.fetch(CommandsRequest()) { response in
            switch response {
            case .resource(let resource):
                resource.commands?.forEach { command in
                    try? realm?.write {
                        realm?.add(command, update: true)
                    }
                }
            case .error:
                break
            }
        }
    }

    func runCommand(command: String, params: String, roomId: String,
                    succeeded: RunCommandSucceeded? = nil, errored: APIErrored? = nil) {
        api.fetch(RunCommandRequest(command: command, params: params, roomId: roomId)) { response in
            switch response {
            case .resource(let resource):
                succeeded?(resource)
            case .error(let error):
                errored?(error)
            }
        }
    }
}

Use Realm dispatch instead of main thread for Commands

//
//  CommandsClient.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 11/27/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//

import RealmSwift

struct CommandsClient: APIClient {
    let api: AnyAPIFetcher

    func fetchCommands(realm: Realm? = Realm.current) {
        api.fetch(CommandsRequest()) { response in
            switch response {
            case .resource(let resource):
                Realm.execute({ (realm) in
                    var commands: [Command] = []

                    resource.commands?.forEach { command in
                        commands.append(command)
                    }

                    realm.add(commands, update: true)
                })
            case .error:
                break
            }
        }
    }

    func runCommand(command: String, params: String, roomId: String,
                    succeeded: RunCommandSucceeded? = nil, errored: APIErrored? = nil) {
        api.fetch(RunCommandRequest(command: command, params: params, roomId: roomId)) { response in
            switch response {
            case .resource(let resource):
                succeeded?(resource)
            case .error(let error):
                errored?(error)
            }
        }
    }
}


//
//  DictionaryExtension.swift
//  HandySwift
//
//  Created by Cihat Gündüz on 16.01.16.
//  Copyright © 2016 Flinesoft. All rights reserved.
//

import Foundation

extension Dictionary {

    /// Initializes a new `Dictionary` and fills it with keys and values arrays.
    ///
    /// - Parameters:
    ///   - keys:       The `Array` of keys.
    ///   - values:     The `Array` of values.
    /// - Returns: A new `Dictionary` instance with prefilled keys and values or `nil` if size of `Array`s different.
    public init?(keys: [Key], values: [Value]) {

        guard keys.count == values.count else {
            return nil
        }

        self.init()

        for (index, key) in keys.enumerate() {
            self[key] = values[index]
        }

    }

}

Add merge method to Dictionaries

//
//  DictionaryExtension.swift
//  HandySwift
//
//  Created by Cihat Gündüz on 16.01.16.
//  Copyright © 2016 Flinesoft. All rights reserved.
//

import Foundation

extension Dictionary {

    /// Initializes a new `Dictionary` and fills it with keys and values arrays.
    ///
    /// - Parameters:
    ///   - keys:       The `Array` of keys.
    ///   - values:     The `Array` of values.
    /// - Returns: A new `Dictionary` instance with prefilled keys and values or `nil` if size of `Array`s different.
    public init?(keys: [Key], values: [Value]) {

        guard keys.count == values.count else {
            return nil
        }

        self.init()

        for (index, key) in keys.enumerate() {
            self[key] = values[index]
        }

    }

    /// Merge given `Dictionary` into this `Dictionary` overriding existing values for matching keys.
    ///
    /// - Parameters:
    ///   - otherDictionary:    The other `Dictionary` to merge into this `Dictionary`.
    public mutating func merge(otherDictionary: [Key: Value]) {
        for (key, value) in otherDictionary {
            self[key] = value
        }
    }

}


//
//  Ordinable+FirebaseModel.swift
//  FireRecord
//
//  Created by Victor Alisson on 25/09/17.
//

import FirebaseCommunity

extension Orderable where Self: FirebaseModel {
    public static func order(byProperty property: String) -> Self.Type {
        Self.fireRecordReference = Self.classPath.queryOrdered(byChild: property) as? DatabaseReference
        return self
    }
}

Define standard implementation of the Orderable protocol

//
//  Ordinable+FirebaseModel.swift
//  FireRecord
//
//  Created by Victor Alisson on 25/09/17.
//

import FirebaseCommunity

extension Orderable where Self: FirebaseModel {
    public static func order(byProperty property: String) -> Self.Type {
        Self.fireRecordQuery = Self.classPath.queryOrdered(byChild: property) as? DatabaseQuery
        return self
    }
}


//
//  EF24StartDateRepository.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 10/05/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import Foundation

struct EF24StartDateRepository: ConventionStartDateRepository {

    var conventionStartDate: Date {
        let components = DateComponents(calendar: .current,
                                        timeZone: TimeZone(secondsFromGMT: 0)!,
                                        year: 2018,
                                        month: 9,
                                        day: 22)
        return components.date!
    }

}

Use correct EF start date 🙃

//
//  EF24StartDateRepository.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 10/05/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import Foundation

struct EF24StartDateRepository: ConventionStartDateRepository {

    var conventionStartDate: Date {
        let components = DateComponents(calendar: .current,
                                        timeZone: TimeZone(secondsFromGMT: 0)!,
                                        year: 2018,
                                        month: 8,
                                        day: 22)
        return components.date!
    }

}


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

/// Wrapper for a contiguous array of T.  UnsafeArray is both a
/// Collection-which is multi-pass if you use indices or call
/// generate() on it-and a Generator, which can only be assumed to be
/// single-pass.  It's not clear how well this combination will work
/// out, or whether all Collections should also be Streams; consider
/// this an experiment.
struct UnsafeArray<T> : Collection, Generator {

  var startIndex: Int {
    return 0
  }

  var endIndex: Int {
    return _end - _position
  }

  subscript(i: Int) -> T {
    assert(i >= 0)
    assert(i < endIndex)
    return (_position + i).get()
  }

  init(start: UnsafePointer<T>, length: Int) {
    _position = start
    _end = start + length
  }

  mutating func next() -> T? {
    if _position == _end {
      return .None
    }
    return .Some((_position++).get())
  }

  func generate() -> UnsafeArray {
    return self
  }

  var _position, _end: UnsafePointer<T>
}

Replace the dashes in the comment with parens, as suggested by DaveA.

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

/// Wrapper for a contiguous array of T.  UnsafeArray is both a
/// Collection (which is multi-pass if you use indices or call
/// generate() on it) and a Generator, which can only be assumed to be
/// single-pass.  It's not clear how well this combination will work
/// out, or whether all Collections should also be Streams; consider
/// this an experiment.
struct UnsafeArray<T> : Collection, Generator {

  var startIndex: Int {
    return 0
  }

  var endIndex: Int {
    return _end - _position
  }

  subscript(i: Int) -> T {
    assert(i >= 0)
    assert(i < endIndex)
    return (_position + i).get()
  }

  init(start: UnsafePointer<T>, length: Int) {
    _position = start
    _end = start + length
  }

  mutating func next() -> T? {
    if _position == _end {
      return .None
    }
    return .Some((_position++).get())
  }

  func generate() -> UnsafeArray {
    return self
  }

  var _position, _end: UnsafePointer<T>
}