/**
 * Question Link: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
 * Primary idea: use a queue to help hold TreeNode, and for each level add a new Int array
 *
 * Note: use a boolean value to determine if needs to be added reversely
 *
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.left = nil
 *         self.right = nil
 *     }
 * }
 *
 */

class BinaryTreeZigzagLevelOrderTraversal {
    func zigzagLevelOrder(root: TreeNode?) -> [[Int]] {
        var res = [[Int]](), queue = [TreeNode](), isReverse = false

        if let root = root {
            queue.append(root)
        }

        while !queue.isEmpty {
            let size = queue.count
            var level = [Int]()

            for _ in 0..<size {
                let node = queue.removeFirst()

                // add val
                level.insert(node.val, at: isReverse ? 0 : level.count)

                // add TreeNodes in next level
                if let left = node.left {
                    queue.append(left)
                }
                if let right = node.right {
                    queue.append(right)
                }
            }

            res.append(level)
            isReverse = !isReverse
        }

        return res
    }
}

Optimize solution to Binary Tree Zigzag Level Order Traversal

/**
 * Question Link: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
 * Primary idea: use a queue to help hold TreeNode, and for each level add a new Int array
 *
 * Note: use a boolean value to determine if needs to be added reversely
 *
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.left = nil
 *         self.right = nil
 *     }
 * }
 *
 */

class BinaryTreeZigzagLevelOrderTraversal {
    func zigzagLevelOrder(root: TreeNode?) -> [[Int]] {
        guard let root = root else {
            return [[Int]]()
        }

        var res = [[Int]](), isReverse = false, nodeQ = [root]

        while !nodeQ.isEmpty {
            let currentLevel = nodeQ.map { $0.val }
            res.append(isReverse ? currentLevel.reversed() : currentLevel)

            isReverse = !isReverse

            nodeQ = nodeQ.flatMap { [$0.left, $0.right].compactMap { $0 } }
        }

        return res
    }
}


//
//  AppDelegate.swift
//  Spotijack
//
//  Created by Alex Jackson on 24/07/2017.
//  Copyright © 2017 Alex Jackson. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    private lazy var mainWindowController: MainWindowController = MainWindowController(windowNibName: "MainWindow")

    func applicationDidFinishLaunching(_ notification: Notification) {
        mainWindowController.showWindow(self)
    }

    @IBAction private func openPreferencesWindow(_ sender: NSMenuItem) {
        fatalError("Not Implemented")
    }
}

Handle reopening main window after closing it

//
//  AppDelegate.swift
//  Spotijack
//
//  Created by Alex Jackson on 24/07/2017.
//  Copyright © 2017 Alex Jackson. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    private lazy var mainWindowController: MainWindowController = MainWindowController(windowNibName: "MainWindow")

    func applicationDidFinishLaunching(_ notification: Notification) {
        // Display the main window
        let _ = applicationShouldHandleReopen(NSApplication.shared(), hasVisibleWindows: false)
    }

    func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
        if !flag {
            mainWindowController.showWindow(self)
            return false
        }

        return true
    }

    @IBAction private func openPreferencesWindow(_ sender: NSMenuItem) {
        fatalError("Not Implemented")
    }
}


//
//  TestComponent.swift
//  ViewComponents
//
//  Created by Oleksii on 01/05/2017.
//  Copyright © 2017 WeAreReasonablePeople. All rights reserved.
//

import XCTest
import ViewComponents

class TestComponent: XCTestCase {

    func testComponentEquatable() {
        let comp = Component<UIView>().viewStyles(.alpha(0.2), .backgroundColor(.red))
        XCTAssertEqual(comp, comp)
        XCTAssertEqual(comp.child(comp, { $0 }), comp.child(comp, { $0 }))
        XCTAssertNotEqual(comp.child(comp, { $0 }), comp.child(Component<UILabel>(), { _ in UILabel() }))
    }

}

Cover component side effect with unit tests

//
//  TestComponent.swift
//  ViewComponents
//
//  Created by Oleksii on 01/05/2017.
//  Copyright © 2017 WeAreReasonablePeople. All rights reserved.
//

import XCTest
import ViewComponents

class TestComponent: XCTestCase {
    let comp = Component<UIView>().viewStyles(.alpha(0.2), .backgroundColor(.red))

    func testComponentEquatable() {
        XCTAssertEqual(comp, comp)
        XCTAssertEqual(comp.child(comp, { $0 }), comp.child(comp, { $0 }))
        XCTAssertNotEqual(comp.child(comp, { $0 }), comp.child(Component<UILabel>(), { _ in UILabel() }))
    }

    func testComponentSideEffect() {
        let view = UIView()
        let label = UILabel()
        let labelComp = Component<UILabel>().labelStyles(.isEnabled(false))

        comp.child(labelComp, { _ in label }).configure(view: view)

        XCTAssertEqualWithAccuracy(view.alpha, 0.2, accuracy: 0.001)
        XCTAssertEqual(view.backgroundColor, .red)
        XCTAssertEqual(label.isEnabled, false)
    }

}


//
//  ViewController.swift
//  BPStatusBarAlert
//
//  Created by taehyun.park on 01/25/2017.
//  Copyright (c) 2017 taehyun.park. All rights reserved.
//

import UIKit
import BPStatusBarAlert

class ViewController: UIViewController {

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

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

    @IBAction func buttonTapped(_ sender: Any) {
        BPStatusBarAlert(duration: 0.3, delay: 2, position: .statusBar)
            .message(message: "Complete Sharing This Contents")
            .messageColor(color: UIColor.white)
            .bgColor(color: UIColor.blue)
            .completion { print("completion closure will called") }
            .show()
    }
}

Update parameter value using swift type inference

//
//  ViewController.swift
//  BPStatusBarAlert
//
//  Created by taehyun.park on 01/25/2017.
//  Copyright (c) 2017 taehyun.park. All rights reserved.
//

import UIKit
import BPStatusBarAlert

class ViewController: UIViewController {

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

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

    @IBAction func buttonTapped(_ sender: Any) {
        BPStatusBarAlert(duration: 0.3, delay: 2, position: .statusBar)
            .message(message: "Complete Sharing This Contents")
            .messageColor(color: .white)
            .bgColor(color: .blue)
            .completion { print("completion closure will called") }
            .show()
    }
}


//
//  Typealiases.swift
//  NotAutoLayout
//
//  Created by 史　翔新 on 2017/02/22.
//  Copyright © 2017年 史翔新. All rights reserved.
//

import Foundation

public typealias LayoutCondition = (_ canvasSize: CGSize) -> Bool
public typealias LayoutMethod = (condition: LayoutCondition, position: LayoutPosition)

Rename canvasSize to boundSize in LayoutCondition, which is more accurate especially in views like UIScrollView

//
//  Typealiases.swift
//  NotAutoLayout
//
//  Created by 史　翔新 on 2017/02/22.
//  Copyright © 2017年 史翔新. All rights reserved.
//

import Foundation

public typealias LayoutCondition = (_ boundSize: CGSize) -> Bool
public typealias LayoutMethod = (condition: LayoutCondition, position: LayoutPosition)


//
//  TemplateDisplay.swift
//
//
//  Created by Jeremi Kaczmarczyk on 05.07.2016.
//
//

import Foundation
import Kitura
import HeliumLogger
import LoggerAPI

import Mustache
import File

public struct TemplateDisplay {

    let response: RouterResponse

    func show(withPathString path: String, context: [String: String]) {
        guard let templateFile = try? File(path: path),
            let templateString = try? String(data: templateFile.readAllBytes()),
            let template = try? Template(string: templateString),
            let body = try? template.render(context: Context(box: Box(dictionary: context))) else {
                return Log.error("Failed to parse template")
        }

        do {
            Log.debug("sending webpage: \(path)")
            try response.send(body.string)
        }

        catch {
            Log.error("Failed to send response \(error)")
        }
    }
}

Make init and show method public

//
//  TemplateDisplay.swift
//
//
//  Created by Jeremi Kaczmarczyk on 05.07.2016.
//
//

import Foundation
import Kitura
import HeliumLogger
import LoggerAPI

import Mustache
import File

public struct TemplateDisplay {

    let response: RouterResponse

    public init(response: RouterResponse) {
        self.response = response
    }

    public func show(withPathString path: String, context: [String: String]) {
        guard let templateFile = try? File(path: path),
            let templateString = try? String(data: templateFile.readAllBytes()),
            let template = try? Template(string: templateString),
            let body = try? template.render(context: Context(box: Box(dictionary: context))) else {
                return Log.error("Failed to parse template")
        }

        do {
            Log.debug("sending webpage: \(path)")
            try response.send(body.string)
        }

        catch {
            Log.error("Failed to send response \(error)")
        }
    }
}


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

final class TypeDifferentialTests: XCTestCase {
	// MARK: Diffing

	func testTheDiffOfATypeWithItselfIsEmpty() {
		assert(TypeDifferentiator.differentiate(before: .Bool, after: .Bool), ==, TypeDifferential.Empty)
	}

	// MARK: Patching

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

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

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

import Assertions
import Manifold
import TesseractCore
import XCTest

Test that different constructors produce a total patch.

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

final class TypeDifferentialTests: XCTestCase {
	// MARK: Diffing

	func testTheDiffOfATypeWithItselfIsEmpty() {
		assert(TypeDifferentiator.differentiate(before: .Bool, after: .Bool), ==, TypeDifferential.Empty)
	}

	func testTheDiffOfAConstructorWithADifferentConstructorReplacesIt() {
		assert(TypeDifferentiator.differentiate(before: .Unit, after: .Bool), ==, TypeDifferential.Bool)
	}

	// MARK: Patching

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

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

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

import Assertions
import Manifold
import TesseractCore
import XCTest


// RUN: %target-swift-emit-silgen -swift-version 6 -Xllvm -sil-full-demangle -parse-as-library -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck %s

class Kitty {
  var age: Int = 5 {
    didSet {
    }
  }

  init(val: Int) {
    defer { age = val }
  }

  // Access in a defer matches the context in Swift 6, so this defer should be
  // direct-to-storage.
  // CHECK-LABEL: sil private [ossa] @$s16observers_swift65KittyC3valACSi_tcfc6$deferL_yyF
  // CHECK:         [[REF:%.+]] = ref_element_addr {{.*}} : $Kitty, #Kitty.age
  // CHECK:         [[ACCESS:%.+]] = begin_access {{.*}} [[REF]] : $*Int
  // CHECK:         assign {{.*}} to [[ACCESS]] : $*Int
}

Add `REQUIRES: asserts` for -swift-version 6 test

// RUN: %target-swift-emit-silgen -swift-version 6 -Xllvm -sil-full-demangle -parse-as-library -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck %s
// REQUIRES: asserts

class Kitty {
  var age: Int = 5 {
    didSet {
    }
  }

  init(val: Int) {
    defer { age = val }
  }

  // Access in a defer matches the context in Swift 6, so this defer should be
  // direct-to-storage.
  // CHECK-LABEL: sil private [ossa] @$s16observers_swift65KittyC3valACSi_tcfc6$deferL_yyF
  // CHECK:         [[REF:%.+]] = ref_element_addr {{.*}} : $Kitty, #Kitty.age
  // CHECK:         [[ACCESS:%.+]] = begin_access {{.*}} [[REF]] : $*Int
  // CHECK:         assign {{.*}} to [[ACCESS]] : $*Int
}


import UIKit

protocol MSettingsProtocol
{
    var reusableIdentifier:String { get }
    var cellHeight:CGFloat { get }
}

Add required init for protocol

import UIKit

protocol MSettingsProtocol
{
    var reusableIdentifier:String { get }
    var cellHeight:CGFloat { get }

    init(settings:DSettings)
}


//
//  SpringBoardAppIconViewCell.swift
//  UIPlayground
//
//  Created by Kip Nicol on 9/20/16.
//  Copyright © 2016 Kip Nicol. All rights reserved.
//

import UIKit

class SpringBoardAppIconViewCell: UICollectionViewCell {

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

        setup()
    }

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

        setup()
    }

    func setup() {
        // TODO: update this
        backgroundColor = .blue
    }
}

Add corner radius to sb app icons.

//
//  SpringBoardAppIconViewCell.swift
//  UIPlayground
//
//  Created by Kip Nicol on 9/20/16.
//  Copyright © 2016 Kip Nicol. All rights reserved.
//

import UIKit

class SpringBoardAppIconViewCell: UICollectionViewCell {

    let cornerRadius = CGFloat(12)

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

        setup()
    }

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

        setup()
    }

    func setup() {
        clipsToBounds = true
        layer.cornerRadius = cornerRadius

        // TODO: update this
        backgroundColor = .blue
    }
}


//
//  SharingServiceDelegate.swift
//  NetNewsWire
//
//  Created by Maurice Parker on 9/7/18.
//  Copyright © 2018 Ranchero Software. All rights reserved.
//

import AppKit

@objc final class SharingServiceDelegate: NSObject, NSSharingServiceDelegate {

	weak var window: NSWindow?

	init(_ window: NSWindow?) {
		self.window = window
	}

	func sharingService(_ sharingService: NSSharingService, willShareItems items: [Any]) {

		var subject = ""

		for (index, item) in items.enumerated() {

			guard let writer = item as? ArticlePasteboardWriter,
				let title = writer.article.title else {
				continue
			}

			subject += index != 0 ? ", \(title)" : title

		}

		sharingService.subject = subject

	}

	func sharingService(_ sharingService: NSSharingService, sourceWindowForShareItems items: [Any], sharingContentScope: UnsafeMutablePointer<NSSharingService.SharingContentScope>) -> NSWindow? {
		return window
	}

}

Simplify sharing item subject logic

//
//  SharingServiceDelegate.swift
//  NetNewsWire
//
//  Created by Maurice Parker on 9/7/18.
//  Copyright © 2018 Ranchero Software. All rights reserved.
//

import AppKit

@objc final class SharingServiceDelegate: NSObject, NSSharingServiceDelegate {

	weak var window: NSWindow?

	init(_ window: NSWindow?) {
		self.window = window
	}

	func sharingService(_ sharingService: NSSharingService, willShareItems items: [Any]) {
		sharingService.subject = items
			.compactMap { item in
				let writer = item as? ArticlePasteboardWriter
				return writer?.article.title
			}
			.joined(separator: ", ")
	}

	func sharingService(_ sharingService: NSSharingService, sourceWindowForShareItems items: [Any], sharingContentScope: UnsafeMutablePointer<NSSharingService.SharingContentScope>) -> NSWindow? {
		return window
	}

}


//
//  BothamUITests.swift
//  BothamUITests
//
//  Created by Davide Mendolia on 25/10/15.
//  Copyright © 2015 GoKarumi S.L. All rights reserved.
//

import XCTest
@testable import BothamUI

class BothamUITests: XCTestCase {

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

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

    func testWireframe() {
        let wireframe = FakeWireframe()
        wireframe.presentRootViewControllerInWindow(UIWindow())
        XCTAssertTrue(wireframe.isRootViewControllerPresented)
    }

    func testViewControllerPresenterStateTransitions() {
        let viewController = FakeWireframe().fakeViewControllerFromStoryboard()
        let presenter = FakePresenter()
        viewController.presenter = presenter

        viewController.viewDidLoad()

        XCTAssertTrue(presenter.viewDidLoadCalled)

        let animated = false

        viewController.viewWillAppear(animated)

        XCTAssertTrue(presenter.viewWillAppearCalled)

        viewController.viewDidAppear(animated)

        XCTAssertTrue(presenter.viewDidAppearCalled)

        viewController.viewWillDisappear(animated)

        XCTAssertTrue(presenter.viewWillDisappearCalled)

        viewController.viewDidDisappear(animated)

        XCTAssertTrue(presenter.viewDidDisappearCalled)
    }
}

Add Given When Then Notation

//
//  BothamUITests.swift
//  BothamUITests
//
//  Created by Davide Mendolia on 25/10/15.
//  Copyright © 2015 GoKarumi S.L. All rights reserved.
//

import XCTest
@testable import BothamUI

class BothamUITests: XCTestCase {

    func testWireframe() {
        // Given
        let wireframe = FakeWireframe()
        // When
        wireframe.presentRootViewControllerInWindow(UIWindow())
        // Then
        XCTAssertTrue(wireframe.isRootViewControllerPresented)
    }

    func testViewControllerPresenterStateTransitions() {
        // Given
        let viewController = FakeWireframe().fakeViewControllerFromStoryboard()
        let presenter = FakePresenter()
        viewController.presenter = presenter
        let animated = false

        // When
        viewController.viewDidLoad()
        // Then
        XCTAssertTrue(presenter.viewDidLoadCalled)

        // When
        viewController.viewWillAppear(animated)
        // Then
        XCTAssertTrue(presenter.viewWillAppearCalled)

        // When
        viewController.viewDidAppear(animated)
        // Then
        XCTAssertTrue(presenter.viewDidAppearCalled)

        // When
        viewController.viewWillDisappear(animated)
        // Then
        XCTAssertTrue(presenter.viewWillDisappearCalled)

        // When
        viewController.viewDidDisappear(animated)
        // Then
        XCTAssertTrue(presenter.viewDidDisappearCalled)
    }
}


//
//  Helper functions to work with strings.
//

import Foundation

public struct TegString {
  public static func blank(text: String) -> Bool {
    let trimmed = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
    return trimmed.isEmpty
  }

  public static func trim(text: String) -> String {
    return text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
  }

  public static func contains(text: String, substring: String,
    ignoreCase: Bool = false,
    ignoreDiacritic: Bool = false) -> Bool {

    var options: UInt = 0

    if ignoreCase { options |= NSStringCompareOptions.CaseInsensitiveSearch.rawValue }
    if ignoreDiacritic { options |= NSStringCompareOptions.DiacriticInsensitiveSearch.rawValue }

    return text.rangeOfString(substring, options: NSStringCompareOptions(rawValue: options)) != nil
  }

  //
  // Joins elements of the array into a string with separator.
  // Blank elements are skipped.
  //
  public static func joinNonBlank(array: [String], separator: String ) -> String {
    let nonBlankStrings = array.filter { !self.blank($0) }
    return separator.join(nonBlankStrings)
  }

  //
  // Returns a single space if string is empty.
  // It is used to set UITableView cells labels as a workaround.
  //
  public static func singleSpaceIfEmpty(text: String) -> String {
    if text == "" {
      return " "
    }

    return text
  }
}

Support Xcode 7 beta 6

//
//  Helper functions to work with strings.
//

import Foundation

public struct TegString {
  public static func blank(text: String) -> Bool {
    let trimmed = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    return trimmed.isEmpty
  }

  public static func trim(text: String) -> String {
    return text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
  }

  public static func contains(text: String, substring: String,
    ignoreCase: Bool = false,
    ignoreDiacritic: Bool = false) -> Bool {

    var options: UInt = 0

    if ignoreCase { options |= NSStringCompareOptions.CaseInsensitiveSearch.rawValue }
    if ignoreDiacritic { options |= NSStringCompareOptions.DiacriticInsensitiveSearch.rawValue }

    return text.rangeOfString(substring, options: NSStringCompareOptions(rawValue: options)) != nil
  }

  //
  // Returns a single space if string is empty.
  // It is used to set UITableView cells labels as a workaround.
  //
  public static func singleSpaceIfEmpty(text: String) -> String {
    if text == "" {
      return " "
    }

    return text
  }
}


// OBJ APP

(string obj_result) obj(string params, string iter_indiv_id) {
  string outdir = "%s/run_%s" % (turbine_output, iter_indiv_id);
  printf("run model: %s", outdir);
  string result_file = outdir/"result.txt";
  run_model(model_script, params, outdir, iter_indiv_id) =>
    obj_result = get_results(result_file);
  printf("result(%s): %s", iter_indiv_id, obj_result);
}

app (void o) run_model (file shfile, string params_string, string instance, string run_id)
{
    "bash" shfile params_string emews_root instance model_name FRAMEWORK exp_id run_id benchmark_timeout;
}

(string obj_result) get_results(string result_file) {
  if (file_exists(result_file)) {
    file line = input(result_file);
    obj_result = trim(read(line));
  } else {
    // This should only happen on timeout
    printf("File not found: %s", result_file);
    obj_result = "NaN";
  }
}

Create a directory for model run outputs

// OBJ APP

(string obj_result) obj(string params, string iter_indiv_id) {
  string outdir = "%s/run/%s" % (turbine_output, iter_indiv_id);
  printf("run model: %s", outdir);
  string result_file = outdir/"result.txt";
  run_model(model_script, params, outdir, iter_indiv_id) =>
    obj_result = get_results(result_file);
  printf("result(%s): %s", iter_indiv_id, obj_result);
}

app (void o) run_model (file shfile, string params_string, string instance, string run_id)
{
    "bash" shfile params_string emews_root instance model_name FRAMEWORK exp_id run_id benchmark_timeout;
}

(string obj_result) get_results(string result_file) {
  if (file_exists(result_file)) {
    file line = input(result_file);
    obj_result = trim(read(line));
  } else {
    // This should only happen on timeout
    printf("File not found: %s", result_file);
    obj_result = "NaN";
  }
}


//
//  Created by Jake Lin on 12/13/15.
//  Copyright © 2015 Jake Lin. All rights reserved.
//

import UIKit

public protocol MaskDesignable {
  var maskType: String { get set }
}

public extension MaskDesignable where Self: UIView {
  public func configMask() {
    guard let maskType = MaskType(rawValue: maskType) else {
      return
    }

    switch(maskType) {
    case .Circle:
      maskCircle()
    }
  }

  // MARK: - Private
  private func maskCircle() {
    let circle = CAShapeLayer()
    circle.path = UIBezierPath(roundedRect: bounds, cornerRadius: bounds.size.height).CGPath
    circle.fillColor = UIColor.blackColor().CGColor
    layer.mask = circle
  }
}

Update the circle mask logic

//
//  Created by Jake Lin on 12/13/15.
//  Copyright © 2015 Jake Lin. All rights reserved.
//

import UIKit

public protocol MaskDesignable {
  var maskType: String { get set }
}

public extension MaskDesignable where Self: UIView {
  public func configMask() {
    guard let maskType = MaskType(rawValue: maskType) else {
      return
    }

    switch(maskType) {
    case .Circle:
      maskCircle()
    }
  }

  // MARK: - Private
  private func maskCircle() {
    let circle = CAShapeLayer()
    var minHeight: CGFloat
    var minBounds: CGRect
    if (bounds.width != bounds.height) {
      minHeight = bounds.width
      minBounds = bounds
    }
    else {
      minHeight = min(bounds.width, bounds.height)
      minBounds = CGRectMake(0, 0, minHeight, minHeight)
    }

    circle.path = UIBezierPath(roundedRect: minBounds, cornerRadius: minHeight).CGPath
    circle.fillColor = UIColor.blackColor().CGColor
    layer.mask = circle
  }
}


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

/// Returns whether or not the receiver can parse the empty string.
extension Combinator {
	var nullable: Bool {
		let nullable: Combinator<Alphabet> -> Bool = fixpoint(false) { recur, combinator in
			switch combinator.language {
			case .Null:
				return true

			case let .Alternation(left, right):
				return recur(left) || recur(right)

			case let .Concatenation(first, second):
				return recur(first) && recur(second)

			case .Repetition:
				return true

			case let .Reduction(c, _):
				return recur(c)

			default:
				return false
			}
		}
		return nullable(self)
	}
}

Put the comment in the right place.

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

extension Combinator {
	/// Returns whether or not the receiver can parse the empty string.
	var nullable: Bool {
		let nullable: Combinator<Alphabet> -> Bool = fixpoint(false) { recur, combinator in
			switch combinator.language {
			case .Null:
				return true

			case let .Alternation(left, right):
				return recur(left) || recur(right)

			case let .Concatenation(first, second):
				return recur(first) && recur(second)

			case .Repetition:
				return true

			case let .Reduction(c, _):
				return recur(c)

			default:
				return false
			}
		}
		return nullable(self)
	}
}


//
//  UIApplication+OAuthSwift.swift
//  OAuthSwift
//
//  Created by phimage on 11/12/15.
//  Copyright © 2015 Dongri Jin. All rights reserved.
//

#if os(iOS) || os(tvOS)
    import UIKit

    extension UIApplication {
        static var topViewController: UIViewController? {
            return UIApplication.sharedApplication().topViewController
        }

        var topViewController: UIViewController? {
            guard let rootController = self.keyWindow?.rootViewController else {
                return nil
            }
            return UIViewController.topViewController(rootController)
        }
    }

    extension UIViewController {

        static func topViewController(viewController: UIViewController) -> UIViewController {
            guard let presentedViewController = viewController.presentedViewController else {
                return viewController
            }
            #if !topVCCastDisabled
            if let navigationController = presentedViewController as? UINavigationController {
                if let visibleViewController = navigationController.visibleViewController {
                    return topViewController(visibleViewController)
                }
            } else if let tabBarController = presentedViewController as? UITabBarController {
                if let selectedViewController = tabBarController.selectedViewController {
                    return topViewController(selectedViewController)
                }
            }
            #endif
            return topViewController(presentedViewController)
        }
    }

#endif

Use OAUTH_APP_EXTENSIONS inside UIApplication extension

//
//  UIApplication+OAuthSwift.swift
//  OAuthSwift
//
//  Created by phimage on 11/12/15.
//  Copyright © 2015 Dongri Jin. All rights reserved.
//

#if os(iOS) || os(tvOS)
    import UIKit

    extension UIApplication {
        static var topViewController: UIViewController? {
			#if !OAUTH_APP_EXTENSIONS
				return UIApplication.sharedApplication().topViewController
			#else
				return nil
			#endif
        }

        var topViewController: UIViewController? {
            guard let rootController = self.keyWindow?.rootViewController else {
                return nil
            }
            return UIViewController.topViewController(rootController)
        }
    }

    extension UIViewController {

        static func topViewController(viewController: UIViewController) -> UIViewController {
            guard let presentedViewController = viewController.presentedViewController else {
                return viewController
            }
            #if !topVCCastDisabled
            if let navigationController = presentedViewController as? UINavigationController {
                if let visibleViewController = navigationController.visibleViewController {
                    return topViewController(visibleViewController)
                }
            } else if let tabBarController = presentedViewController as? UITabBarController {
                if let selectedViewController = tabBarController.selectedViewController {
                    return topViewController(selectedViewController)
                }
            }
            #endif
            return topViewController(presentedViewController)
        }
    }

#endif


//
//  SidebarCellAppearance.swift
//  NetNewsWire
//
//  Created by Brent Simmons on 11/24/17.
//  Copyright © 2017 Ranchero Software. All rights reserved.
//

import AppKit

struct SidebarCellAppearance: Equatable {

	let imageSize: CGSize
	let imageMarginRight: CGFloat = 4.0
	let unreadCountMarginLeft: CGFloat = 10.0
	let textFieldFontSize: CGFloat
	let textFieldFont: NSFont

	init(rowSizeStyle: NSTableView.RowSizeStyle) {
		switch rowSizeStyle {
		case .small:
			imageSize = CGSize(width: 16, height: 16)
			textFieldFontSize = 11
		case .large:
			imageSize = CGSize(width: 24, height: 24)
			if #available(macOS 11.0, *) {
				textFieldFontSize = 15
			} else {
				textFieldFontSize = 13
			}
		default:
			imageSize = CGSize(width: 20, height: 20)
			textFieldFontSize = 13
		}

		self.textFieldFont = NSFont.systemFont(ofSize: textFieldFontSize)
	}
}

Tweak the sidebar image sizes so that they match the system apps as it looks like the HIG has the wrong values in it for sidebar image sizes

//
//  SidebarCellAppearance.swift
//  NetNewsWire
//
//  Created by Brent Simmons on 11/24/17.
//  Copyright © 2017 Ranchero Software. All rights reserved.
//

import AppKit

struct SidebarCellAppearance: Equatable {

	let imageSize: CGSize
	let imageMarginRight: CGFloat = 4.0
	let unreadCountMarginLeft: CGFloat = 10.0
	let textFieldFontSize: CGFloat
	let textFieldFont: NSFont

	init(rowSizeStyle: NSTableView.RowSizeStyle) {
		switch rowSizeStyle {
		case .small:
			imageSize = CGSize(width: 16, height: 16)
			textFieldFontSize = 11
		case .large:
			imageSize = CGSize(width: 22, height: 22)
			if #available(macOS 11.0, *) {
				textFieldFontSize = 15
			} else {
				textFieldFontSize = 13
			}
		default:
			imageSize = CGSize(width: 19, height: 19)
			textFieldFontSize = 13
		}

		self.textFieldFont = NSFont.systemFont(ofSize: textFieldFontSize)
	}
}


//
//  SpringBoardLaunchedAppViewController.swift
//  UIPlayground
//
//  Created by Kip Nicol on 9/27/16.
//  Copyright © 2016 Kip Nicol. All rights reserved.
//

import UIKit

class SpringBoardLaunchedAppViewController: UIViewController {

    let exitButton = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .red

        view.addSubview(exitButton)
        exitButton.translatesAutoresizingMaskIntoConstraints = false
        exitButton.anchorConstraintsToCenterInSuperview()
        exitButton.contentEdgeInsets = UIEdgeInsets(top: 7, left: 20, bottom: 7, right: 20)
        exitButton.setTitle("Exit", for: .normal)
        exitButton.setTitleColor(.white, for: .normal)
        exitButton.setTitleColor(.red, for: .highlighted)
        exitButton.titleLabel?.font = .systemFont(ofSize: 26)
        exitButton.addTarget(self, action: #selector(exitPressed), for: .touchUpInside)
        exitButton.backgroundColor = .black
        exitButton.clipsToBounds = true
        exitButton.layer.cornerRadius = 8
    }

    // MARK: - Actions

    func exitPressed(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
}

Set launched app view controller to portrait.

//
//  SpringBoardLaunchedAppViewController.swift
//  UIPlayground
//
//  Created by Kip Nicol on 9/27/16.
//  Copyright © 2016 Kip Nicol. All rights reserved.
//

import UIKit

class SpringBoardLaunchedAppViewController: UIViewController {

    let exitButton = UIButton()

    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .red

        view.addSubview(exitButton)
        exitButton.translatesAutoresizingMaskIntoConstraints = false
        exitButton.anchorConstraintsToCenterInSuperview()
        exitButton.contentEdgeInsets = UIEdgeInsets(top: 7, left: 20, bottom: 7, right: 20)
        exitButton.setTitle("Exit", for: .normal)
        exitButton.setTitleColor(.white, for: .normal)
        exitButton.setTitleColor(.red, for: .highlighted)
        exitButton.titleLabel?.font = .systemFont(ofSize: 26)
        exitButton.addTarget(self, action: #selector(exitPressed), for: .touchUpInside)
        exitButton.backgroundColor = .black
        exitButton.clipsToBounds = true
        exitButton.layer.cornerRadius = 8
    }

    // MARK: - Actions

    func exitPressed(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
}


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

import XCTest

import CoreDataStack

class CoreDataStackTVTests: TempDirectoryTestCase {

    var inMemoryStack: CoreDataStack!
    var sqlStack: CoreDataStack!

    override func setUp() {
        super.setUp()

        let modelName = "TestModel"

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

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

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

    func testInMemoryInitialization() {
        XCTAssertNotNil(inMemoryStack)
    }

    func testSQLiteInitialization() {
        XCTAssertNotNil(sqlStack)
    }
}

Fix library import in the unit tests for tvOS

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

import XCTest

@testable import CoreDataStack

class CoreDataStackTVTests: TempDirectoryTestCase {

    var inMemoryStack: CoreDataStack!
    var sqlStack: CoreDataStack!

    override func setUp() {
        super.setUp()

        let modelName = "TestModel"

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

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

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

    func testInMemoryInitialization() {
        XCTAssertNotNil(inMemoryStack)
    }

    func testSQLiteInitialization() {
        XCTAssertNotNil(sqlStack)
    }
}


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

import XCTest

class BeerTests: XCTestCase {

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

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

}

Add a test for init with name

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

import XCTest
@testable import BreweryDB

class BeerTests: XCTestCase {

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

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

    func testBeerCanBeInitializedWithName() {
        let beer: Beer? = Beer(name: "Beer name")
        XCTAssertNotNil(beer)
    }

}


import UIKit

protocol MCreateMapStatusProtocol
{
    var menuItems:[MCreateMapMenuProtocol] { get }
    var barTop:CGFloat { get }
}

Add required init to protocol

import UIKit

protocol MCreateMapStatusProtocol
{
    var menuItems:[MCreateMapMenuProtocol] { get }
    var barTop:CGFloat { get }

    init()
}


// This test is the same as availability_refinement_contexts_target_min_inlining.swift
// but with a different run invocation to specifically test macCatalyst because
// currently there are no bots that run the tests with macCatalyst as the
// target OS.

// RUN: %target-swift-frontend -swift-version 5 -enable-library-evolution -target %target-cpu-apple-ios14.4-macabi -typecheck -dump-type-refinement-contexts -target-min-inlining-version min %s > %t.dump 2>&1
// RUN: %FileCheck --strict-whitespace %s < %t.dump

// REQUIRES: maccatalyst_support

// Verify that -target-min-inlining-version min implies 13.1 on macCatalyst.

// CHECK: {{^}}(root versions=[13.1,+Inf)
// CHECK-NEXT: {{^}}  (decl_implicit versions=[14.4.0,+Inf) decl=foo()
func foo() {}

Update availability check for VersionTuple change

// This test is the same as availability_refinement_contexts_target_min_inlining.swift
// but with a different run invocation to specifically test macCatalyst because
// currently there are no bots that run the tests with macCatalyst as the
// target OS.

// RUN: %target-swift-frontend -swift-version 5 -enable-library-evolution -target %target-cpu-apple-ios14.4-macabi -typecheck -dump-type-refinement-contexts -target-min-inlining-version min %s > %t.dump 2>&1
// RUN: %FileCheck --strict-whitespace %s < %t.dump

// REQUIRES: maccatalyst_support

// Verify that -target-min-inlining-version min implies 13.1 on macCatalyst.

// CHECK: {{^}}(root versions=[13.1,+Inf)
// CHECK-NEXT: {{^}}  (decl_implicit versions=[14.4,+Inf) decl=foo()
func foo() {}


import Foundation

extension DPlan
{

}

Add origin and destination properties

import Foundation

extension DPlan
{
    var origin:DPlanStop?
    {
        get
        {
            let stop:DPlanStop? = stops?.firstObject as? DPlanStop

            return stop
        }
    }

    var destination:DPlanStop?
    {
        get
        {
            let stop:DPlanStop? = stops?.lastObject as? DPlanStop

            return stop
        }
    }
}


/**
 *  Unbox
 *  Copyright (c) 2015-2017 John Sundell
 *  Licensed under the MIT license, see LICENSE file
 */

import Foundation

internal extension Sequence {
    func map<T>(allowInvalidElements: Bool, transform: (Iterator.Element) throws -> T) throws -> [T] {
        if !allowInvalidElements {
            return try self.map(transform)
        }

        return self.flatMap {
            return try? transform($0)
        }
    }
}

Replace deprecated flatMap with compactMap

/**
 *  Unbox
 *  Copyright (c) 2015-2017 John Sundell
 *  Licensed under the MIT license, see LICENSE file
 */

import Foundation

internal extension Sequence {
    func map<T>(allowInvalidElements: Bool, transform: (Iterator.Element) throws -> T) throws -> [T] {
        if !allowInvalidElements {
            return try self.map(transform)
        }

        return compactMap {
            return try? transform($0)
        }
    }
}


import Quick
import Nimble
@testable import Sourcery
@testable import SourceryRuntime

class VerifierSpec: QuickSpec {
    override func spec() {
        describe("Verifier") {
            it("allows empty strings") {
                expect(Verifier.canParse(content: "")).to(equal(Verifier.Result.approved))
            }

            it("rejects files generated by Sourcery") {
                let content = Sourcery.generationMarker + "\n something\n is\n there"

                expect(Verifier.canParse(content: content)).to(equal(Verifier.Result.isCodeGenerated))
            }

            it("rejects file containing conflict marker") {
                let content = ["\n<<<<<\n", "\n>>>>>\n"]

                content.forEach { expect(Verifier.canParse(content: $0)).to(equal(Verifier.Result.containsConflictMarkers)) }
            }
        }
    }
}

Add tests for the `force-parse` feature

import Quick
import Nimble
@testable import Sourcery
@testable import SourceryRuntime

class VerifierSpec: QuickSpec {
    override func spec() {
        describe("Verifier") {
            it("allows empty strings") {
                expect(Verifier.canParse(content: "", path: Path("/"))).to(equal(Verifier.Result.approved))
            }

            it("rejects files generated by Sourcery") {
                let content = Sourcery.generationMarker + "\n something\n is\n there"

                expect(Verifier.canParse(content: content, path: Path("/"))).to(equal(Verifier.Result.isCodeGenerated))
            }

            it("rejects files generated by Sourcery when a force parse extension is defined but doesn't match file") {
                let content = Sourcery.generationMarker + "\n something\n is\n there"

                expect(Verifier.canParse(content: content, path: Path("/file.swift"), forceParse: ["toparse"])).to(equal(Verifier.Result.isCodeGenerated))
            }

            it("doesn't reject files generated by Soucery but that we want to force the parsing for") {
                let content = Sourcery.generationMarker + "\n something\n is\n there"

                expect(Verifier.canParse(content: content, path: Path("/file.toparse.swift"), forceParse: ["toparse"])).to(equal(Verifier.Result.approved))
            }

            it("rejects file containing conflict marker") {
                let content = ["\n<<<<<\n", "\n>>>>>\n"]

                content.forEach { expect(Verifier.canParse(content: $0, path: Path("/"))).to(equal(Verifier.Result.containsConflictMarkers)) }
            }
        }
    }
}


//
//  UIBarButtonItem.swift
//  Ello
//
//  Created by Sean on 1/19/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import Foundation

extension UIBarButtonItem {

    class func backChevronWithTarget(target:AnyObject, action:Selector) -> UIBarButtonItem {
        let frame = CGRect(x: 20, y: 0, width: 29.0, height: 44.0)
        let button = UIButton(frame: frame)
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
        let image = UIImage(named: "chevron-back-icon")
        button.setImage(image, forState: .Normal)
        button.addTarget(target, action: action, forControlEvents: .TouchUpInside)

        return UIBarButtonItem(customView: button)
    }
}

Fix positioning on back chevron.

//
//  UIBarButtonItem.swift
//  Ello
//
//  Created by Sean on 1/19/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import Foundation

extension UIBarButtonItem {

    class func backChevronWithTarget(target:AnyObject, action:Selector) -> UIBarButtonItem {
        let frame = CGRect(x: 10, y: 0, width: 29.0, height: 44.0)
        let button = UIButton(frame: frame)
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
        let image = UIImage(named: "chevron-back-icon")
        button.setImage(image, forState: .Normal)
        button.addTarget(target, action: action, forControlEvents: .TouchUpInside)

        return UIBarButtonItem(customView: button)
    }
}


import libc
import HTTP
import Bits
import Core
import Foundation
import Dispatch

/// Services files from the public folder.
public final class FileMiddleware: Middleware {
    /// The public directory.
    /// note: does _not_ end with a slash
    let publicDirectory: String

    public var webTypes = [MediaType]()

    /// Creates a new filemiddleware.
    public init(publicDirectory: String) {
        self.publicDirectory = publicDirectory.finished(with: "/")
    }

    /// See Middleware.respond.
    public func respond(to req: Request, chainingTo next: Responder) throws -> Future<Response> {
        return try next.respond(to: req).map { response in
            if response.http.status == 404 {
                let reader = try req.eventLoop.make(FileReader.self, for: FileMiddleware.self)

                var path = req.http.uri.path
                if path.hasPrefix("/") {
                    path = String(path.dropFirst())
                }
                guard !path.contains("../") else {
                    throw Abort(.forbidden)
                }

                let filePath = self.publicDirectory + path

                guard reader.fileExists(at: filePath) else {
                    return response
                }

                return try req.streamFile(at: filePath)
            } else {
                return response
            }
        }
    }
}

Revert filemiddleware running routes before files

import libc
import HTTP
import Bits
import Core
import Foundation
import Dispatch

/// Services files from the public folder.
public final class FileMiddleware: Middleware {
    /// The public directory.
    /// note: does _not_ end with a slash
    let publicDirectory: String

    public var webTypes = [MediaType]()

    /// Creates a new filemiddleware.
    public init(publicDirectory: String) {
        self.publicDirectory = publicDirectory.finished(with: "/")
    }

    /// See Middleware.respond.
    public func respond(to req: Request, chainingTo next: Responder) throws -> Future<Response> {
        let reader = try req.eventLoop.make(FileReader.self, for: FileMiddleware.self)

        var path = req.http.uri.path
        if path.hasPrefix("/") {
            path = String(path.dropFirst())
        }
        guard !path.contains("../") else {
            throw Abort(.forbidden)
        }

        let filePath = self.publicDirectory + path

        guard reader.fileExists(at: filePath) else {
            return try next.respond(to: req)
        }

        return Future(try req.streamFile(at: filePath))
    }
}


import RxSwift

public extension Sugar where HostType: UISwitch {
	/**
	RxSugar wrapper for on property.
	*/
    public var on: ValueBinding<Bool> {
        return controlValueBinding(
            valueChangeEventTypes: .ValueChanged,
            valueGetter: { $0.on },
            valueSetter: { control, value in
                control.on = value
        })
    }
}

Update UISwitch to use updated ValueBinding

import RxSwift

public extension Sugar where HostType: UISwitch {
	/**
	RxSugar wrapper for on property.
	*/
    public var on: ValueBinding<Bool> {
        return controlValueBinding(
            valueChangeEventTypes: .ValueChanged,
            getter: { $0.on },
            setter: { $0.on = $1 })
    }
}


//
//  TestLogic.swift
//  StudyBox_iOS
//
//  Created by user on 12.03.2016.
//  Copyright © 2016 BLStream. All rights reserved.
//

import Foundation

class Test {

    private var deck : [Flashcard]
    private var currentCard : Flashcard?
    private var passedFlashcards = 0
    private var index = 0
    private var numberOfFlashcardsInFullDeck : Int

    init(deck : [Flashcard]) {

        self.deck = deck
        currentFlashcard()
        self.numberOfFlashcardsInFullDeck = deck.count
    }

    func currentFlashcard() {

        var rand : Int

        if(deck.count == 0) {

            currentCard = nil
        }
        else {

            rand = Int(arc4random_uniform(UInt32(deck.count)))
            currentCard = deck[rand]
            deck.removeAtIndex(rand)
            index += 1
        }
    }

    func correctAnswer() { //funkcja podpieta pod przycisk dobra odpowiedz

        passedFlashcards += 1
        currentFlashcard()
    }

    func IncorrectAnswer() {   //funkcja podpieta pod przycisk zla odpowiedz

        currentFlashcard()
    }
}

Edit : w poprzednim commicie zapomnialem skompilowac projektu wiec wrzucam kolejny commit juz po kompilacji

//
//  TestLogic.swift
//  StudyBox_iOS
//
//  Created by user on 12.03.2016.
//  Copyright © 2016 BLStream. All rights reserved.
//

import Foundation

class Test {

    private var deck : [Flashcard]
    private var currentCard : Flashcard?
    private var passedFlashcards = 0
    private var index = 0
    private var numberOfFlashcardsInFullDeck : Int

    init(deck : [Flashcard]) {

        self.deck = deck
        self.numberOfFlashcardsInFullDeck = deck.count
        currentFlashcard()
    }

    func currentFlashcard() {

        var rand : Int

        if(deck.count == 0) {

            currentCard = nil
        }
        else {

            rand = Int(arc4random_uniform(UInt32(deck.count)))
            currentCard = deck[rand]
            deck.removeAtIndex(rand)
            index += 1
        }
    }

    func correctAnswer() { //funkcja podpieta pod przycisk dobra odpowiedz

        passedFlashcards += 1
        currentFlashcard()
    }

    func IncorrectAnswer() {   //funkcja podpieta pod przycisk zla odpowiedz

        currentFlashcard()
    }
}


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

import Foundation

struct ScheduleEventViewModel: Equatable {

    var title: String
    var startTime: String
    var endTime: String
    var location: String
    var bannerGraphicPNGData: Data?
    var isFavourite: Bool
    var isSponsorOnly: Bool
    var isSuperSponsorOnly: Bool
    var isArtShow: Bool
    var isKageEvent: Bool
    var isDealersDenEvent: Bool
    var isMainStageEvent: Bool
    var isPhotoshootEvent: Bool

}

Add protocol type to represent event view model

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

import Foundation

protocol ScheduleEventViewModelProtocol {

    var title: String { get }
    var startTime: String { get }
    var endTime: String { get }
    var location: String { get }
    var bannerGraphicPNGData: Data? { get }
    var isFavourite: Bool { get }
    var isSponsorOnly: Bool { get }
    var isSuperSponsorOnly: Bool { get }
    var isArtShow: Bool { get }
    var isKageEvent: Bool { get }
    var isDealersDenEvent: Bool { get }
    var isMainStageEvent: Bool { get }
    var isPhotoshootEvent: Bool { get }

}

struct ScheduleEventViewModel: ScheduleEventViewModelProtocol, Equatable {

    var title: String
    var startTime: String
    var endTime: String
    var location: String
    var bannerGraphicPNGData: Data?
    var isFavourite: Bool
    var isSponsorOnly: Bool
    var isSuperSponsorOnly: Bool
    var isArtShow: Bool
    var isKageEvent: Bool
    var isDealersDenEvent: Bool
    var isMainStageEvent: Bool
    var isPhotoshootEvent: Bool

}


import SourceKittenFramework

public struct NSObjectPreferIsEqualRule: Rule, ConfigurationProviderRule, AutomaticTestableRule {
    public var configuration = SeverityConfiguration(.warning)

    public init() {}

    public static let description = RuleDescription(
        identifier: "nsobject_prefer_isequal",
        name: "NSObject Prefer isEqual",
        description: "NSObject subclasses should implement isEqual instead of ==.",
        kind: .lint,
        nonTriggeringExamples: NSObjectPreferIsEqualRuleExamples.nonTriggeringExamples,
        triggeringExamples: NSObjectPreferIsEqualRuleExamples.triggeringExamples
    )

    public func validate(file: File) -> [StyleViolation] {
        return []
    }
}

Implement NSObject == linter rule

import SourceKittenFramework

public struct NSObjectPreferIsEqualRule: Rule, ConfigurationProviderRule, AutomaticTestableRule {
    public var configuration = SeverityConfiguration(.warning)

    public init() {}

    public static let description = RuleDescription(
        identifier: "nsobject_prefer_isequal",
        name: "NSObject Prefer isEqual",
        description: "NSObject subclasses should implement isEqual instead of ==.",
        kind: .lint,
        nonTriggeringExamples: NSObjectPreferIsEqualRuleExamples.nonTriggeringExamples,
        triggeringExamples: NSObjectPreferIsEqualRuleExamples.triggeringExamples
    )

    public func validate(file: File) -> [StyleViolation] {
        return objcVisibleClasses(in: file).flatMap { violations(in: file, for: $0) }
    }

    // MARK: - Private

    private func objcVisibleClasses(in file: File) -> [[String: SourceKitRepresentable]] {
        return file.structure.dictionary.substructure.filter { dictionary in
            guard
                let kind = dictionary.kind,
                SwiftDeclarationKind(rawValue: kind) == .class
            else { return false }
            let isDirectNSObjectSubclass = dictionary.inheritedTypes.contains("NSObject")
            let isMarkedObjc = dictionary.enclosedSwiftAttributes.contains(.objc)
            return isDirectNSObjectSubclass || isMarkedObjc
        }
    }

    private func violations(in file: File,
                            for dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
        guard let typeName = dictionary.name else { return [] }
        return dictionary.substructure.compactMap { subDictionary -> StyleViolation? in
            guard
                isDoubleEqualsMethod(subDictionary, onType: typeName),
                let offset = subDictionary.offset
            else { return nil }
            return StyleViolation(ruleDescription: type(of: self).description,
                                  severity: configuration.severity,
                                  location: Location(file: file, byteOffset: offset))
        }
    }

    private func isDoubleEqualsMethod(_ method: [String: SourceKitRepresentable],
                                      onType typeName: String) -> Bool {
        guard
            let kind = method.kind.flatMap(SwiftDeclarationKind.init),
            let name = method.name,
            kind == .functionMethodStatic,
            name == "==(_:_:)",
            areAllArguments(toMethod: method, ofType: typeName)
        else { return false }
        return true
    }

    private func areAllArguments(toMethod method: [String: SourceKitRepresentable],
                                 ofType typeName: String) -> Bool {
        return method.enclosedVarParameters.reduce(true) { soFar, param -> Bool in
            soFar && (param.typeName == typeName)
        }
    }
}


/// Set value for key of an instance
public func set(_ value: Any, key: String, for instance: inout Any) throws {
    try property(type: type(of: instance), key: key).write(value, to: mutableStorage(instance: &instance))
}

/// Set value for key of an instance
public func set(_ value: Any, key: String, for instance: AnyObject) throws {
    var copy: Any = instance
    try set(value, key: key, for: &copy)
}

/// Set value for key of an instance
public func set<T>(_ value: Any, key: String, for instance: inout T, instanceType: Any.Type = T.self) throws {
    try property(type: instanceType, key: key).write(value, to: mutableStorage(instance: &instance, type: instanceType))
}

private func property(type: Any.Type, key: String) throws -> Property.Description {
    guard let property = try properties(type).first(where: { $0.key == key }) else { throw ReflectionError.instanceHasNoKey(type: type, key: key) }
    return property
}

Change method to overload to the one that supported Any

/// Set value for key of an instance
public func set(_ value: Any, key: String, for instance: inout Any, instanceType: Any.Type? = nil) throws {
    let type = instanceType ?? type(of: instance)
    try property(type: type(of: instance), key: key).write(value, to: mutableStorage(instance: &instance, type: type))
}

/// Set value for key of an instance
public func set(_ value: Any, key: String, for instance: AnyObject) throws {
    var copy: Any = instance
    try set(value, key: key, for: &copy)
}

/// Set value for key of an instance
public func set<T>(_ value: Any, key: String, for instance: inout T) throws {
    try property(type: T.self, key: key).write(value, to: mutableStorage(instance: &instance))
}

private func property(type: Any.Type, key: String) throws -> Property.Description {
    guard let property = try properties(type).first(where: { $0.key == key }) else { throw ReflectionError.instanceHasNoKey(type: type, key: key) }
    return property
}


//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

Create UIImage from pixel buffer data

//: Playground - noun: a place where people can play

import UIKit

struct Point2d<T> {
    let x: T
    let y: T
}

struct Pixel {
    let r: UInt8
    let g: UInt8
    let b: UInt8
    let a: UInt8 = 255
}

func createImage(width: Int, height: Int, pixels: [Pixel]) -> UIImage? {
    guard pixels.count == (width * height) else {
        return nil
    }
    let dataProvider = CGDataProviderCreateWithCFData(
        NSData(bytes: pixels, length: pixels.count * sizeof(Pixel))
    )

    let bytesPerPixel = 4
    let bitsPerComponent = 8
    let colourSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
    if let cgImage = CGImageCreate(width, height, bitsPerComponent, bytesPerPixel * 8, bytesPerPixel * width, colourSpace, bitmapInfo, dataProvider, nil, false, .RenderingIntentDefault) {
        let image = UIImage(CGImage: cgImage)
        UIImagePNGRepresentation(image)
        return image
    } else {
        return nil
    }
}

let width = 320
let height = 240
let redPixel = Pixel(r: 255, g: 0, b: 0)
let pixelData = [Pixel](count: width * height, repeatedValue: redPixel)
let image = createImage(width, height: height, pixels: pixelData)


//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport
import NotAutoLayout

let view = LayoutView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
view.backgroundColor = .white
PlaygroundPage.current.liveView = view

typealias LayoutOutput = (condition: LayoutCondition, viewA: LayoutPosition, viewB: LayoutPosition, viewC: LayoutPosition)

let oneThird: CGFloat = 1 / 3

let label: UILabel = {
	let label = UILabel()
	label.backgroundColor = .red
	label.textAlignment = .center
	label.text = "Label A"
	view.addSubview(label)
	return label
}()

let position = LayoutPosition.customByXYWidthHeight(x: { $0.width * 0.8 - 10 },
                                                    y: { _ in 10 },
                                                    width: { $0.width * 0.2 },
                                                    height: { $0.width * 0.2 })
view.setConstantPosition(position, for: label)

view.setNeedsLayout()

Remove unused lines in Playground

//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport
import NotAutoLayout

let view = LayoutView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
view.backgroundColor = .white
PlaygroundPage.current.liveView = view

let label: UILabel = {
	let label = UILabel()
	label.backgroundColor = .red
	label.textAlignment = .center
	label.text = "Label A"
	view.addSubview(label)
	return label
}()

let position = LayoutPosition.customByXYWidthHeight(x: { $0.width * 0.8 - 10 },
                                                    y: { _ in 10 },
                                                    width: { $0.width * 0.2 },
                                                    height: { $0.width * 0.2 })
view.setConstantPosition(position, for: label)

view.setNeedsLayout()


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

extension CollectionType {
	public var uncons: (first: SubSequence._Element, rest: SubSequence)? {
		if !isEmpty {
			let some = self[startIndex..<startIndex.advancedBy(1)]
			return (first: some[some.startIndex], rest: dropFirst())
		}
		return nil
	}

	public var rest: SubSequence {
		return isEmpty
			? self[startIndex..<endIndex]
			: dropFirst()
	}
}

extension CollectionType where SubSequence: CollectionType, SubSequence.SubSequence == SubSequence {
	public var conses: AnyGenerator<(first: SubSequence._Element, rest: SubSequence)> {
		var current = uncons
		return anyGenerator {
			let next = current
			current = current?.rest.uncons
			return next
		}
	}
}

extension CollectionType where SubSequence == Self {
	public func fold<Out>(initial: Out, @noescape combine: (Generator.Element, Out) -> Out) -> Out {
		return first.map {
			combine($0, dropFirst().fold(initial, combine: combine))
		} ?? initial
	}
}

Add a fold overload that will work on Array.

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

extension CollectionType {
	public var uncons: (first: SubSequence._Element, rest: SubSequence)? {
		if !isEmpty {
			let some = self[startIndex..<startIndex.advancedBy(1)]
			return (first: some[some.startIndex], rest: dropFirst())
		}
		return nil
	}

	public var rest: SubSequence {
		return isEmpty
			? self[startIndex..<endIndex]
			: dropFirst()
	}
}

extension CollectionType where SubSequence: CollectionType, SubSequence.SubSequence == SubSequence {
	public var conses: AnyGenerator<(first: SubSequence._Element, rest: SubSequence)> {
		var current = uncons
		return anyGenerator {
			let next = current
			current = current?.rest.uncons
			return next
		}
	}

	public func fold<Out>(initial: Out, @noescape combine: (SubSequence._Element, Out) -> Out) -> Out {
		return self[indices].fold(initial, combine: combine)
	}
}

extension CollectionType where SubSequence == Self {
	public func fold<Out>(initial: Out, @noescape combine: (Generator.Element, Out) -> Out) -> Out {
		return first.map {
			combine($0, dropFirst().fold(initial, combine: combine))
		} ?? initial
	}
}


//
//  Created by Pierluigi Cifani on 12/07/2018.
//

import UIKit

extension UITextField {

    static func autolayoutTextFieldWith(textStyle style: UIFont.TextStyle, placeholderText: String) -> UITextField {
        let textField = UITextField()
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.font = UIFont.preferredFont(forTextStyle: style)
        textField.setContentHuggingPriority(.required, for: .vertical)
        textField.placeholder = placeholderText
        return textField
    }
}

Make sure the textField is using the right font

//
//  Created by Pierluigi Cifani on 12/07/2018.
//

import UIKit

extension UITextField {

    static func autolayoutTextFieldWith(textStyle style: UIFont.TextStyle, placeholderText: String) -> UITextField {
        let textField = UITextField()
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.font = TextStyler.styler.fontForStyle(style)
        textField.setContentHuggingPriority(.required, for: .vertical)
        textField.placeholder = placeholderText
        return textField
    }
}


//
//  Extensions.swift
//  Cartography
//
//  Created by Robert Böhnke on 22/01/15.
//  Copyright (c) 2015 Robert Böhnke. All rights reserved.
//

import Foundation

internal extension Dictionary {
    init (_ pairs: [Element]) {
        self.init()

        for (key, value) in pairs {
            self[key] = value
        }
    }
}

public protocol Number {
    var doubleValue: Double { get }
}

extension Float: Number {
    public var doubleValue: Double {
        return Double(self)
    }
}

extension Double: Number {
    public var doubleValue: Double {
        return self
    }
}

extension CGFloat: Number {
    public var doubleValue: Double {
        return Double(self)
    }
}

Fix CGFloat not being found

//
//  Extensions.swift
//  Cartography
//
//  Created by Robert Böhnke on 22/01/15.
//  Copyright (c) 2015 Robert Böhnke. All rights reserved.
//

#if os(iOS)
    import UIKit
#else
    import AppKit
#endif

internal extension Dictionary {
    init (_ pairs: [Element]) {
        self.init()

        for (key, value) in pairs {
            self[key] = value
        }
    }
}

public protocol Number {
    var doubleValue: Double { get }
}

extension Float: Number {
    public var doubleValue: Double {
        return Double(self)
    }
}

extension Double: Number {
    public var doubleValue: Double {
        return self
    }
}

extension CGFloat: Number {
    public var doubleValue: Double {
        return Double(self)
    }
}


import Foundation

extension Optional {
	func reduce<U>(initial: U, combine: (U, T) -> U) -> U {
		switch self {
		case .None:
			return initial
		case .Some(let value):
			return combine(initial, value)
		}
	}

	func flatMap<U>(transform: T -> U?) -> U? {
		return map(transform).reduce(nil) { $1 }
	}

	func filter(includeElement: T -> Bool) -> T? {
		return flatMap { includeElement($0) ? $0 : nil }
	}

	func each(action: T -> ()) {
		reduce(()) { action($1) }
	}
}

extension Array {
	func flatMap<U>(transform: T -> [U]) -> [U] {
		return map(transform).reduce([], combine: +)
	}

	func each(action: T -> ()) {
		reduce(()) { action($1) }
	}
}

Remove flatMap for Swift 1.2

import Foundation

extension Optional {
	func reduce<U>(initial: U, combine: (U, T) -> U) -> U {
		switch self {
		case .None:
			return initial
		case .Some(let value):
			return combine(initial, value)
		}
	}

	func filter(includeElement: T -> Bool) -> T? {
		return flatMap { includeElement($0) ? $0 : nil }
	}

	func each(action: T -> ()) {
		reduce(()) { action($1) }
	}
}

extension Array {
	func each(action: T -> ()) {
		reduce(()) { action($1) }
	}
}


//
//  Component.swift
//  BoundariesKit
//
//  Created by Andrei Raifura on 9/3/15.
//  Copyright © 2015 YOPESO. All rights reserved.
//

public enum ComponentType {
    case Class
    case Function
    case Comment
    case EmptyLines
}

public struct Component {
    public let type: ComponentType
    public let range: ComponentRange
    public var name: String?
    public let components: [Component]

    public init(type:ComponentType, range: ComponentRange, components:[Component], name: String) {
        self.type = type
        self.range = range
        self.components = components
        self.name = name
    }

    public init(type:ComponentType, range: ComponentRange, components:[Component]) {
        self.type = type
        self.range = range
        self.components = components
    }
}

extension Component : Equatable {}

public func ==(lhs: Component, rhs: Component) -> Bool {
    if lhs.range != rhs.range { return false }
    if lhs.type != rhs.type { return false }
    if lhs.name !~== lhs.name { return false }
    if rhs.components != lhs.components { return false }

    return true
}

Add struct and enum component types

//
//  Component.swift
//  BoundariesKit
//
//  Created by Andrei Raifura on 9/3/15.
//  Copyright © 2015 YOPESO. All rights reserved.
//

public enum ComponentType {
    case Class
    case Function
    case Comment
    case EmptyLines
    case Struct
    case Enum
}

public struct Component {
    public let type: ComponentType
    public let range: ComponentRange
    public var name: String?
    public let components: [Component]

    public init(type:ComponentType, range: ComponentRange, components:[Component], name: String) {
        self.type = type
        self.range = range
        self.components = components
        self.name = name
    }

    public init(type:ComponentType, range: ComponentRange, components:[Component]) {
        self.type = type
        self.range = range
        self.components = components
    }
}

extension Component : Equatable {}

public func ==(lhs: Component, rhs: Component) -> Bool {
    if lhs.range != rhs.range { return false }
    if lhs.type != rhs.type { return false }
    if lhs.name !~== lhs.name { return false }
    if rhs.components != lhs.components { return false }

    return true
}


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

import UIKit

extension UIImage {
    /**
     通过URL路径获取Image

     - parameter contentsOfURL: 图片的 URL 地址
     */
    public convenience init?(contentsOfURL URLString: String) {
        guard let URL = NSURL(string: URLString) else {
            print("UIImage init Error: URL might not exist")
            return nil
        }

        guard let data = NSData(contentsOfURL: URL) else {
            print("UIImage init Error: get data fail")
            return nil
        }

        self.init(data: data)
    }
}

Update the comment for the extension of UIImage

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

import UIKit

extension UIImage {
    /**
     通过 URL 路径获取 Image

     - parameter URLString: 图片的 URL 地址

     - returns: 初始化的 UIImage 对象, 如果不能从该 URL 初始化图像则返回nil
     */
    public convenience init?(contentsOfURL URLString: String) {
        guard let URL = NSURL(string: URLString) else {
            print("UIImage init Error: URL might not exist")
            return nil
        }

        guard let data = NSData(contentsOfURL: URL) else {
            print("UIImage init Error: get data fail")
            return nil
        }

        self.init(data: data)
    }
}


//  Copyright © 2016 Gavan Chan. All rights reserved.

import UIKit

final class RotatingContentController: UIViewController {

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

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

}

import RxSwift

Move module import declarations to the top of the file

//  Copyright © 2016 Gavan Chan. All rights reserved.

import RxCocoa
import RxSwift
import UIKit

final class RotatingContentController: UIViewController {

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

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

}


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

final class ListTests: XCTestCase {
	func testListTypechecks() {
		let kind = Expression<Term>.Variable("List").typecheck(Expression.list.context)
		assert(kind.left, ==, nil)
	}
}

import Assertions
@testable import Manifold
import XCTest

Test that List typechecks as a function from type to type.

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

final class ListTests: XCTestCase {
	func testListTypechecksAsAHigherOrderType() {
		let kind = Expression<Term>.Variable("List").typecheck(Expression.list.context)
		assert(kind.left, ==, nil)
		assert(kind.right, ==, Expression<Term>.lambda(.Type(0), const(.Type(0))))
	}
}

import Assertions
@testable import Manifold
import Prelude
import XCTest


// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s
// REQUIRES: objc_interop
public struct Q<T> {
  let x: T
}
public func foo<T>(arg: [Q<T>]) {
  // CHECK: define {{.*}}_TF12generic_arg43foourFGSaGVS_1Qx__T_
  // CHECK: store %[[TY:.*]]* %0, %[[TY]]** %[[ALLOCA:.*]], align
  // CHECK: call void @llvm.dbg.declare(metadata %[[TY]]** %[[ALLOCA]],
  // CHECK-SAME:       metadata ![[ARG:.*]], metadata ![[EXPR:.*]])
  // No deref here: the array argument is passed by value.
  // CHECK: ![[EXPR]] = !DIExpression()
  // CHECK: ![[ARG]] = !DILocalVariable(name: "arg", arg: 1,
  // CHECK-SAME:                        line: 5,
  // CHECK-SAME:   type: !"_TtGSaGV12generic_arg41QQq_FS_3foourFGSaGS0_x__T___")
}

Replace a hard-coded line number with an @LINE.

// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s
// REQUIRES: objc_interop
public struct Q<T> {
  let x: T
}
  // CHECK: define {{.*}}_TF12generic_arg43foourFGSaGVS_1Qx__T_
  // CHECK: store %[[TY:.*]]* %0, %[[TY]]** %[[ALLOCA:.*]], align
  // CHECK: call void @llvm.dbg.declare(metadata %[[TY]]** %[[ALLOCA]],
  // CHECK-SAME:       metadata ![[ARG:.*]], metadata ![[EXPR:.*]])
  // No deref here: the array argument is passed by value.
  // CHECK: ![[EXPR]] = !DIExpression()
  // CHECK: ![[ARG]] = !DILocalVariable(name: "arg", arg: 1,
  // CHECK-SAME:                        line: [[@LINE+2]],
  // CHECK-SAME:   type: !"_TtGSaGV12generic_arg41QQq_FS_3foourFGSaGS0_x__T___")
public func foo<T>(arg: [Q<T>]) {
}


//
//  Contain.swift
//  Sleipnir
//
//  Created by Artur Termenji on 7/18/14.
//  Copyright (c) 2014 railsware. All rights reserved.
//

import Foundation

class Contain<S: Sequence, T: Equatable where S.GeneratorType.Element == T> : BaseMatcher<S> {

    init(items: S) {
        super.init(expected: items)
    }

    override func match(actual: S?) -> Bool  {
        if !actual {
            return false
        }

        if (actual is String && expected is String) {
            return matchString(actual as String, expected: expected as String)
        } else {
            return matchSequence(actual!, expected: expected!)
        }
    }

    override func failureMessageEnd() -> String {
        return "contain <\(expected)>"
    }

    /// Private

    func matchString(actual: String, expected: String) -> Bool {
        return !actual.rangeOfString(expected).isEmpty
    }

    func matchSequence(actual: S, expected: S) -> Bool {
        var result = true

        for item in expected {
            if !(contains(actual, item)) {
                result = false
            }
        }

        return result
    }
}

func contain<S: Sequence, T: Equatable where S.GeneratorType.Element == T>(items: S) -> Contain<S, T> {
    return Contain(items: items)
}

func contain<T: Equatable>(items: T...) -> Contain<[T], T> {
    return Contain(items: items)
}

Fix contain matcher for strings

//
//  Contain.swift
//  Sleipnir
//
//  Created by Artur Termenji on 7/18/14.
//  Copyright (c) 2014 railsware. All rights reserved.
//

import Foundation

class Contain<S: Sequence, T: Equatable where S.GeneratorType.Element == T> : BaseMatcher<S> {

    init(items: S) {
        super.init(expected: items)
    }

    override func match(actual: S?) -> Bool  {
        if !actual {
            return false
        }

        if (actual is String && expected is String) {
            return matchString(actual as String, expected: expected as String)
        } else {
            return matchSequence(actual!, expected: expected!)
        }
    }

    override func failureMessageEnd() -> String {
        return "contain <\(stringify(expected))>"
    }

    /// Private

    func matchString(actual: String, expected: String) -> Bool {
        return actual.rangeOfString(expected) != nil
    }

    func matchSequence(actual: S, expected: S) -> Bool {
        var result = true

        for item in expected {
            if !(contains(actual, item)) {
                result = false
            }
        }

        return result
    }
}

func contain<S: Sequence, T: Equatable where S.GeneratorType.Element == T>(items: S) -> Contain<S, T> {
    return Contain(items: items)
}

func contain<T: Equatable>(items: T...) -> Contain<[T], T> {
    return Contain(items: items)
}


/*
  RECUR 1 SWIFT

  Simply run with: 'swift-t recur-1.swift | nl'
*/

app (void v) dummy(string parent, int stage, int id, void block)
{
  "echo" ("parent='%3s'"%parent) ("stage="+stage) ("id="+id) ;
}

N = 4; // Data split factor
S = 3; // Maximum stage number (tested up to S=7, 21,844 dummy tasks)

(void v) runstage(int N, int S, string parent, int stage, int id, void block)
{
  string this = parent+int2string(id);
  v = dummy(parent, stage, id, block);
  if (stage < S)
  {
    foreach id_child in [0:N-1]
    {
      runstage(N, S, this, stage+1, id_child, v);
    }
  }
}

int stage = 1;
foreach id in [0:N-1]
{
  runstage(N, S, "", stage, id, propagate());
}

Make N, S accessible from the command line

/*
  RECUR 1 SWIFT

  Simply run with: 'swift-t recur-1.swift | nl'
  Or specify the N, S values:
  'swift-t recur-1.swift -N=6 -S=6 | nl'
  for 55,986 tasks.
*/

import sys;

app (void v) dummy(string parent, int stage, int id, void block)
{
  "echo" ("parent='%3s'"%parent) ("stage="+stage) ("id="+id) ;
}

// Data split factor with default
N = string2int(argv("N", "4"));
// Maximum stage number with default
// (tested up to S=7, 21,844 dummy tasks)
S = string2int(argv("S", "3"));

(void v) runstage(int N, int S, string parent, int stage, int id, void block)
{
  string this = parent+int2string(id);
  v = dummy(parent, stage, id, block);
  if (stage < S)
  {
    foreach id_child in [0:N-1]
    {
      runstage(N, S, this, stage+1, id_child, v);
    }
  }
}

int stage = 1;
foreach id in [0:N-1]
{
  runstage(N, S, "", stage, id, propagate());
}


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

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

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

import PackageType
import Utility
import Build
import POSIX

#if os(Linux)
public func describe(prefix: String, _ conf: Configuration, _ modules: [Module], _ products: [Product], Xcc: [String], Xld: [String], Xswiftc: [String]) throws -> String {
    do {
        return try Build.describe(prefix, conf, modules, products, Xcc: Xcc, Xld: Xld, Xswiftc: Xswiftc)
    } catch {

        // it is a common error on Linux for clang++ to not be installed, but
        // we need it for linking. swiftc itself gives a non-useful error, so
        // we try to help here.
        //FIXME using `which' is non-ideal: it may not be available

        if (try? Utility.popen(["which", "clang++"])) == nil {
            print("warning: clang++ not found: this will cause build failure", toStream: &stderr)
        }

        throw error
    }
}
#endif

Use command instead of which to check if clang++ is installed

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

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

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

import PackageType
import Utility
import Build
import POSIX

#if os(Linux)
public func describe(prefix: String, _ conf: Configuration, _ modules: [Module], _ products: [Product], Xcc: [String], Xld: [String], Xswiftc: [String]) throws -> String {
    do {
        return try Build.describe(prefix, conf, modules, products, Xcc: Xcc, Xld: Xld, Xswiftc: Xswiftc)
    } catch {

        if (try? Utility.popen(["command", "-v", "clang++"])) == nil {
            print("warning: clang++ not found: this will cause build failure", toStream: &stderr)
        }

        throw error
    }
}
#endif


//
// String+Indent.swift
//
// Copyright (c) 2015 Andrey Fidrya
//
// Licensed under the MIT license. For full copyright and license information,
// please see the LICENSE file.
//

import Foundation

extension String {
    /// Indents every line with prefix.
    public func indent(prefix: String = "  ") -> String {
        let lines = split(characters) { $0 == "\n" }

        var result = String()
        result.reserveCapacity(characters.count + lines.count * prefix.characters.count)

        // $1 is String.CharacterView
        result = lines.reduce(result) { $0 + prefix + String($1) + "\n" }

        return result
    }
}

Optimize indentation in debug output

//
// String+Indent.swift
//
// Copyright (c) 2015 Andrey Fidrya
//
// Licensed under the MIT license. For full copyright and license information,
// please see the LICENSE file.
//

import Foundation

extension String {
    /// Indents every line with prefix.
    public func indent(prefix: String = "  ") -> String {
        let lines = split(characters) { $0 == "\n" }

        var result = String()
        result.reserveCapacity(characters.count + lines.count * prefix.characters.count)

        // $1 is String.CharacterView
        //result = lines.reduce(result) { $0 + prefix + String($1) + "\n" }
        // Optimized:
        for line in lines {
            result += prefix
            result += String(line)
            result += "\n"
        }

        return result
    }
}


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

public enum Symbol: Hashable, Printable {
	public init(_ name: String, _ type: Term) {
		self = Named(name, type)
	}

	public init(_ index: Int, _ type: Term) {
		self = Index(index, type)
	}

	case Named(String, Term)
	case Index(Int, Term)

	public var name: String {
		switch self {
		case let Named(name, _):
			return name
		case let Index(index, _):
			return index.description
		}
	}

	public var type: Term {
		switch self {
		case let Named(_, type):
			return type
		case let Index(_, type):
			return type
		}
	}

	// MARK: Hashable

	public var hashValue: Int {
		return
			name.hashValue
		^	type.hashValue
	}

	// MARK: Printable

	public var description: String {
		let comma = ", "
		return "\(name) :: \(type)"
	}
}

public func == (left: Symbol, right: Symbol) -> Bool {
	return
		left.name == right.name
	&&	left.type == right.type
}

// MARK: - Imports

import Manifold

Add static functions to construct symbols.

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

public enum Symbol: Hashable, Printable {
	public init(_ name: String, _ type: Term) {
		self = Named(name, type)
	}

	public init(_ index: Int, _ type: Term) {
		self = Index(index, type)
	}

	public static func named(name: String, _ type: Term) -> Symbol {
		return Named(name, type)
	}

	public static func index(index: Int, _ type: Term) -> Symbol {
		return Index(index, type)
	}

	case Named(String, Term)
	case Index(Int, Term)

	public var name: String {
		switch self {
		case let Named(name, _):
			return name
		case let Index(index, _):
			return index.description
		}
	}

	public var type: Term {
		switch self {
		case let Named(_, type):
			return type
		case let Index(_, type):
			return type
		}
	}

	// MARK: Hashable

	public var hashValue: Int {
		return
			name.hashValue
		^	type.hashValue
	}

	// MARK: Printable

	public var description: String {
		let comma = ", "
		return "\(name) :: \(type)"
	}
}

public func == (left: Symbol, right: Symbol) -> Bool {
	return
		left.name == right.name
	&&	left.type == right.type
}

// MARK: - Imports

import Manifold


//
//  Error.swift
//  FranticApparatus
//
//  Created by Justin Kolb on 9/30/14.
//  Copyright (c) 2014 Justin Kolb. All rights reserved.
//

import Foundation

public class Error {
    public let message: String

    public init(message: String = "") {
        self.message = message
    }
}

public class NSErrorWrapperError : Error, Printable {
    public let cause: NSError

    public init(cause: NSError) {
        self.cause = cause
        super.init(message: cause.localizedDescription)
    }

    public var description: String {
        return cause.description
    }
}

public class OutOfMemoryError : Error { }

Make it easier to print errors

//
//  Error.swift
//  FranticApparatus
//
//  Created by Justin Kolb on 9/30/14.
//  Copyright (c) 2014 Justin Kolb. All rights reserved.
//

import Foundation

public class Error : Printable {
    public let message: String

    public init(message: String = "") {
        self.message = message
    }

    public var description: String {
        return reflect(self).summary + ": " + message
    }
}

public class NSErrorWrapperError : Error, Printable {
    public let cause: NSError

    public init(cause: NSError) {
        self.cause = cause
        super.init(message: cause.description)
    }
}

public class OutOfMemoryError : Error { }


import Foundation

internal struct Util {
    static func createTempDirectory(prefix: String) -> URL? {
        let tempDirPath = NSTemporaryDirectory() + prefix + NSUUID().uuidString
        let tempDirURL = URL(fileURLWithPath: tempDirPath, isDirectory: true)

        do {
            try FileManager.default.createDirectory(at: tempDirURL, withIntermediateDirectories: true,
                attributes: nil)
        } catch {
            return nil
        }

        return tempDirURL
    }
}

Make temp dir prefix optional

import Foundation

internal struct Util {
    static func createTempDirectory(prefix: String = "") -> URL? {
        let tempDirPath = NSTemporaryDirectory() + prefix + NSUUID().uuidString
        let tempDirURL = URL(fileURLWithPath: tempDirPath, isDirectory: true)

        do {
            try FileManager.default.createDirectory(at: tempDirURL, withIntermediateDirectories: true,
                attributes: nil)
        } catch {
            return nil
        }

        return tempDirURL
    }
}


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

import Assertions
import XCTest

final class AssertionsTests: XCTestCase {
	func testAssertingWithOptionalArrays() {
		let array: [Int]? = [1, 2, 3]
		assert(array, ==, [1, 2, 3])
//		XCTAssertEqual(array, [1, 2, 3]) // => error: value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?
	}

	func testAssertingWithOptionalStrings() {
		let string: String? = "hello"
		assert(string, ==, "hello")
//		XCTAssertEqual(string, "hello") // => error: cannot find an overload for 'XCTAssertEqual' that accepts an argument list of type '(String?, String)'
	}

	func testAssertingWithMethods() {
		let set: Set<Int>? = Set([1, 2, 3])
		assert(set, Set.contains, 3)
	}

	func testAssertingPropertyWithPredicate() {
		let string: String? = ""
		assert(string, { $0.isEmpty })
	}

	func testAssertingNilOfEquatableType() {
		let x: Int? = nil
		assert(x, ==, nil)
	}

	func testAssertingNonNilOfEquatableType() {
		let x: Int? = 1
		assert(x, !=, nil)
	}
}

Move imports to the bottom.

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

final class AssertionsTests: XCTestCase {
	func testAssertingWithOptionalArrays() {
		let array: [Int]? = [1, 2, 3]
		assert(array, ==, [1, 2, 3])
//		XCTAssertEqual(array, [1, 2, 3]) // => error: value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?
	}

	func testAssertingWithOptionalStrings() {
		let string: String? = "hello"
		assert(string, ==, "hello")
//		XCTAssertEqual(string, "hello") // => error: cannot find an overload for 'XCTAssertEqual' that accepts an argument list of type '(String?, String)'
	}

	func testAssertingWithMethods() {
		let set: Set<Int>? = Set([1, 2, 3])
		assert(set, Set.contains, 3)
	}

	func testAssertingPropertyWithPredicate() {
		let string: String? = ""
		assert(string, { $0.isEmpty })
	}

	func testAssertingNilOfEquatableType() {
		let x: Int? = nil
		assert(x, ==, nil)
	}

	func testAssertingNonNilOfEquatableType() {
		let x: Int? = 1
		assert(x, !=, nil)
	}
}

// MARK: - Imports

import Assertions
import XCTest


import Vapor
import Validation

public struct JSONValidator: Validator {

    public func validate(_ input: String) throws {
        do {
            _ = try JSON(bytes: input.makeBytes())
        } catch {
            throw Validator.error("Invalid JSON.")
        }
    }
}

Throw error correctly (for real this time)

import Vapor
import Validation

public struct JSONValidator: Validator {

    public func validate(_ input: String) throws {
        do {
            _ = try JSON(bytes: input.makeBytes())
        } catch {
            throw self.error("Invalid JSON.")
        }
    }
}


import UIKit

class CHome:Controller<VHome, MHome>
{
    deinit
    {
        NotificationCenter.default.removeObserver(self)
    }

    override func modelRefresh()
    {
        DispatchQueue.main.async
        { [weak self] in

            self?.asyncRefresh()
        }
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()

        DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
        { [weak self] in

            self?.loadSessionStrategy()
        }
    }

    //MARK: notified

    func notifiedBecameActive(sender notification:Notification)
    {
        model.authLocation(controller:self)
    }

    //MARK: private

    private func asyncRefresh()
    {
    }
}

Validate if home is top vc

import UIKit

class CHome:Controller<VHome, MHome>
{
    deinit
    {
        NotificationCenter.default.removeObserver(self)
    }

    override func modelRefresh()
    {
        DispatchQueue.main.async
        { [weak self] in

            self?.asyncRefresh()
        }
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()

        DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
        { [weak self] in

            self?.loadSessionStrategy()
        }
    }

    //MARK: notified

    func notifiedBecameActive(sender notification:Notification)
    {
        if parent?.childViewControllers.last === self
        {
            model.authLocation(controller:self)
        }
    }

    //MARK: private

    private func asyncRefresh()
    {
    }
}


//
//  Colors.swift
//  passKit
//
//  Created by Danny Moesch on 01.10.19.
//  Copyright © 2019 Bob Sun. All rights reserved.
//

public struct Colors {
    public static let label: UIColor = {
        if #available(iOS 13.0, *) {
            return .label
        }
        return .black
    }()

    public static let secondaryLabel: UIColor = {
        if #available(iOS 13.0, *) {
            return .secondaryLabel
        }
        return .init(red: 60.0, green: 60.0, blue: 67.0, alpha: 0.6)
    }()

    public static let systemBackground: UIColor = {
        if #available(iOS 13.0, *) {
            return .systemBackground
        }
        return .white
    }()

    public static let secondarySystemBackground: UIColor = {
        if #available(iOS 13.0, *) {
            return .secondarySystemBackground
        }
        return .init(red: 242.0, green: 242.0, blue: 247.0, alpha: 1.0)
    }()

    public static let systemRed: UIColor = {
        if #available(iOS 13.0, *) {
            return .systemRed
        }
        return .red
    }()

    public static let systemBlue: UIColor = {
        if #available(iOS 13.0, *) {
            return .systemBlue
        }
        return .blue
    }()
}

Fix ios12 blue and red

//
//  Colors.swift
//  passKit
//
//  Created by Danny Moesch on 01.10.19.
//  Copyright © 2019 Bob Sun. All rights reserved.
//

public struct Colors {
    public static let label: UIColor = {
        if #available(iOS 13.0, *) {
            return .label
        }
        return .black
    }()

    public static let secondaryLabel: UIColor = {
        if #available(iOS 13.0, *) {
            return .secondaryLabel
        }
        return .init(red: 60.0, green: 60.0, blue: 67.0, alpha: 0.6)
    }()

    public static let systemBackground: UIColor = {
        if #available(iOS 13.0, *) {
            return .systemBackground
        }
        return .white
    }()

    public static let secondarySystemBackground: UIColor = {
        if #available(iOS 13.0, *) {
            return .secondarySystemBackground
        }
        return .init(red: 242.0, green: 242.0, blue: 247.0, alpha: 1.0)
    }()

    public static let systemRed: UIColor = {
        return .systemRed
    }()

    public static let systemBlue: UIColor = {
        return .systemBlue
    }()
}


//
//  AZLabel.swift
//  AZViewer
//
//  Created by Ali Zahedi on 1/15/1396 AP.
//  Copyright © 1396 AP Ali Zahedi. All rights reserved.
//

import UIKit

public class AZLabel: UILabel {

    // MARK: Public
    public var aZConstraints: AZConstraint!
    public var loader: AZLoader = AZLoader()
    // MARK: Internal

    /*
     // Only override draw() if you perform custom drawing.
     // An empty implementation adversely affects performance during animation.
     override func draw(_ rect: CGRect) {
     // Drawing code
        super.draw(rect)
     }
    */

    // MARK: Init
    override public init(frame: CGRect) {
        super.init(frame: frame)
        self.defaultInit()
    }

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

    // MARK: Function
    fileprivate func defaultInit(){
        self.loader.parent(parent: self)
        self.aZConstraints = AZConstraint(view: self)
        self.textAlignment = .right
    }
}

Add label padding from top for reorder baseline Persian

//
//  AZLabel.swift
//  AZViewer
//
//  Created by Ali Zahedi on 1/15/1396 AP.
//  Copyright © 1396 AP Ali Zahedi. All rights reserved.
//

import UIKit

public class AZLabel: UILabel {

    // MARK: Public
    public var aZConstraints: AZConstraint!
    public var loader: AZLoader = AZLoader()
    // MARK: Internal

    /*
     // Only override draw() if you perform custom drawing.
     // An empty implementation adversely affects performance during animation.
     override func draw(_ rect: CGRect) {
     // Drawing code
        super.draw(rect)
     }
    */
    override public func drawText(in rect: CGRect) {
        let insets: UIEdgeInsets = UIEdgeInsets(top: 5.0, left: 0.0, bottom: 0.0, right: 0)
        super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))

    }

    // MARK: Init
    override public init(frame: CGRect) {
        super.init(frame: frame)
        self.defaultInit()
    }

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

    // MARK: Function
    fileprivate func defaultInit(){
        self.loader.parent(parent: self)
        self.aZConstraints = AZConstraint(view: self)
        self.textAlignment = .right
    }
}


import Moya
import ReactiveSwift

@available(*, unavailable, renamed: "ReactiveSwiftMoyaProvider")
public class ReactiveCocoaMoyaProvider { }

extension ReactiveSwiftMoyaProvider {
    @available(*, unavailable, renamed: "request(_:)")
    public func request(token: Target) -> SignalProducer<Response, MoyaError> { fatalError() }
}

Add cocoapods conditional import of Moya in ReactiveMoyaAvialability.

#if !COCOAPODS
    import Moya
#endif
import ReactiveSwift

@available(*, unavailable, renamed: "ReactiveSwiftMoyaProvider")
public class ReactiveCocoaMoyaProvider { }

extension ReactiveSwiftMoyaProvider {
    @available(*, unavailable, renamed: "request(_:)")
    public func request(token: Target) -> SignalProducer<Response, MoyaError> { fatalError() }
}


//
//  AKScheduledAction.swift
//  AudioKit For iOS
//
//  Created by David Sweetman on 4/1/17.
//  Copyright © 2017 AudioKit. All rights reserved.
//

import Foundation

class AKScheduledAction {

    private var interval: TimeInterval
    private var block: (() -> Void)
    private var timer: Timer?

    init(interval: TimeInterval, block: @escaping () -> Void) {
        self.interval = interval
        self.block = block
        start()
    }

    dynamic func start() {
        timer?.invalidate()
        timer = nil
        timer = Timer.scheduledTimer(withTimeInterval: interval,
                                     repeats: false,
                                     block: { [weak self] (timer) in
                                        guard timer.isValid else { return }
                                        self?.block()
        })
    }

    dynamic func stop() {
        timer?.invalidate()
        timer = nil
    }

    deinit {
        stop()
    }
}

Use delegate-based Timer initializer instead of block-based to meet iOS 9 req

//
//  AKScheduledAction.swift
//  AudioKit For iOS
//
//  Created by David Sweetman on 4/1/17.
//  Copyright © 2017 AudioKit. All rights reserved.
//

import Foundation

class AKScheduledAction {

    private var interval: TimeInterval
    private var block: (() -> Void)
    private var timer: Timer?

    init(interval: TimeInterval, block: @escaping () -> Void) {
        self.interval = interval
        self.block = block
        start()
    }

    func start() {
        timer?.invalidate()
        timer = Timer.scheduledTimer(timeInterval: interval,
                                     target: self,
                                     selector: #selector(fire(timer:)),
                                     userInfo: nil,
                                     repeats: false)
    }

    func stop() {
        timer?.invalidate()
        timer = nil
    }

    private dynamic func fire(timer: Timer) {
        guard timer.isValid else { return }
        self.block()
    }

    deinit {
        stop()
    }
}