// Copyright (c) 2017 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information

import Foundation

extension ContainerEntryType {

    init(from fileTypeIndicator: UInt8) {
        switch fileTypeIndicator {
        case 48: // "0"
            self = .regular
        case 49: // "1"
            self = .hardLink
        case 50: // "2"
            self = .symbolicLink
        case 51: // "3"
            self = .characterSpecial
        case 52: // "4"
            self = .blockSpecial
        case 53: // "5"
            self = .directory
        case 54: // "6"
            self = .fifo
        case 55: // "7"
            self = .contiguous
        default:
            self = .unknown
        }
    }

}

Set type regular for tar entries with 0 file type indicator

// Copyright (c) 2017 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information

import Foundation

extension ContainerEntryType {

    init(from fileTypeIndicator: UInt8) {
        switch fileTypeIndicator {
        case 0, 48: // "0"
            self = .regular
        case 49: // "1"
            self = .hardLink
        case 50: // "2"
            self = .symbolicLink
        case 51: // "3"
            self = .characterSpecial
        case 52: // "4"
            self = .blockSpecial
        case 53: // "5"
            self = .directory
        case 54: // "6"
            self = .fifo
        case 55: // "7"
            self = .contiguous
        default:
            self = .unknown
        }
    }

}


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

#if !COMPILING_TENSORFLOW_MODULE
import TensorFlow
#endif

@differentiable(vjp: _vjpMSE)
public func meanSquaredError<Scalar: FloatingPoint>(predicted: Tensor<Scalar>,
                                                    expected: Tensor<Scalar>) -> Tensor<Scalar> {
    return (expected - predicted).squared().mean()
}

@usableFromInline func _vjpMSE<Scalar: FloatingPoint>(
    predicted: Tensor<Scalar>, expected: Tensor<Scalar>
) -> (Tensor<Scalar>, (Tensor<Scalar>) -> (Tensor<Scalar>, Tensor<Scalar>)) {
    let result = meanSquaredError(predicted: predicted, expected: expected)
    return (result, { [n = predicted.scalarCountTensor] v in
      let d = 2 * v / Tensor(n)
      return (d, -d)
    })
}

Use generic AD on all functions.

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

#if !COMPILING_TENSORFLOW_MODULE
import TensorFlow
#endif

@differentiable
public func meanSquaredError<Scalar: FloatingPoint>(predicted: Tensor<Scalar>,
                                                    expected: Tensor<Scalar>) -> Tensor<Scalar> {
    return (expected - predicted).squared().mean()
}


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

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

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

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

// MARK: - Imports

import Prelude

Replace the typealias with a struct.

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

/// The type of trees to drop from the input.
public struct Ignore {
	public init() {}
}

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

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

// MARK: - Imports

import Prelude


import SwiftSyntaxBuilder

/// This example will print the following example:
///
///```
/// import Foundation
/// import UIKit
/// class SomeViewController{
///    let tableView: UITableView
/// }
///```

let source = SourceFile {
  ImportDecl(path: "Foundation")
  ImportDecl(path: "UIKit")
  ClassDecl(classKeyword: .class, identifier: "SomeViewController", membersBuilder: {
    VariableDecl(.let, name: "tableView", type: "UITableView")
  })
}

let syntax = source.buildSyntax(format: Format())

var text = ""
syntax.write(to: &text)

print(text)

Use trailing closure in code generation example

import SwiftSyntaxBuilder

/// This example will print the following example:
///
///```
/// import Foundation
/// import UIKit
/// class SomeViewController{
///    let tableView: UITableView
/// }
///```

let source = SourceFile {
  ImportDecl(path: "Foundation")
  ImportDecl(path: "UIKit")
  ClassDecl(identifier: "SomeViewController") {
    VariableDecl(.let, name: "tableView", type: "UITableView")
  }
}

let syntax = source.buildSyntax(format: Format())

var text = ""
syntax.write(to: &text)

print(text)


import PackageDescription

let package = Package(
    name: "SteamPressExample",
    dependencies: [
        .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1),
        .Package(url: "https://github.com/brokenhandsio/SteamPress", majorVersion: 0, minor: 1),
        .Package(url: "https://github.com/vapor/postgresql-provider.git", majorVersion: 1)
    ],
    exclude: [
        "Config",
        "Database",
        "Localization",
        "Public",
        "Resources",
        "Tests",
    ]
)

Use latest version 0 of SteamPress

import PackageDescription

let package = Package(
    name: "SteamPressExample",
    dependencies: [
        .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1),
        .Package(url: "https://github.com/brokenhandsio/SteamPress", majorVersion: 0),
        .Package(url: "https://github.com/vapor/postgresql-provider.git", majorVersion: 1)
    ],
    exclude: [
        "Config",
        "Database",
        "Localization",
        "Public",
        "Resources",
        "Tests",
    ]
)


// swift-tools-version:5.0

import PackageDescription

let package = Package(
    name: "Swinject",
    products: [
        .library(name: "Swinject",
                 targets: ["Swinject"]),
        .library(name: "Swinject-Dynamic",
                 type: .dynamic,
                 targets: ["Swinject"]),
    ],
    targets: [
        .target(name: "Swinject",
                path: "Sources"),
    ]
)

Add explicit supported versions for SPM

// swift-tools-version:5.0

import PackageDescription

let package = Package(
    name: "Swinject",
    platforms: [
        .macOS(.v10_10),
        .iOS(.v9),
        .tvOS(.v9),
        .watchOS(.v2)
    ],
    products: [
        .library(name: "Swinject",
                 targets: ["Swinject"]),
        .library(name: "Swinject-Dynamic",
                 type: .dynamic,
                 targets: ["Swinject"]),
    ],
    targets: [
        .target(name: "Swinject",
                path: "Sources"),
    ]
)


//
// SwiftyUserDefaults
//
// Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

import Foundation

public extension UserDefaults {

    func observe<T: DefaultsSerializable>(key: DefaultsKey<T>, options: NSKeyValueObservingOptions = [.initial, .old, .new], handler: @escaping (DefaultsObserver<T>.Update) -> Void) -> DefaultsDisposable {
        return DefaultsObserver(key: key, userDefaults: self, options: options, handler: handler)
    }
}

Set default options for observing to [.new, .old]

//
// SwiftyUserDefaults
//
// Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

import Foundation

public extension UserDefaults {

    func observe<T: DefaultsSerializable>(key: DefaultsKey<T>, options: NSKeyValueObservingOptions = [.old, .new], handler: @escaping (DefaultsObserver<T>.Update) -> Void) -> DefaultsDisposable {
        return DefaultsObserver(key: key, userDefaults: self, options: options, handler: handler)
    }
}


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

final class AlternationTests: XCTestCase {
	let alternation = %"x" | (%"y" --> const(1))

	func testAlternationParsesEitherAlternative() {
		assertEqual(alternation("xy")?.1, "y")
		assertEqual(alternation("yx")?.1, "x")
	}

	func testAlternationProducesTheParsedAlternative() {
		assert(alternation("xy")?.0, ==, Either.left("x"))
	}

	func testAlternationOfASingleTypeCoalescesTheParsedValue() {
		assertEqual((%"x" | %"y")("xy")?.0, "x")
	}
}

// MARK: - Imports

import Assertions
import Either
import Madness
import Prelude
import XCTest

Correct a nondeterministic test failure :weary:

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

final class AlternationTests: XCTestCase {
	let alternation = %"x" | (%"y" --> const(1))

	func testAlternationParsesEitherAlternative() {
		assertEqual(alternation("xy")?.1, "y")
		assertEqual(alternation("yx")?.1, "x")
	}

	func testAlternationProducesTheParsedAlternative() {
		assert(alternation("xy")?.0, ==, Either.left("x"))
	}

	func testAlternationOfASingleTypeCoalescesTheParsedValue() {
		let parsed = (%"x" | %"y")("xy")
		assertEqual(parsed?.0, "x")
	}
}

// MARK: - Imports

import Assertions
import Either
import Madness
import Prelude
import XCTest


//
//  TweetListInteractor.swift
//  CleanTweeter
//
//  Created by Markus Müller on 29.10.14.
//  Copyright (c) 2014 Markus Müller. All rights reserved.
//

import Foundation

public class TweetListInteractor: TweetListInteractorInput {
	public var output: TweetListInteractorOutput?
	var repository: UserRepository
	let dateFormatter: NSDateComponentsFormatter

	public init(repository: UserRepository) {
		self.repository = repository
		let formatter = NSDateComponentsFormatter()
		formatter.unitsStyle = .Abbreviated
		formatter.allowedUnits = [.Year, .Day, .Hour, .Minute]
		formatter.maximumUnitCount = 1
		self.dateFormatter = formatter
	}

	public func requestTweetsForUserName(userName:String) {
		if let user = self.repository.findUser(userName) {
			let followedUserTweets: [Tweet] = flatten(user.followedUsers.map {
				if let follower = self.repository.findUser($0) {
					return follower.tweets
				}
				return []
			})

			let sortedTweets = (user.tweets + followedUserTweets).sort()

			let result: [TweetListResponseModel] = sortedTweets.map {
				TweetListResponseModel(user: $0.author, content: $0.content, age: self.dateFormatter.stringFromDate($0.publicationDate, toDate: NSDate())!)
			}
			output?.foundTweets(result)
		}
	}
}

Use Swift 2.0 standard library

//
//  TweetListInteractor.swift
//  CleanTweeter
//
//  Created by Markus Müller on 29.10.14.
//  Copyright (c) 2014 Markus Müller. All rights reserved.
//

import Foundation

public class TweetListInteractor: TweetListInteractorInput {
	public var output: TweetListInteractorOutput?
	var repository: UserRepository
	let dateFormatter: NSDateComponentsFormatter

	public init(repository: UserRepository) {
		self.repository = repository
		let formatter = NSDateComponentsFormatter()
		formatter.unitsStyle = .Abbreviated
		formatter.allowedUnits = [.Year, .Day, .Hour, .Minute]
		formatter.maximumUnitCount = 1
		self.dateFormatter = formatter
	}

	public func requestTweetsForUserName(userName:String) {
		if let user = self.repository.findUser(userName) {
			let followedUserTweets: [[Tweet]] = user.followedUsers.map {
				if let follower = self.repository.findUser($0) {
					return follower.tweets
				}
				return []
			}

			let sortedTweets = (user.tweets + followedUserTweets.flatMap{ $0 }).sort()

			let result: [TweetListResponseModel] = sortedTweets.map {
				TweetListResponseModel(user: $0.author, content: $0.content, age: self.dateFormatter.stringFromDate($0.publicationDate, toDate: NSDate())!)
			}
			output?.foundTweets(result)
		}
	}
}


import PackageDescription

let package = Package(
    name: "BasicAuthMiddleware",
    dependencies: [
        .Package(url: "https://github.com/Zewo/HTTP.git", majorVersion: 0, minor: 5),
        .Package(url: "https://github.com/Zewo/Base64.git", majorVersion: 0, minor: 5),
        .Package(url: "https://github.com/Zewo/String.git", majorVersion: 0, minor: 5),
    ]
)

Update Base64 dependency to 0.7

import PackageDescription

let package = Package(
    name: "BasicAuthMiddleware",
    dependencies: [
        .Package(url: "https://github.com/Zewo/HTTP.git", majorVersion: 0, minor: 5),
        .Package(url: "https://github.com/Zewo/Base64.git", majorVersion: 0, minor: 7),
        .Package(url: "https://github.com/Zewo/String.git", majorVersion: 0, minor: 5),
    ]
)


//
//  ShotCellReactor.swift
//  Drrrible
//
//  Created by Suyeol Jeon on 09/03/2017.
//  Copyright © 2017 Suyeol Jeon. All rights reserved.
//

import ReactorKit
import RxCocoa
import RxSwift

final class ShotCellReactor: Reactor {
  typealias Action = NoAction

  struct State {
    var imageURL: URL

    init(imageURL: URL) {
      self.imageURL = imageURL
    }
  }

  let provider: ServiceProviderType
  let shot: Shot
  let initialState: State

  init(provider: ServiceProviderType, shot: Shot) {
    self.provider = provider
    self.shot = shot
    self.initialState = State(imageURL: shot.imageURLs.teaser)
  }
}

Use normal image in ShotTileCell

//
//  ShotCellReactor.swift
//  Drrrible
//
//  Created by Suyeol Jeon on 09/03/2017.
//  Copyright © 2017 Suyeol Jeon. All rights reserved.
//

import ReactorKit
import RxCocoa
import RxSwift

final class ShotCellReactor: Reactor {
  typealias Action = NoAction

  struct State {
    var imageURL: URL

    init(imageURL: URL) {
      self.imageURL = imageURL
    }
  }

  let provider: ServiceProviderType
  let shot: Shot
  let initialState: State

  init(provider: ServiceProviderType, shot: Shot) {
    self.provider = provider
    self.shot = shot
    self.initialState = State(imageURL: shot.imageURLs.normal)
  }
}


//
//  Device
//  Thingy
//
//  Created by Bojan Dimovski on 19/01/2020.
//  Copyright © 2020 Bojan Dimovski. All rights reserved.
//

import Foundation

public extension Device {

	/// Product line of the model, currently supported only for the iPad.
	var productLine: ProductLine? {
		switch self {
		case .iPad2,
		     .iPad3,
		     .iPad4,
		     .iPad5,
		     .iPad6,
		     .iPad7:
			return Lines.iPad.regular
		case .iPadAir,
		     .iPadAir2,
		     .iPadAir3:
			return Lines.iPad.air
		case .iPadPro12Inch,
		     .iPadPro12Inch2G,
		     .iPadPro12Inch3G,
		     .iPadPro9Inch,
		     .iPadPro10Inch,
		     .iPadPro11Inch:
			return Lines.iPad.pro
		case .iPadMini,
		     .iPadMini2,
		     .iPadMini3,
		     .iPadMini4,
		     .iPadMini5:
			return Lines.iPad.mini
		default:
			return nil
		}
	}

}

Improve the product line check and add support for the iPhone lines.

//
//  Device
//  Thingy
//
//  Created by Bojan Dimovski on 19/01/2020.
//  Copyright © 2020 Bojan Dimovski. All rights reserved.
//

import Foundation

public extension Device {

	/// Product line of the model, currently supported only for the iPad.
	var productLine: ProductLine? {
		switch family {
		case .pad:
			switch self {
			case .iPadAir,
			     .iPadAir2,
			     .iPadAir3:
				return Lines.iPad.air
			case .iPadPro12Inch,
			     .iPadPro12Inch2G,
			     .iPadPro12Inch3G,
			     .iPadPro9Inch,
			     .iPadPro10Inch,
			     .iPadPro11Inch:
				return Lines.iPad.pro
			case .iPadMini,
			     .iPadMini2,
			     .iPadMini3,
			     .iPadMini4,
			     .iPadMini5:
				return Lines.iPad.mini
			default:
				return Lines.iPad.standard
			}
		case .phone:
			switch self {
			case .iPhoneSE,
			     .iPhoneSE2G:
				return Lines.iPhone.se
			case .iPhoneX,
			     .iPhoneXS,
			     .iPhoneXSMax,
			     .iPhone11Pro,
			     .iPhone11ProMax:
				return Lines.iPhone.pro
			default:
				return Lines.iPhone.standard
			}
		default:
			return nil
		}
	}

}


// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o Swift.swiftmodule -O -sil-inline-threshold 0 -module-name Swift -module-link-name swiftCore -parse-as-library -parse-stdlib -emit-module %S/Inputs/vtable-function-deserialization-input.swift -o %t/Swift.swiftmodule
// RUN: %target-swift-frontend -I %t %s -emit-sil -o - -O -sil-link-all

import Swift

var a = A()

Remove obsolete output from test.

// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -O -sil-inline-threshold 0 -module-name Swift -module-link-name swiftCore -parse-as-library -parse-stdlib -emit-module %S/Inputs/vtable-function-deserialization-input.swift -o %t/Swift.swiftmodule
// RUN: %target-swift-frontend -I %t %s -emit-sil -o - -O -sil-link-all

import Swift

var a = A()


//
//  ShadowView.swift
//  breadwallet
//
//  Created by Adrian Corscadden on 2016-11-17.
//  Copyright © 2016 breadwallet LLC. All rights reserved.
//

import UIKit

class MaskedShadow: UIView {

    var style: TransactionCellStyle = .middle {
        didSet {
            setNeedsLayout()
        }
    }
    private let shadowSize: CGFloat = 8.0

    override func layoutSubviews() {
        var shadowRect = bounds.insetBy(dx: 0, dy: -shadowSize)
        var maskRect = bounds.insetBy(dx: -shadowSize, dy: 0)

        if style == .first {
            maskRect.origin.y -= shadowSize
            maskRect.size.height += shadowSize
            shadowRect.origin.y += shadowSize
        }

        if style == .last {
            maskRect.size.height += shadowSize
            shadowRect.size.height -= shadowSize
        }

        let maskLayer = CAShapeLayer()
        maskLayer.path = UIBezierPath(rect: maskRect).cgPath
        layer.mask = maskLayer
        layer.shadowPath = UIBezierPath(rect: shadowRect).cgPath
    }
}

Make transaction cells work with single transaction

//
//  ShadowView.swift
//  breadwallet
//
//  Created by Adrian Corscadden on 2016-11-17.
//  Copyright © 2016 breadwallet LLC. All rights reserved.
//

import UIKit

class MaskedShadow: UIView {

    var style: TransactionCellStyle = .middle {
        didSet {
            setNeedsLayout()
        }
    }
    private let shadowSize: CGFloat = 8.0

    override func layoutSubviews() {

        guard style != .single else {
            layer.shadowPath = UIBezierPath(rect: bounds).cgPath
            return
        }

        var shadowRect = bounds.insetBy(dx: 0, dy: -shadowSize)
        var maskRect = bounds.insetBy(dx: -shadowSize, dy: 0)

        if style == .first {
            maskRect.origin.y -= shadowSize
            maskRect.size.height += shadowSize
            shadowRect.origin.y += shadowSize
        }

        if style == .last {
            maskRect.size.height += shadowSize
            shadowRect.size.height -= shadowSize
        }

        let maskLayer = CAShapeLayer()
        maskLayer.path = UIBezierPath(rect: maskRect).cgPath
        layer.mask = maskLayer
        layer.shadowPath = UIBezierPath(rect: shadowRect).cgPath
    }
}


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

import SwiftSyntax

extension VariableDecl {
  /// Creates an optionally initialized property.
  public init(
    leadingTrivia: Trivia = [],
    _ letOrVarKeyword: TokenSyntax,
    name: ExpressibleAsIdentifierPattern,
    type: ExpressibleAsTypeAnnotation? = nil,
    initializer: ExpressibleAsInitializerClause? = nil
  ) {
    self.init(leadingTrivia: leadingTrivia, letOrVarKeyword: letOrVarKeyword) {
      PatternBinding(
        pattern: name,
        typeAnnotation: type,
        initializer: initializer
      )
    }
  }

  /// Creates a computed property with the given accessor.
  public init(
    leadingTrivia: Trivia = [],
    modifiers: ModifierList? = nil,
    name: ExpressibleAsIdentifierPattern,
    type: ExpressibleAsTypeAnnotation,
    @CodeBlockItemListBuilder accessor: () -> ExpressibleAsCodeBlockItemList
  ) {
    self.init(leadingTrivia: leadingTrivia, modifiers: modifiers, letOrVarKeyword: .var) {
      PatternBinding(
        pattern: name,
        typeAnnotation: type,
        accessor: CodeBlock(statements: accessor())
      )
    }
  }
}

Add modifiers parameter to VariableDecl convenience init

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

import SwiftSyntax

extension VariableDecl {
  /// Creates an optionally initialized property.
  public init(
    leadingTrivia: Trivia = [],
    modifiers: ModifierList? = nil,
    _ letOrVarKeyword: TokenSyntax,
    name: ExpressibleAsIdentifierPattern,
    type: ExpressibleAsTypeAnnotation? = nil,
    initializer: ExpressibleAsInitializerClause? = nil
  ) {
    self.init(leadingTrivia: leadingTrivia, modifiers: modifiers, letOrVarKeyword: letOrVarKeyword) {
      PatternBinding(
        pattern: name,
        typeAnnotation: type,
        initializer: initializer
      )
    }
  }

  /// Creates a computed property with the given accessor.
  public init(
    leadingTrivia: Trivia = [],
    modifiers: ModifierList? = nil,
    name: ExpressibleAsIdentifierPattern,
    type: ExpressibleAsTypeAnnotation,
    @CodeBlockItemListBuilder accessor: () -> ExpressibleAsCodeBlockItemList
  ) {
    self.init(leadingTrivia: leadingTrivia, modifiers: modifiers, letOrVarKeyword: .var) {
      PatternBinding(
        pattern: name,
        typeAnnotation: type,
        accessor: CodeBlock(statements: accessor())
      )
    }
  }
}


//
// Email.swift
//
// This source file is part of the SMUD open source project
//
// Copyright (c) 2016 SMUD project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SMUD project authors
//

import Foundation

class Email {
    static func isValidEmail(_ email: String) -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
        #if os(OSX)
        return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
        #else
        return Predicate(format: "SELF MATCHES %@", argumentArray: [NSString(string: emailRegex)]).evaluate(with: NSString(string: email))
        #endif
    }
}

Replace email validation with Linux-compatible version

//
// Email.swift
//
// This source file is part of the SMUD open source project
//
// Copyright (c) 2016 SMUD project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SMUD project authors
//

import Foundation

class Email {
    static func isValidEmail(_ email: String) -> Bool {
        let regex = try! RegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$",
            options: [.caseInsensitive])
        return regex.firstMatch(in: email, options: [],
            range: NSMakeRange(0, email.utf16.count)) != nil
    }
}


//
//  UserDefaultsStoreTests.swift
//  StoreKitUserInfo
//
//  Created by Jakub Olejník on 04/05/2017.
//  Copyright © 2017 CocoaPods. All rights reserved.
//

import XCTest
@testable import StoreKitUserInfo

class UserDefaultsStoreTests: XCTestCase {

    var store: StoreKitUserInfoStore!

    // MARK: Setup

    override func setUp() {
        store = UserDefaults(suiteName: name!)!
    }

    // MARK: Tests

    func testGettingNilValuesWhenEmpty() {
        let key = String.random
        let int: Int? = store.loadUserInfo(forKey: key)

        XCTAssertNil(int)
    }

    func testSavingIntValues() {
        let int = Int.random
        let key = String.random

        store.save(userInfo: int, forKey: key)

        let savedInt: Int? = store.loadUserInfo(forKey: key)

        XCTAssertEqual(int, savedInt)
    }

    func testSavingStringValues() {
        let string = String.random
        let key = String.random

        store.save(userInfo: string, forKey: key)

        let savedString: String? = store.loadUserInfo(forKey: key)

        XCTAssertEqual(string, savedString)
    }
}

Add deletion test for store

//
//  UserDefaultsStoreTests.swift
//  StoreKitUserInfo
//
//  Created by Jakub Olejník on 04/05/2017.
//  Copyright © 2017 CocoaPods. All rights reserved.
//

import XCTest
@testable import StoreKitUserInfo

class UserDefaultsStoreTests: XCTestCase {

    var store: StoreKitUserInfoStore!

    // MARK: Setup

    override func setUp() {
        store = UserDefaults(suiteName: name!)!
    }

    // MARK: Tests

    func testGettingNilValuesWhenEmpty() {
        let key = String.random
        let int: Int? = store.loadUserInfo(forKey: key)

        XCTAssertNil(int)
    }

    func testSavingIntValues() {
        let int = Int.random
        let key = String.random

        store.save(userInfo: int, forKey: key)

        let savedInt: Int? = store.loadUserInfo(forKey: key)

        XCTAssertEqual(int, savedInt)
    }

    func testSavingStringValues() {
        let string = String.random
        let key = String.random

        store.save(userInfo: string, forKey: key)

        let savedString: String? = store.loadUserInfo(forKey: key)

        XCTAssertEqual(string, savedString)
    }

    func testDeletion() {
        let string = String.random
        let key = String.random

        store.save(userInfo: string, forKey: key)

        let savedString: String? = store.loadUserInfo(forKey: key)

        XCTAssertEqual(string, savedString)

        store.deleteUserInfo(forKey: key)

        let savedString2: String? = store.loadUserInfo(forKey: key)

        XCTAssertNil(savedString2)
    }
}


//
//  ContentViewController.swift
//  AppearanceNavigationController
//
//  Created by zen on 28/10/15.
//  Copyright © 2015 Zen. All rights reserved.
//

import Foundation
import UIKit

class ContentViewController: UIViewController, AppearanceNavigationControllerContent {

    var appearance: Appearance? {
        didSet {
            setNeedsUpdateNavigationControllerAppearance()
        }
    }

    // mark: - Actions

    // mark: - AppearanceNavigationControllerContent

    func prefersNavigationControllerToolbarHidden(navigationController: AppearanceNavigationController) -> Bool {
        return editing
    }

    func preferredNavigationControllerAppearance(navigationController: AppearanceNavigationController) -> Appearance? {
        return editing ? appearance?.inversedAppearance : appearance
    }
}

Add editing handling in content view controller

//
//  ContentViewController.swift
//  AppearanceNavigationController
//
//  Created by zen on 28/10/15.
//  Copyright © 2015 Zen. All rights reserved.
//

import Foundation
import UIKit

class ContentViewController: UIViewController, AppearanceNavigationControllerContent {

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

        navigationItem.rightBarButtonItem = editButtonItem()
    }

    var appearance: Appearance? {
        didSet {
            setNeedsUpdateNavigationControllerAppearance()
        }
    }

    // mark: - Actions

    override func setEditing(editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)

        setNeedsStatusBarAppearanceUpdate()
    }

    // mark: - AppearanceNavigationControllerContent

    func prefersNavigationControllerToolbarHidden(navigationController: AppearanceNavigationController) -> Bool {
        return editing
    }

    func preferredNavigationControllerAppearance(navigationController: AppearanceNavigationController) -> Appearance? {
        return editing ? appearance?.inversedAppearance : appearance
    }
}


//
//  Wallet+ViewModels.swift
//  breadwallet
//
//  Created by Adrian Corscadden on 2017-01-12.
//  Copyright © 2017 breadwallet LLC. All rights reserved.
//

import Foundation
import BRCore

extension BRWallet {
    func makeTransactionViewModels(blockHeight: UInt32) -> [Transaction] {
        return transactions.flatMap{ $0 }.sorted{ $0.pointee.timestamp > $1.pointee.timestamp }.map {
            return Transaction($0, wallet: self, blockHeight: blockHeight)
        }
    }
}

Move transactions with 0 timestamp to top of list

//
//  Wallet+ViewModels.swift
//  breadwallet
//
//  Created by Adrian Corscadden on 2017-01-12.
//  Copyright © 2017 breadwallet LLC. All rights reserved.
//

import Foundation
import BRCore

extension BRWallet {
    func makeTransactionViewModels(blockHeight: UInt32) -> [Transaction] {
        return transactions.flatMap{ $0 }.sorted {
                if $0.pointee.timestamp == 0 {
                    return true
                } else {
                    return $0.pointee.timestamp > $1.pointee.timestamp
                }
            }.map {
                return Transaction($0, wallet: self, blockHeight: blockHeight)
            }
    }
}


//
//  Droplet+VaporJsonApi.swift
//  VaporJsonApi
//
//  Created by Koray Koska on 10/05/2017.
//
//

import Vapor
import HTTP

public extension Droplet {

    public func jsonApiResource<C: JsonApiResourceController>(controller: C) {
        let resourceType = controller.resourceType.parse()
        // Get routes
        group(resourceType) { resourceType in
            resourceType.get(handler: controller.getResources)
            get(String.self, handler: controller.getResource)
            get(String.self, String.self, handler: controller.getRelatedResource)
            get(String.self, "relationships", String.self, handler: controller.getRelationships)
        }

        // Post routes
        post(resourceType, handler: controller.postResource)
    }
}

Add missing prefix to droplet route group

//
//  Droplet+VaporJsonApi.swift
//  VaporJsonApi
//
//  Created by Koray Koska on 10/05/2017.
//
//

import Vapor
import HTTP

public extension Droplet {

    public func jsonApiResource<C: JsonApiResourceController>(controller: C) {
        let resourceType = controller.resourceType.parse()
        // Get routes
        group(resourceType) { resourceType in
            resourceType.get(handler: controller.getResources)
            resourceType.get(String.self, handler: controller.getResource)
            resourceType.get(String.self, String.self, handler: controller.getRelatedResource)
            resourceType.get(String.self, "relationships", String.self, handler: controller.getRelationships)
        }

        // Post routes
        post(resourceType, handler: controller.postResource)
    }
}


/**
 * Question Link: https://leetcode.com/problems/intersection-of-two-arrays-ii/
 * Primary idea: Sort and iterate to find all common elements
 * Note: Set cannot help you to find the number of common elements; thus it is not effective
 *
 * Time Complexity: O(nlogn), Space Complexity: O(n)
 *
 */

 class IntersectionTwoArraysII {
    func intersect(nums1: [Int], _ nums2: [Int]) -> [Int] {
        var nums1 = nums1.sorted(by: <)
        var nums2 = nums2.sorted(by: <)

        var i = 0
        var j = 0
        var res = [Int]()

        while i < nums1.count && j < nums2.count {
            if nums1[i] < nums2[j] {
                i += 1
            } else if nums1[i] > nums2[j] {
                j += 1
            } else {
                res.append(nums1[i])
                i += 1
                j += 1
            }
        }

        return res
    }
}

Optimize the solution to Intersection of Two Arrays II

/**
 * Question Link: https://leetcode.com/problems/intersection-of-two-arrays-ii/
 * Primary idea: Use dictionary to get frequencies of elements of one array, and
 *               compare with another array to filter the intersection
 * Note: Set cannot help you to find the number of common elements; thus it is not effective
 *
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 */

 class IntersectionTwoArraysII {
    func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
        var frequencies = Dictionary(nums1.map { ($0, 1) } , uniquingKeysWith: +)
        var res = [Int]()

        for num in nums2 {
            guard let frequent = frequencies[num] else {
                continue
            }

            if frequent > 0 {
                frequencies[num]! = frequent - 1
                res.append(num)
            }
        }

        return res
    }
}


//
//  MovieTests.swift
//  Architectures
//
//  Created by Fabijan Bajo on 20/05/2017.
//
//

import XCTest
@testable import MVC

class MovieTests: XCTestCase {

    // MARK: - Related to every test

    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()
    }

    // MARK: - Initialization

    func test_Init_WhenGivenTitle_SetsTitle() {

    }

}

Add Movie object initialization tests

//
//  MovieTests.swift
//  Architectures
//
//  Created by Fabijan Bajo on 20/05/2017.
//
//

import XCTest
@testable import MVC

class MovieTests: XCTestCase {

    // MARK: - Related to every test

    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()
    }

    // MARK: - Initialization

    func test_Init_WhenGivenTitle_SetsTitle() {
        let movie = Movie(title: "Foo", posterPath: "", movieID: 0, releaseDate: Date(), averageRating: 0.0)
        XCTAssertEqual(movie.title, "Foo")
    }
    func test_Init_WhenGivenPosterPath_SetsPosterPath() {
        let movie = Movie(title: "", posterPath: "Foo", movieID: 0, releaseDate: Date(), averageRating: 0.0)
        XCTAssertEqual(movie.posterPath, "Foo")
    }
    func test_Init_WhenGivenID_SetsID() {
        let movie = Movie(title: "", posterPath: "", movieID: 1, releaseDate: Date(), averageRating: 0.0)
        XCTAssertEqual(movie.movieID, 1)
    }
    func test_Init_WhenGivenReleaseDate_SetsReleaseDate() {
        let dateNow = Date()
        let movie = Movie(title: "", posterPath: "", movieID: 0, releaseDate: dateNow, averageRating: 0.0)
        XCTAssertEqual(movie.releaseDate, dateNow)
    }
    func test_Init_WhenGivenRating_SetsRating() {
        let movie = Movie(title: "", posterPath: "", movieID: 0, releaseDate: Date(), averageRating: 1.0)
        XCTAssertEqual(movie.averageRating, 1.0)
    }

}


//
//  User.swift
//  TOZ_iOS
//
//  Copyright © 2017 intive. All rights reserved.
//

import Foundation

final class User {
    private(set) var isSignedIn: Bool

    static var shared: User = User(token: BackendAuth.shared.token)

    init(token: String?) {
        if token != nil {
            self.isSignedIn = true
        } else {
            self.isSignedIn = false
        }
    }
}

Make isSignedIn a computed property

//
//  User.swift
//  TOZ_iOS
//
//  Copyright © 2017 intive. All rights reserved.
//

import Foundation

final class User {
    static let shared: User = User()

    var isSignedIn: Bool {
        if BackendAuth.shared.token != nil {
            return true
        } else {
            return false
        }
    }
}


// RUN: %target-typecheck-verify-swift

protocol P1 {}
protocol P2 {}

struct Var<N> {}

extension Var : P2 where N : P1 { }

protocol P3 {}
extension Var : P3 where Self : P2 {} // expected-error {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'Var'?}}
// expected-error@-1 {{type 'Var<N>' in conformance requirement does not refer to a generic parameter or associated type}}

Update fixed crasher validation test


//
//  UnreadIndicatorView.swift
//  Evergreen
//
//  Created by Brent Simmons on 2/16/16.
//  Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//

import AppKit

class UnreadIndicatorView: NSView {

	static let unreadCircleDimension = appDelegate.currentTheme.float(forKey: "MainWindow.Timeline.cell.unreadCircleDimension")

	static let bezierPath: NSBezierPath = {
		let r = NSRect(x: 0.0, y: 0.0, width: unreadCircleDimension, height: unreadCircleDimension)
		return NSBezierPath(ovalIn: r)
	}()

	static let unreadCircleColor = appDelegate.currentTheme.color(forKey: "MainWindow.Timeline.cell.unreadCircleColor")

	var isEmphasized = false {
		didSet {
			if isEmphasized != oldValue {
				needsDisplay = true
			}
		}
	}

	var isSelected = false {
		didSet {
			if isSelected != oldValue {
				needsDisplay = true
			}
		}
	}

    override func draw(_ dirtyRect: NSRect) {

		let color = isEmphasized && isSelected ? NSColor.white : UnreadIndicatorView.unreadCircleColor
		color.setFill()
		UnreadIndicatorView.bezierPath.fill()
    }

}

Use controlAccent color for unread indicator in timeline.

//
//  UnreadIndicatorView.swift
//  Evergreen
//
//  Created by Brent Simmons on 2/16/16.
//  Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//

import AppKit

class UnreadIndicatorView: NSView {

	static let unreadCircleDimension = appDelegate.currentTheme.float(forKey: "MainWindow.Timeline.cell.unreadCircleDimension")

	static let bezierPath: NSBezierPath = {
		let r = NSRect(x: 0.0, y: 0.0, width: unreadCircleDimension, height: unreadCircleDimension)
		return NSBezierPath(ovalIn: r)
	}()

	static let unreadCircleColor = appDelegate.currentTheme.color(forKey: "MainWindow.Timeline.cell.unreadCircleColor")

	var isEmphasized = false {
		didSet {
			if isEmphasized != oldValue {
				needsDisplay = true
			}
		}
	}

	var isSelected = false {
		didSet {
			if isSelected != oldValue {
				needsDisplay = true
			}
		}
	}

    override func draw(_ dirtyRect: NSRect) {

		if #available(OSX 10.14, *) {
			let color = isEmphasized && isSelected ? NSColor.white : NSColor.controlAccent
			color.setFill()
		} else {
			let color = isEmphasized && isSelected ? NSColor.white : NSColor.systemBlue
			color.setFill()
		}
		UnreadIndicatorView.bezierPath.fill()
    }

}


//
//  InstagramMediaCell.swift
//  Yep
//
//  Created by NIX on 15/5/14.
//  Copyright (c) 2015年 Catch Inc. All rights reserved.
//

import UIKit
import Kingfisher

let MediaOptionsInfos: KingfisherOptionsInfo = [
    .Options([.BackgroundDecode])
]

class InstagramMediaCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()

        imageView.contentMode = .ScaleAspectFill
    }

    func configureWithInstagramMedia(media: InstagramWork.Media) {

        imageView.kf_showIndicatorWhenLoading = true
        imageView.kf_setImageWithURL(NSURL(string: media.images.lowResolution)!, placeholderImage: nil, optionsInfo: MediaOptionsInfos)
    }
}

Use more option on kingfisher

//
//  InstagramMediaCell.swift
//  Yep
//
//  Created by NIX on 15/5/14.
//  Copyright (c) 2015年 Catch Inc. All rights reserved.
//

import UIKit
import Kingfisher

let MediaOptionsInfos: KingfisherOptionsInfo = [
    .Options([.BackgroundDecode, .ScreenScale])
]

class InstagramMediaCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()

        imageView.contentMode = .ScaleAspectFill
    }

    func configureWithInstagramMedia(media: InstagramWork.Media) {

        imageView.kf_showIndicatorWhenLoading = true
        imageView.kf_setImageWithURL(NSURL(string: media.images.lowResolution)!, placeholderImage: nil, optionsInfo: MediaOptionsInfos)
    }
}


/// Possible relations between items in a group
public enum QueryGroupRelation {
    case and, or
}

extension QueryBuilder {
    public typealias GroupClosure = (QueryBuilder<Model>) throws -> ()

    /// Create a query group.
    @discardableResult
    public func group(
        _ relation: QueryGroupRelation,
        closure: @escaping GroupClosure
    ) rethrows -> Self {
        let sub = copy()
        try closure(sub)
        let filter = QueryFilter(
            entity: Model.entity,
            method: .group(.or, sub.query.filters)
        )
        return addFilter(filter)
    }
}

Fix grouping several filters with `AND` instead of `OR`

/// Possible relations between items in a group
public enum QueryGroupRelation {
    case and, or
}

extension QueryBuilder {
    public typealias GroupClosure = (QueryBuilder<Model>) throws -> ()

    /// Create a query group.
    @discardableResult
    public func group(
        _ relation: QueryGroupRelation,
        closure: @escaping GroupClosure
    ) rethrows -> Self {
        let sub = copy()
        try closure(sub)
        let filter = QueryFilter(
            entity: Model.entity,
            method: .group(relation, sub.query.filters)
        )
        return addFilter(filter)
    }
}


//
//  Optional+Extension.swift
//  MyLibrary
//
//  Created by Rodrigo Ruiz on 8/1/17.
//  Copyright © 2017 Rodrigo Ruiz. All rights reserved.
//

public func map<T1, T2>(_ transform: @escaping (T1) -> T2) -> (T1?) -> T2? {
    return { s1 in
        return s1.map(transform)
    }
}

extension Optional {

    public func apply<U>(_ f: ((Wrapped) -> U)?) -> U? {
        switch f {
        case .some(let someF):
            return map(someF)
        case .none:
            return .none
        }
    }

}

Add missing functions to Optional extension.

//
//  Optional+Extension.swift
//  MyLibrary
//
//  Created by Rodrigo Ruiz on 8/1/17.
//  Copyright © 2017 Rodrigo Ruiz. All rights reserved.
//

public func map<T1, T2>(_ transform: @escaping (T1) -> T2) -> (T1?) -> T2? {
    return { $0.map(transform) }
}

extension Optional {

    public func apply<U>(_ transform: ((Wrapped) -> U)?) -> U? {
        switch transform {
        case .some(let someTransform):
            return map(someTransform)
        case .none:
            return .none
        }
    }

}

public func apply<T, U>(_ transform: ((T) -> U)?) -> (T?) -> U? {
    return { $0.apply(transform) }
}


//
//  CloudKitArticleStatusUpdate.swift
//  Account
//
//  Created by Maurice Parker on 4/29/20.
//  Copyright © 2020 Ranchero Software, LLC. All rights reserved.
//

import Foundation
import SyncDatabase
import Articles

struct CloudKitArticleStatusUpdate {

	enum Record {
		case all
		case statusOnly
		case delete
	}

	var articleID: String
	var statuses: [SyncStatus]
	var article: Article?

	var record: Record {
		if statuses.contains(where: { $0.key == .deleted }) {
			return .delete
		}

		if let article = article {
			if statuses.contains(where: { $0.key == .new }) {
				return .all
			}
			if article.status.read == false || article.status.starred == true {
				return .all
			}
		}

		return .statusOnly
	}

	var isRead: Bool {
		if let article = article {
			return article.status.read
		}

		if let status = statuses.first(where: { $0.key == .read }) {
			return status.flag
		}

		return true
	}

	var isStarred: Bool {
		if let article = article {
			return article.status.starred
		}

		if let status = statuses.first(where: { $0.key == .starred }) {
			return status.flag
		}

		return false
	}

}

Change how statuses are processed

//
//  CloudKitArticleStatusUpdate.swift
//  Account
//
//  Created by Maurice Parker on 4/29/20.
//  Copyright © 2020 Ranchero Software, LLC. All rights reserved.
//

import Foundation
import SyncDatabase
import Articles

struct CloudKitArticleStatusUpdate {

	enum Record {
		case all
		case statusOnly
		case delete
	}

	var articleID: String
	var statuses: [SyncStatus]
	var article: Article?

	var record: Record {
		if statuses.contains(where: { $0.key == .deleted }) {
			return .delete
		}

		if let article = article {
			if article.status.read == false || article.status.starred == true {
				return .all
			}
		}

		return .statusOnly
	}

	var isRead: Bool {
		if let article = article {
			return article.status.read
		}
		return true
	}

	var isStarred: Bool {
		if let article = article {
			return article.status.starred
		}
		return false
	}

}


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

import XCTest
@testable import BreweryDB

class RequestBuilderTests: 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 testRequestBuilderInitsWithRequestEndPoint() {
        let requestBuilder = RequestBuilder(endPoint: .Beer)
        XCTAssertNotNil(requestBuilder)
    }

}

Add test for NSURL extension

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

import XCTest
@testable import BreweryDB

class RequestBuilderTests: 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 testRequestBuilderInitsWithRequestEndPoint() {
        let requestBuilder = RequestBuilder(endPoint: .Beer)
        XCTAssertNotNil(requestBuilder)
    }

    func testRequestBuilderNSURLExtensionReturnsURLWithRawValue() {
        let baseURL = NSURL(string: "app.mywebservice.com")
        let url = baseURL?.URLByAppendingPathComponent(.Beer)

        XCTAssertEqual(url, NSURL(string: "app.mywebservice.com/beer"))
    }

}


//
//  StreamRepostHeaderCell.swift
//  Ello
//
//  Created by Ryan Boyajian on 4/23/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import Foundation

public class StreamRepostHeaderCell: UICollectionViewCell, ElloTextViewDelegate {

    @IBOutlet weak var viaTextViewHeight: NSLayoutConstraint!
    @IBOutlet weak var viaTextView: ElloTextView!
    @IBOutlet weak var sourceTextView: ElloTextView!
    weak var userDelegate: UserDelegate?

    override public func awakeFromNib() {
        super.awakeFromNib()
        viaTextView.textViewDelegate = self
        sourceTextView.textViewDelegate = self
    }

    func textViewTapped(link: String, object: ElloAttributedObject) {
        switch object {
        case let .AttributedUserId(userId):
            userDelegate?.userTappedParam(userId)
        default: break
        }
    }

}

Truncate "via" & "source" when usernames are to long in discover.

//
//  StreamRepostHeaderCell.swift
//  Ello
//
//  Created by Ryan Boyajian on 4/23/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import Foundation

public class StreamRepostHeaderCell: UICollectionViewCell, ElloTextViewDelegate {

    @IBOutlet weak var viaTextViewHeight: NSLayoutConstraint!
    @IBOutlet weak var viaTextView: ElloTextView!
    @IBOutlet weak var sourceTextView: ElloTextView!
    weak var userDelegate: UserDelegate?

    override public func awakeFromNib() {
        super.awakeFromNib()
        viaTextView.textViewDelegate = self
        configureTextView(viaTextView)
        sourceTextView.textViewDelegate = self
        configureTextView(sourceTextView)
    }

    func configureTextView(textview: UITextView) {
        textview.scrollEnabled = false
        textview.textContainer.maximumNumberOfLines = 0
        textview.textContainer.lineBreakMode = NSLineBreakMode.ByTruncatingTail
    }

    func textViewTapped(link: String, object: ElloAttributedObject) {
        switch object {
        case let .AttributedUserId(userId):
            userDelegate?.userTappedParam(userId)
        default: break
        }
    }

}


//  Copyright (c) 2015 Ben Guo. All rights reserved.

import Foundation

extension Chord {
    /// Creates a new `Harmonizer` using the (1-indexed) indices of the given harmonizer
    public static func create(_ harmonizer: Harmonizer, indices: [UInt]) -> Harmonizer {
        if indices.count < 2 || indices.contains(0) {
            return Harmony.IdentityHarmonizer
        }

        // sort and convert to zero-indexed indices
        let sortedIndices = (indices.map { $0 - 1 }).sorted()
        let maxIndex = Int(sortedIndices.last!)
        let scalePitches = harmonizer(Chroma.c*0)

        // extend scale until it covers the max index
        while (scalePitches.count < maxIndex + 1) {
            _ = scalePitches.extend(1)
        }

        let chosenPitches = PitchSet(sortedIndices.map { scalePitches[Int($0)] })
        return Harmony.create(MKUtil.intervals(chosenPitches.semitoneIndices()))
    }
}

Use Collection return value in ChordExtension

//  Copyright (c) 2015 Ben Guo. All rights reserved.

import Foundation

extension Chord {
    /// Creates a new `Harmonizer` using the (1-indexed) indices of the given harmonizer
    public static func create(_ harmonizer: Harmonizer, indices: [UInt]) -> Harmonizer {
        if indices.count < 2 || indices.contains(0) {
            return Harmony.IdentityHarmonizer
        }

        // sort and convert to zero-indexed indices
        let sortedIndices = (indices.map { $0 - 1 }).sorted()
        let maxIndex = Int(sortedIndices.last!)
        var scalePitches = harmonizer(Chroma.c*0)

        // extend scale until it covers the max index
        while (scalePitches.count < maxIndex + 1) {
            scalePitches = scalePitches.extend(1)
        }

        let chosenPitches = PitchSet(sortedIndices.map { scalePitches[Int($0)] })
        return Harmony.create(MKUtil.intervals(chosenPitches.semitoneIndices()))
    }
}


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

final class DatatypeTests: XCTestCase {
	func testDatatypeWithZeroConstructorsIsUnitType() {
		assert(Datatype(constructors: []).value("A"), ==, .UnitType)
	}

	func testDatatypeWithOneConstructorIsTypeOfConstructedValue() {
		assert(Datatype(constructors: [ ("a", .Argument(.BooleanType, const(.End))) ]).value("A"), ==, .lambda(.BooleanType, const(.Product(.BooleanType, .UnitType))))
	}
}

import Assertions
@testable import Manifold
import Prelude
import XCTest

Correct the test of the constructed value.

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

final class DatatypeTests: XCTestCase {
	func testDatatypeWithZeroConstructorsIsUnitType() {
		assert(Datatype(constructors: []).value("A"), ==, .UnitType)
	}

	func testDatatypeWithOneConstructorIsTypeOfConstructedValue() {
		assert(Datatype(constructors: [ ("a", .Argument(.BooleanType, const(.End))) ]).value("A"), ==, .Product(.BooleanType, .UnitType))
	}
}

import Assertions
@testable import Manifold
import Prelude
import XCTest


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

final class LocationTests: XCTestCase {
	func testTraversingAnExpressionReturnsALocationAtTheTraversedExpression() {
		assert(identity.explore().it, ==, identity)
	}

	func testTopLevelNodesHaveNoParents() {
		assert(Expression<Term>.Unit.explore().up?.it, ==, nil)
	}

	func testTopLevelNodesHaveNoSiblings() {
		assert(Expression<Term>.Unit.explore().left?.it, ==, nil)
		assert(Expression<Term>.Unit.explore().right?.it, ==, nil)
	}

	func testNullaryNodesHaveNoChildren() {
		assert(Expression<Term>.Unit.explore().down?.it, ==, nil)
	}

	func testDeepNavigationExploresChildrenOfChildrenRecursively() {
		assert(identity.explore().down?.right?.down?.right?.it, ==, .Variable(.Local(0)))
	}
}

import Assertions
@testable import Manifold
import XCTest

Test that deep navigation can return out of an Expression.

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

final class LocationTests: XCTestCase {
	func testTraversingAnExpressionReturnsALocationAtTheTraversedExpression() {
		assert(identity.explore().it, ==, identity)
	}

	func testTopLevelNodesHaveNoParents() {
		assert(Expression<Term>.Unit.explore().up?.it, ==, nil)
	}

	func testTopLevelNodesHaveNoSiblings() {
		assert(Expression<Term>.Unit.explore().left?.it, ==, nil)
		assert(Expression<Term>.Unit.explore().right?.it, ==, nil)
	}

	func testNullaryNodesHaveNoChildren() {
		assert(Expression<Term>.Unit.explore().down?.it, ==, nil)
	}

	func testDeepNavigationExploresChildrenOfChildrenRecursively() {
		assert(identity.explore().down?.right?.down?.right?.it, ==, .Variable(.Local(0)))
	}

	func testDeepNavigationReturnsUpwards() {
		assert(identity.explore().down?.right?.down?.right?.up?.up?.it, ==, identity)
	}
}

import Assertions
@testable import Manifold
import XCTest


import Foundation;

println("Hello, World!")

enum CompassPoint {
    case North;
    case South;
    case East;
    case West;
};

protocol SomeProtocol {
    var fullName: String { get };
    func demo();
    func dummy(f: Int);
    func foo(bar: String, baz: Double);
};

// Class examples

class lowerCamelCase {
    var x: String = "hello";
    let b = 2;

    func demo()
    {
        for var x = 0; ; {
            print(x);
        };

        if temperatureInFahrenheit <= 32 {
            println("It's very cold. Consider wearing a scarf.");
        } else if temperatureInFahrenheit >= 86 {
            println("It's really warm. Don't forget to wear sunscreen.");
        } else {
            println("It's not that cold. Wear a t-shirt.");
        }
    };
};

Add additional functional tests for ';' terminated

import Foundation;

println("Hello, World!")

enum CompassPoint {
    case North;
    case South;
    case East;
    case West;
};

protocol SomeProtocol {
    var fullName: String { get };
    func demo();
    func dummy(f: Int);
    func foo(bar: String, baz: Double);
};

extension SomeType {
    // new functionality to add to SomeType goes here
};

struct DemoStruct {
    var x: String;

    func test() {
        // while loop test
        while (true)
        {
        };

        // for loop
        for ; ; {

        };

        // do while
        do {

        } while (true);
    };
};

// Class examples

class lowerCamelCase {
    var x: String = "hello";
    let b = 2;

    func demo()
    {
        for var x = 0; ; {
            print(x);
        };

        if temperatureInFahrenheit <= 32 {
            println("It's very cold. Consider wearing a scarf.");
        } else if temperatureInFahrenheit >= 86 {
            println("It's really warm. Don't forget to wear sunscreen.");
        } else {
            println("It's not that cold. Wear a t-shirt.");
        }
    };
};


//
//  CellIdentifiable.swift
//  ZamzamKit
//
//  Created by Basem Emara on 4/28/17.
//  Copyright © 2017 Zamzam. All rights reserved.
//

import UIKit

public protocol CellIdentifiable {
    associatedtype CellIdentifier: RawRepresentable
}

public extension CellIdentifiable where Self: UITableViewController, CellIdentifier.RawValue == String {

    /**
     Gets the visible cell with the specified identifier name.

     - parameter identifier: Enum value of the cell identifier.

     - returns: Returns the table view cell.
     */
    func tableViewCell(at identifier: CellIdentifier) -> UITableViewCell? {
        return tableView.visibleCells.first { $0.reuseIdentifier == identifier.rawValue }
    }
}

Extend CellIdentifier to extract from table view cell

//
//  CellIdentifiable.swift
//  ZamzamKit
//
//  Created by Basem Emara on 4/28/17.
//  Copyright © 2017 Zamzam. All rights reserved.
//

import UIKit

public protocol CellIdentifiable {
    associatedtype CellIdentifier: RawRepresentable
}

public extension CellIdentifiable where Self: UITableViewController, CellIdentifier.RawValue == String {

    /**
     Gets the visible cell with the specified identifier name.

     - parameter identifier: Enum value of the cell identifier.

     - returns: Returns the table view cell.
     */
    func tableViewCell(at identifier: CellIdentifier) -> UITableViewCell? {
        return tableView.visibleCells.first { $0.reuseIdentifier == identifier.rawValue }
    }
}

public extension RawRepresentable where Self.RawValue == String {

    init?(from cell: UITableViewCell) {
        guard let identifier = cell.reuseIdentifier else { return nil }
        self.init(rawValue: identifier)
    }
}


//
//  ViewController.swift
//  SwiftExample
//
//  Created by Frank Schmitt on 4/13/15.
//  Copyright (c) 2015 Apptentive. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var messageCenterButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "messageCenterUnreadCountChanged", name:ATMessageCenterUnreadCountChangedNotification, object: nil)
    }

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    func messageCenterUnreadCountChanged(notification: NSNotification) {
        if let notificationCount = notification.userInfo?["count"] as? Int {
            self.messageCenterButton.setTitle("Message Center (\(notificationCount))", forState: .Normal)
        }
    }

    @IBAction func engageEvent1(sender: AnyObject) {
        ATConnect.sharedConnection().engage("Event_1", fromViewController: self)
    }

    @IBAction func showMessageCenter(sender: AnyObject) {
        ATConnect.sharedConnection().presentMessageCenterFromViewController(self)
    }
}

Add missing colon to selector

//
//  ViewController.swift
//  SwiftExample
//
//  Created by Frank Schmitt on 4/13/15.
//  Copyright (c) 2015 Apptentive. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var messageCenterButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "messageCenterUnreadCountChanged:", name:ATMessageCenterUnreadCountChangedNotification, object: nil)
    }

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    func messageCenterUnreadCountChanged(notification: NSNotification) {
        if let notificationCount = notification.userInfo?["count"] as? Int {
            self.messageCenterButton.setTitle("Message Center (\(notificationCount))", forState: .Normal)
        }
    }

    @IBAction func engageEvent1(sender: AnyObject) {
        ATConnect.sharedConnection().engage("Event_1", fromViewController: self)
    }

    @IBAction func showMessageCenter(sender: AnyObject) {
        ATConnect.sharedConnection().presentMessageCenterFromViewController(self)
    }
}


//
//  MessagesSizingViewModel.swift
//  Rocket.Chat
//
//  Created by Rafael Streit on 25/09/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

import Foundation

final class MessagesSizingManager {

    internal var cache: [AnyHashable: NSValue] = [:]
    internal var nibsCache: [AnyHashable: Any] = [:]

    /**
     Clear all height values cached.
     */
    func clearCache() {
        cache = [:]
    }

    func invalidateLayout(for identifier: AnyHashable) {
        cache.removeValue(forKey: identifier)
    }

    /**
     Returns the cached size for the IndexPath.
     */
    func size(for identifier: AnyHashable) -> CGSize? {
        return cache[identifier]?.cgSizeValue
    }

    /**
     Sets the cached size for the identified cell.
     */
    func set(size: CGSize, for identifier: AnyHashable) {
        return cache[identifier] = NSValue(cgSize: size)
    }

    /**
     Returns the cached view for identifier.
     */
    func view(for identifier: AnyHashable) -> Any? {
        return nibsCache[identifier]
    }

    /**
     Sets the cached view to specific identifier.
     */
    func set(view: Any, for identifier: AnyHashable) {
        return nibsCache[identifier] = view
    }

}

Clear nibs cache on whole cache clearing

//
//  MessagesSizingViewModel.swift
//  Rocket.Chat
//
//  Created by Rafael Streit on 25/09/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

import Foundation

final class MessagesSizingManager {

    internal var cache: [AnyHashable: NSValue] = [:]
    internal var nibsCache: [AnyHashable: Any] = [:]

    /**
     Clear all height values cached.
     */
    func clearCache() {
        cache = [:]
        nibsCache = [:]
    }

    func invalidateLayout(for identifier: AnyHashable) {
        cache.removeValue(forKey: identifier)
    }

    /**
     Returns the cached size for the IndexPath.
     */
    func size(for identifier: AnyHashable) -> CGSize? {
        return cache[identifier]?.cgSizeValue
    }

    /**
     Sets the cached size for the identified cell.
     */
    func set(size: CGSize, for identifier: AnyHashable) {
        return cache[identifier] = NSValue(cgSize: size)
    }

    /**
     Returns the cached view for identifier.
     */
    func view(for identifier: AnyHashable) -> Any? {
        return nibsCache[identifier]
    }

    /**
     Sets the cached view to specific identifier.
     */
    func set(view: Any, for identifier: AnyHashable) {
        return nibsCache[identifier] = view
    }

}


/**
 * Tae Won Ha - http://taewon.de - @hataewon
 * See LICENSE
 */

import Foundation
import Swifter
import RxSwift

fileprivate let defaults = UserDefaults.standard

class PrefService: Service {

  typealias Element = StateActionPair<AppState, UuidAction<MainWindow.Action>>

  static let compatibleVersion = "200" // yet dummy
  static let lastCompatibleVersion = "128"

  func apply(_ pair: Element) {
    guard case .close = pair.action.payload else {
      return
    }

    NSLog("Saving pref!")
    defaults.setValue(pair.state.dict(), forKey: PrefService.compatibleVersion)
  }
}

Set the correct pref version

/**
 * Tae Won Ha - http://taewon.de - @hataewon
 * See LICENSE
 */

import Foundation
import Swifter
import RxSwift

fileprivate let defaults = UserDefaults.standard

class PrefService: Service {

  typealias Element = StateActionPair<AppState, UuidAction<MainWindow.Action>>

  static let compatibleVersion = "168" // yet dummy
  static let lastCompatibleVersion = "128"

  func apply(_ pair: Element) {
    guard case .close = pair.action.payload else {
      return
    }

    NSLog("Saving pref!")
    defaults.setValue(pair.state.dict(), forKey: PrefService.compatibleVersion)
  }
}


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

// RUN: not --crash %target-swift-frontend %s -emit-ir
protocol A.init(UInt=_=1 + 1){{let c{extension{lazy var f={

Mark a crasher as nondeterministic

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

// RUN: not --crash %target-swift-frontend %s -emit-ir
// REQUIRES: deterministic-behavior
protocol A.init(UInt=_=1 + 1){{let c{extension{lazy var f={


import Foundation

protocol Semigroup {
  func op (g: Self) -> Self
}

func op <S: Semigroup> (s: S, t: S) -> S {
  return s.op(t)
}

infix operator ++ {associativity left}
func ++ <S: Semigroup> (s: S, t: S) -> S {
  return op(s, t)
}

prefix operator ++ {}
prefix func ++ <S: Semigroup> (t: S) -> S -> S {
  return {s in op(s, t)}
}

postfix operator ++ {}
postfix func ++ <S: Semigroup> (s: S) -> S -> S {
  return {t in op(s, t)}
}

func sconcat <S: Semigroup> (ss: [S]) -> S? {
  if countElements(ss) == 0 {
    return nil
  }
  return ss[1..<ss.count].reduce(ss[0], {$0.op($1)})
}

Rename the global semigroup op to sop.

import Foundation

protocol Semigroup {
  func op (g: Self) -> Self
}

func sop <S: Semigroup> (s: S, t: S) -> S {
  return s.op(t)
}

infix operator ++ {associativity left}
func ++ <S: Semigroup> (s: S, t: S) -> S {
  return sop(s, t)
}

prefix operator ++ {}
prefix func ++ <S: Semigroup> (t: S) -> S -> S {
  return {s in sop(s, t)}
}

postfix operator ++ {}
postfix func ++ <S: Semigroup> (s: S) -> S -> S {
  return {t in sop(s, t)}
}

func sconcat <S: Semigroup> (ss: [S]) -> S? {
  if countElements(ss) == 0 {
    return nil
  }
  return ss[1..<ss.count].reduce(ss[0], {$0.op($1)})
}


import UIKit

class ChooseInstagramViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet var instagramUsernameField: UITextField!
    @IBOutlet var instagramLabel:         UILabel!
    @IBOutlet var instagramLogoImageView: UIImageView!
    var pusher: PusherType = Pusher()

    override func viewDidLoad() {
        instagramLabel.font         = Config.standardHeaderFont
        instagramLabel.text         = Config.chooseInstagramText
        instagramUsernameField.font = Config.standardBodyFont
        view.backgroundColor        = Config.instagramBackgroundColor
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        pushNextViewController()
        return true
    }

    private func pushNextViewController() {
        if let navigationController = navigationController {
            let nextViewController = UIStoryboard.loadViewController(storyboardName: "ChooseSuspect", identifier: "chooseYoutubeViewController") as! ChooseYoutubeViewController
            nextViewController.chosenInstagramUsername = instagramUsernameField.text
            pusher.pushViewController(navigationController: navigationController, viewControllerToPush: nextViewController, animated: true)
        }
    }
}

Use instagram logo from Config

import UIKit

class ChooseInstagramViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet var instagramUsernameField: UITextField!
    @IBOutlet var instagramLabel:         UILabel!
    @IBOutlet var instagramLogoImageView: UIImageView!
    var pusher: PusherType = Pusher()

    override func viewDidLoad() {
        instagramLogoImageView.image = Config.instagramLogoImage
        instagramLabel.font          = Config.standardHeaderFont
        instagramLabel.text          = Config.chooseInstagramText
        instagramUsernameField.font  = Config.standardBodyFont
        view.backgroundColor         = Config.instagramBackgroundColor
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        pushNextViewController()
        return true
    }

    private func pushNextViewController() {
        if let navigationController = navigationController {
            let nextViewController = UIStoryboard.loadViewController(storyboardName: "ChooseSuspect", identifier: "chooseYoutubeViewController") as! ChooseYoutubeViewController
            nextViewController.chosenInstagramUsername = instagramUsernameField.text
            pusher.pushViewController(navigationController: navigationController, viewControllerToPush: nextViewController, animated: true)
        }
    }
}


import UIKit

class CenterCellCollectionViewFlowLayout: UICollectionViewFlowLayout {

  override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {

    if let collectionView = self.collectionView {

      let collectionViewBounds = collectionView.bounds
      let halfWidth = collectionViewBounds.size.width / 2;
      let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidth;

      if let attributesForVisibleCells = self.layoutAttributesForElementsInRect(collectionViewBounds) as? [UICollectionViewLayoutAttributes] {

        var candidateAttributes : UICollectionViewLayoutAttributes?

        for attributes in attributesForVisibleCells {
          // Skip comparison with non-cell items (headers and footers)
          if attributes.representedElementCategory != UICollectionElementCategory.Cell {
            continue
          }

          if let candAttrs = candidateAttributes {
            let a = attributes.center.x - proposedContentOffsetCenterX
            let b = candAttrs.center.x - proposedContentOffsetCenterX

            if velocity.x < 0 {
              continue
            } else if velocity.x > 0 {
              candidateAttributes = attributes
            } else if fabsf(Float(a)) < fabsf(Float(b)) {
              candidateAttributes = attributes
            }

          } else { // First time in the loop
            candidateAttributes = attributes;
            continue;
          }
        }
        return CGPoint(x : candidateAttributes!.center.x - halfWidth, y : proposedContentOffset.y);
      }
    }

    return super.targetContentOffsetForProposedContentOffset(proposedContentOffset)
  }
}

Add filter for the loop

import UIKit

class CenterCellCollectionViewFlowLayout: UICollectionViewFlowLayout {

  override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {

    if let collectionView = self.collectionView {

      let collectionViewBounds = collectionView.bounds
      let halfWidth = collectionViewBounds.size.width / 2
      let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidth;

      if let attributesForVisibleCells = self.layoutAttributesForElementsInRect(collectionViewBounds) as? [UICollectionViewLayoutAttributes] {

        var candidateAttributes : UICollectionViewLayoutAttributes?

        for attributes in attributesForVisibleCells.filter({
          $0.representedElementCategory != UICollectionElementCategory.Cell}) {

          if let candAttrs = candidateAttributes {
            let a = attributes.center.x - proposedContentOffsetCenterX
            let b = candAttrs.center.x - proposedContentOffsetCenterX

            if velocity.x < 0 {
              continue
            } else if velocity.x > 0 {
              candidateAttributes = attributes
            } else if fabsf(Float(a)) < fabsf(Float(b)) {
              candidateAttributes = attributes
            }

          } else { // First time in the loop
            candidateAttributes = attributes;
            continue;
          }
        }
        return CGPoint(x : candidateAttributes!.center.x - halfWidth, y : proposedContentOffset.y);
      }
    }

    return super.targetContentOffsetForProposedContentOffset(proposedContentOffset)
  }
}


//
//  FilesTests.swift
//  ResourceApp
//
//  Created by Mathijs Kadijk on 25-09-15.
//  Copyright © 2015 Mathijs Kadijk. All rights reserved.
//

import UIKit
import XCTest
@testable import ResourceApp

class FilesTests: XCTestCase {

  func testNoNilResourceFiles() {
    XCTAssertNotNil(R.file.someJson() as NSURL?)
    XCTAssertNotNil(R.file.someJson() as String?)
  }
}

Fix test that used the removed String FileResource

//
//  FilesTests.swift
//  ResourceApp
//
//  Created by Mathijs Kadijk on 25-09-15.
//  Copyright © 2015 Mathijs Kadijk. All rights reserved.
//

import UIKit
import XCTest
@testable import ResourceApp

class FilesTests: XCTestCase {

  func testNoNilResourceFiles() {
    XCTAssertNotNil(R.file.someJson())
  }
}


//
//  TextInputFormat+TransformValue.swift
//  TextInputKit
//
//  Created by Artem Starosvetskiy on 27/11/2016.
//  Copyright © 2016 Artem Starosvetskiy. All rights reserved.
//

import Foundation

public extension TextInputFormat {

    public typealias DirectValueTransform<Result> = (Value) throws -> Result
    public typealias ReverseValueTransform<Result> = (Result) -> Value

    func transformValue<Result>(
        direct directTransform: @escaping DirectValueTransform<Result>,
        reverse reverseTransform: @escaping ReverseValueTransform<Result>) -> TextInputFormat<Result> {

        return TextInputFormat.from(
            self.serializer.map(direct: directTransform, reverse: reverseTransform),
            self.formatter)
    }

}

Add a convenient method for transforming a value of a `TextInputFormat`.

//
//  TextInputFormat+TransformValue.swift
//  TextInputKit
//
//  Created by Artem Starosvetskiy on 27/11/2016.
//  Copyright © 2016 Artem Starosvetskiy. All rights reserved.
//

import Foundation

public extension TextInputFormat {

    public typealias DirectValueTransform<Result> = (Value) throws -> Result
    public typealias ReverseValueTransform<Result> = (Result) -> Value

    /// Creates a `TextInputFormat` which transforms the values produced by the source serializer
    /// (the serializer of the callee format).
    ///
    /// - Parameters:
    ///   - directTransform: The transformation from a source value to a resulting value.
    ///   - reverseTransform: The transformation from a resulting value to a source value.
    /// - Returns: The created `TextInputFormatter`.
    func transformValue<Result>(
        direct directTransform: @escaping DirectValueTransform<Result>,
        reverse reverseTransform: @escaping ReverseValueTransform<Result>) -> TextInputFormat<Result> {

        return TextInputFormat.from(
            self.serializer.map(direct: directTransform, reverse: reverseTransform),
            self.formatter)
    }

}

public extension TextInputFormat {

    public typealias NonThrowingDirectValueTransform<Result> = (Value) -> Result?

    /// Creates a `TextInputFormat` which transforms the values produced by the source serializer
    /// (the serializer of the callee format).
    ///
    /// - Parameters:
    ///   - directTransform: The transformation from a source value to a resulting value.
    ///   - reverseTransform: The transformation from a resulting value to a source value.
    /// - Returns: The created `TextInputFormatter`.
    func transformValue<Result>(
        direct nonThrowingDirectTransform: @escaping NonThrowingDirectValueTransform<Result>,
        reverse reverseTransform: @escaping ReverseValueTransform<Result>) -> TextInputFormat<Result> {

        let directTransform: DirectValueTransform<Result> = { value in
            guard let result = nonThrowingDirectTransform(value) else {
                throw TextInputKitError.unknown
            }
            return result
        }

        return TextInputFormat.from(
            self.serializer.map(direct: directTransform, reverse: reverseTransform),
            self.formatter)
    }

}


//
//  UIViewController+AllowCellularDataDownloadsAlert.swift
//  Podverse
//
//  Created by Mitchell Downey on 2/19/18.
//  Copyright © 2018 Podverse LLC. All rights reserved.
//

import UIKit

extension UIViewController {
    func showAllowCellularDataAlert(completion: ((Bool) -> ())? = nil) {
        if !UserDefaults.standard.bool(forKey: kAskedToAllowCellularDataDownloads) {

            UserDefaults.standard.set(true, forKey: kAskedToAllowCellularDataDownloads)

            let allowCellularDataAlert = UIAlertController(title: "Enable Cellular Data?", message: "Do you want to allow downloading episodes using cellular data when not connected to Wi-Fi?", preferredStyle: UIAlertControllerStyle.alert)

            allowCellularDataAlert.addAction(UIAlertAction(title: "Yes", style: .default) { (_) -> Void in
                UserDefaults.standard.set(true, forKey: kAllowCellularDataDownloads)
                completion?(true)
            })

            allowCellularDataAlert.addAction(UIAlertAction(title: "No", style: .cancel) { (_) -> Void in
                UserDefaults.standard.set(false, forKey: kAllowCellularDataDownloads)
                completion?(false)
            })

            DispatchQueue.main.async {
                self.present(allowCellularDataAlert, animated: true, completion: nil)
            }
        }
    }
}

Stop limiting the showAllowCellularDataAlert to one time

//
//  UIViewController+AllowCellularDataDownloadsAlert.swift
//  Podverse
//
//  Created by Mitchell Downey on 2/19/18.
//  Copyright © 2018 Podverse LLC. All rights reserved.
//

import UIKit

extension UIViewController {
    func showAllowCellularDataAlert(completion: ((Bool) -> ())? = nil) {
        UserDefaults.standard.set(true, forKey: kAskedToAllowCellularDataDownloads)

        let allowCellularDataAlert = UIAlertController(title: "Enable Cellular Data?", message: "Do you want to allow downloading episodes using cellular data when not connected to Wi-Fi?", preferredStyle: UIAlertControllerStyle.alert)

        allowCellularDataAlert.addAction(UIAlertAction(title: "Yes", style: .default) { (_) -> Void in
            UserDefaults.standard.set(true, forKey: kAllowCellularDataDownloads)
            completion?(true)
        })

        allowCellularDataAlert.addAction(UIAlertAction(title: "No", style: .cancel) { (_) -> Void in
            UserDefaults.standard.set(false, forKey: kAllowCellularDataDownloads)
            completion?(false)
        })

        DispatchQueue.main.async {
            self.present(allowCellularDataAlert, animated: true, completion: nil)
        }
    }
}


/**
 * Question Link: https://leetcode.com/problems/combination-sum-iv/
 * Primary idea: DFS cannot solve without time limited error, so use DP
 *
 * Note: Integer overflow
 * Space Complexity: O(n)
 *
 */

class CombinationSumIV {
    func combinationSum4(_ nums: [Int], _ target: Int) -> Int {
        var dp = [Int](repeating: 0, count: target + 1)
        dp[0] = 1

        for i in 1 ... target {
            for num in nums.sorted() {
                if i < num {
                    break
                }

                if dp[i - num] > Int.max - dp[i] {
                    continue
                }
                dp[i] += dp[i - num]
            }
        }

        return dp.last!
    }
}

Optimize code for Combination Sum IV

/**
 * Question Link: https://leetcode.com/problems/combination-sum-iv/
 * Primary idea: DFS cannot solve without time limited error, so use DP
 *
 * Note: Integer overflow
 * Space Complexity: O(n)
 *
 */

class CombinationSumIV {
    func combinationSum4(_ nums: [Int], _ target: Int) -> Int {
        var dp = [Int](repeating: 0, count: target + 1)
        dp[0] = 1
        let nums = nums.sorted()

        for i in 1 ... target {
            for num in nums {
                if i < num {
                    break
                }

                if dp[i - num] > Int.max - dp[i] {
                    continue
                }
                dp[i] += dp[i - num]
            }
        }

        return dp.last!
    }
}


/**
 * Question Link: https://leetcode.com/problems/decode-ways/
 * Primary idea: Dynamic Programming, dp[i] = dp[i - 1] + dp[i - 2],
 *               determine if current one or two characters are number at first
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 */

class DecodeWays {
    func numDecodings(_ s: String) -> Int {
        let sChars = Array(s.characters), len = sChars.count
        var dp = Array(repeating: 0, count: len + 1)
        dp[0] = 1

        guard len >= 1 else {
            return 0
        }

        for i in 1...len {
            if isValid(String(sChars[i - 1..<i])) {
                dp[i] += dp[i - 1]
            }
            if i >= 2 && isValid(String(sChars[i - 2..<i])) {
                dp[i] += dp[i - 2]
            }
        }

        return dp[len]
    }

    private func isValid(_ numStr: String) -> Bool {
        if Array(numStr.characters).first == "0" {
            return false
        }

        guard let num = Int(numStr) else {
            return false
        }

        return num >= 1 && num <= 26
    }
}

Update solution to Decode Ways

/**
 * Question Link: https://leetcode.com/problems/decode-ways/
 * Primary idea: Dynamic Programming, dp[i] = dp[i - 1] + dp[i - 2],
 *               determine if current one or two characters are number at first
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 */

class DecodeWays {
    func numDecodings(_ s: String) -> Int {
        let sChars = Array(s)
        var dp = Array(repeating: 0, count: s.count + 1)
        dp[0] = 1

        guard s.count >= 1 else {
            return 0
        }

        for i in 1...s.count {
            if String(sChars[i - 1..<i]).isValid {
                dp[i] += dp[i - 1]
            }
            if i >= 2 && String(sChars[i - 2..<i]).isValid {
                dp[i] += dp[i - 2]
            }
        }

        return dp[s.count]
    }
}

extension String {
    var isValid: Bool {
        if let first = first, first == "0" {
            return false
        }

        guard let num = Int(self) else {
            return false
        }

        return 0 < num && 26 >= num
    }
}


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

// rdar://problem/19792730

public func foo<
    Expected : SequenceType,
    Actual : SequenceType,
    T : Comparable
    where
      Expected.Generator.Element == Actual.Generator.Element,
      Expected.Generator.Element == T
>(expected: Expected, actual: Actual) {}

public func foo<
    Expected : SequenceType,
    Actual : SequenceType,
    T : Comparable
    where
      Expected.Generator.Element == Actual.Generator.Element,
      Expected.Generator.Element == (T, T)
>(expected: Expected, actual: Actual) {}

Disable a crash test in no-asserts builds

// RUN: not --crash %target-swift-frontend %s -emit-silgen
// REQUIRES: asserts

// rdar://problem/19792730

public func foo<
    Expected : SequenceType,
    Actual : SequenceType,
    T : Comparable
    where
      Expected.Generator.Element == Actual.Generator.Element,
      Expected.Generator.Element == T
>(expected: Expected, actual: Actual) {}

public func foo<
    Expected : SequenceType,
    Actual : SequenceType,
    T : Comparable
    where
      Expected.Generator.Element == Actual.Generator.Element,
      Expected.Generator.Element == (T, T)
>(expected: Expected, actual: Actual) {}


//
//  Runtime.swift
//  OpenSim
//
//  Created by Luo Sheng on 11/12/15.
//  Copyright © 2015 Luo Sheng. All rights reserved.
//

import Foundation

final class Runtime: CustomStringConvertible {

    let name: String
    var devices: [Device] = []

    var description: String {
        // current version is format "iOS major.minir"
        // old versions of iOS are com.Apple.CoreSimulator.SimRuntime.iOS-major-minor

        let characterSet = CharacterSet(charactersIn: " -.")
        let components = name.components(separatedBy: characterSet)

        guard components.count > 2 else {
            return name
        }

        let lastTwoComponents = components[components.count - 2 ..< components.count]
        return lastTwoComponents.joined(separator: ".")
    }

    init(name: String) {
        self.name = name
    }

}

Add OS name to runtime description

//
//  Runtime.swift
//  OpenSim
//
//  Created by Luo Sheng on 11/12/15.
//  Copyright © 2015 Luo Sheng. All rights reserved.
//

import Foundation

final class Runtime: CustomStringConvertible {

    let name: String
    var devices: [Device] = []

    var description: String {
        // current version is format "iOS major.minir"
        // old versions of iOS are com.Apple.CoreSimulator.SimRuntime.iOS-major-minor

        let characterSet = CharacterSet(charactersIn: " -.")
        let components = name.components(separatedBy: characterSet)

        guard components.count > 2 else {
            return name
        }

        return "\(components[components.count - 3]) \(components[components.count - 2]).\(components[components.count - 1])"
    }

    init(name: String) {
        self.name = name
    }

}


//
//  SVWebViewProtocol.swift
//  KomicaViewer
//
//  Created by Craig Zheng on 21/08/2016.
//  Copyright © 2016 Craig. All rights reserved.
//

import UIKit

import SVWebViewController

protocol SVWebViewProtocol: class {
    var svWebViewGuardDog: WebViewGuardDog? { get set }
    var svWebViewURL: URL? { get set }

    func presentSVWebView()
}

extension SVWebViewProtocol where Self: UIViewController {

    func presentSVWebView() {
        if let svWebViewURL = svWebViewURL
        {
            if let navigationController = self.navigationController,
                let webViewController = SVWebViewController(url: svWebViewURL) {
                webViewController.delegate = svWebViewGuardDog
                navigationController.pushViewController(webViewController, animated: true)
            } else if let webViewController = SVModalWebViewController(url: svWebViewURL) {
                webViewController.navigationBar.tintColor = navigationController?.navigationBar.tintColor
                webViewController.barsTintColor = navigationController?.navigationBar.barTintColor
                webViewController.webViewDelegate = svWebViewGuardDog
                webViewController.popoverPresentationController?.sourceView = self.view
                webViewController.popoverPresentationController?.sourceRect = self.view.bounds
                present(webViewController, animated: true, completion: nil)
            }
        }
    }

}

Use modal presentation for SVWebViewController.

//
//  SVWebViewProtocol.swift
//  KomicaViewer
//
//  Created by Craig Zheng on 21/08/2016.
//  Copyright © 2016 Craig. All rights reserved.
//

import UIKit

import SVWebViewController

protocol SVWebViewProtocol: class {
    var svWebViewGuardDog: WebViewGuardDog? { get set }
    var svWebViewURL: URL? { get set }

    func presentSVWebView()
}

extension SVWebViewProtocol where Self: UIViewController {

    func presentSVWebView() {
        if let svWebViewURL = svWebViewURL,
            let webViewController = SVModalWebViewController(url: svWebViewURL) {
            webViewController.navigationBar.tintColor = navigationController?.navigationBar.tintColor
            webViewController.barsTintColor = navigationController?.navigationBar.barTintColor
            webViewController.webViewDelegate = svWebViewGuardDog
            webViewController.popoverPresentationController?.sourceView = self.view
            webViewController.popoverPresentationController?.sourceRect = self.view.bounds
            present(webViewController, animated: true, completion: nil)
        }
    }

}


import XCTest

@testable import OSCCoreTests

XCTMain([
    testCase(OSCMessageTests.allTests),
    testCase(ValueConversionTests.allTests),
    testCase(AddressMatcherTests.allTests),
    testCase(DispatcherTests.allTests),
    testCase(OSCBundleTests.allTests)
])

Extend linux test head with leftover cases

import XCTest

@testable import OSCCoreTests

XCTMain([
    testCase(OSCMessageTests.allTests),
    testCase(ValueConversionTests.allTests),
    testCase(AddressMatcherTests.allTests),
    testCase(DispatcherTests.allTests),
    testCase(OSCBundleTests.allTests),
    testCase(OSCTimeTagTests.allTests)
])


//
//  FASTAReaderTests.swift
//  BioSwift
//
//  Created by Maciej Trybilo on 01/03/2016.
//  Copyright © 2016 Maciej Trybilo. All rights reserved.
//

import XCTest

class FASTAReaderTests: XCTestCase {

    func test_readFromFile() {

        let sequences = FASTAReader.readFromFile(NSBundle.mainBundle().resourcePath! + "/example.fa")

        XCTAssertEqual(sequences.count, 3)
    }

}

Disable the FASTAReader test for now.

//
//  FASTAReaderTests.swift
//  BioSwift
//
//  Created by Maciej Trybilo on 01/03/2016.
//  Copyright © 2016 Maciej Trybilo. All rights reserved.
//

import XCTest

class FASTAReaderTests: XCTestCase {

    func test_readFromFile() {

        let sequences = FASTAReader.readFromFile(NSBundle.mainBundle().resourcePath! + "/example.fa")

        //XCTAssertEqual(sequences.count, 3)
    }

}


import Vapor
import VaporMySQL

let drop = Droplet(preparations: [Sighting.self], providers: [VaporMySQL.Provider.self])

drop.post("sightings") { request in
    guard let bird = request.data["bird"]?.string else {
        throw Abort.badRequest
    }

    let response = try drop.client.get("http://ebird.org/ws1.1/ref/taxon/find", query: [
        "q" : bird ])

    guard let _ = response.data[0, "name"]?.string else {
        throw Abort.custom(
             status: .badRequest,
             message: "Bird \(bird) was not found")
    }

    var sighting = Sighting(bird: bird)
    try sighting.save()

    return sighting
}

drop.get("sightings", Sighting.self) { request, sighting in
    return sighting
}

drop.get("sightings", String.self, "count") { request, bird in
    let sightings = try Sighting.query().filter("bird", bird).all()

    return JSON([
            "count": Node(sightings.count)
        ])
}

drop.run()

Fix bird checking json conversion

import Vapor
import VaporMySQL
import Foundation

let drop = Droplet(preparations: [Sighting.self], providers: [VaporMySQL.Provider.self])

drop.post("sightings") { request in
    guard let bird = request.data["bird"]?.string else {
        throw Abort.badRequest
    }

    let response = try drop.client.get("http://ebird.org/ws1.1/ref/taxon/find", query: [
        "q" : bird ])

    let birds = response.data["name"]?
            .array?
            .flatMap({ $0.string })

    if birds == nil || birds?.count == 0 {
            throw Abort.custom(
                status: .badRequest,
                message: "Bird \(bird) was not found")
    }

    var sighting = Sighting(bird: bird)
    try sighting.save()

    return sighting
}

drop.get("sightings", Sighting.self) { request, sighting in
    return sighting
}

drop.get("sightings", String.self, "count") { request, bird in
    let sightings = try Sighting.query().filter("bird", bird).all()

    return JSON([
            "count": Node(sightings.count)
        ])
}

drop.run()


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

// %t.input: "A ---> B" ==> "A"
// RUN: sed -ne '/--->/s/ *--->.*$//p' < %S/Inputs/decl-reconstr-names.txt > %t.input

// %t.check: "A ---> B" ==> "B"
// RUN: sed -ne '/--->/s/^.*---> *//p' < %S/Inputs/decl-reconstr-names.txt > %t.check

// RUN: %target-build-swift -emit-executable %s -g -o %t/DeclReconstr -emit-module
// RUN: %lldb-moduleimport-test %t/DeclReconstr -target-triple %target-triple \
// RUN:   -decl-from-mangled=%t.input > %t.output 2>&1
// RUN: diff %t.check %t.output

// FIXME: rdar://38822524
// REQUIRES: OS=macosx

// REQUIRES: executable_test
struct S {
  init() {
  }
}

func patatino() -> Int {
  let s = S()
  return 0
}

patatino()

Remove REQUIRES from test now that the issue is fixed.

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

// %t.input: "A ---> B" ==> "A"
// RUN: sed -ne '/--->/s/ *--->.*$//p' < %S/Inputs/decl-reconstr-names.txt > %t.input

// %t.check: "A ---> B" ==> "B"
// RUN: sed -ne '/--->/s/^.*---> *//p' < %S/Inputs/decl-reconstr-names.txt > %t.check

// RUN: %target-build-swift -emit-executable %s -g -o %t/DeclReconstr -emit-module
// RUN: %lldb-moduleimport-test %t/DeclReconstr -target-triple %target-triple \
// RUN:   -decl-from-mangled=%t.input > %t.output 2>&1
// RUN: diff %t.check %t.output

// REQUIRES: executable_test
struct S {
  init() {
  }
}

func patatino() -> Int {
  let s = S()
  return 0
}

patatino()


//
//  StoryCollectionViewCell.swift
//  TechEmpathy
//
//  Created by Sarah Olson on 4/15/17.
//  Copyright © 2017 SarahEOlson. All rights reserved.
//

import UIKit
import AVFoundation

class StoryCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var storyImageView: UIImageView!
    @IBOutlet weak var listenButton: UIButton!
    @IBOutlet weak var lampButton: UIButton!

    var story: Story? {
        didSet {
            guard let story = story else {
                return
            }
            self.backgroundColor = UIColor(hexString: story.color)
            if story.audio == nil || story.audio == "" || story.audio == "No audio" {
                listenButton.tintColor = UIColor.gray
                listenButton.isEnabled = false
            } else {
                listenButton.tintColor = UIColor.white
                listenButton.isEnabled = true
            }
            if let image = story.image,
                image != "" {
                storyImageView.pin_setImage(from: URL(string: image)!)
            } else {
                storyImageView.image = nil
            }
            self.lampButton.isHidden = !story.isLampLit
        }
    }
}

Add a placeholder image to story cells.

//
//  StoryCollectionViewCell.swift
//  TechEmpathy
//
//  Created by Sarah Olson on 4/15/17.
//  Copyright © 2017 SarahEOlson. All rights reserved.
//

import UIKit
import AVFoundation

class StoryCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var storyImageView: UIImageView!
    @IBOutlet weak var listenButton: UIButton!
    @IBOutlet weak var lampButton: UIButton!

    var story: Story? {
        didSet {
            guard let story = story else {
                return
            }
            self.backgroundColor = UIColor(hexString: story.color)
            if story.audio == nil || story.audio == "" || story.audio == "No audio" {
                listenButton.tintColor = UIColor.gray
                listenButton.isEnabled = false
            } else {
                listenButton.tintColor = UIColor.white
                listenButton.isEnabled = true
            }
            storyImageView.pin_setPlaceholder(with: #imageLiteral(resourceName: "placeholder"))
            if let image = story.image,
                image != "" {
                storyImageView.pin_setImage(from: URL(string: image)!)
            } else {
                storyImageView.image = nil
            }
            self.lampButton.isHidden = !story.isLampLit
        }
    }
}


// RUN: not %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
extension String->[Void{#^A^#

Remove 'not' because code completion prints result.

// RUN: %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
extension String->[Void{#^A^#


//
//  SurveyTableViewDelegate.swift
//  Pods
//
//  Created by Nora Mullaney on 3/15/17.
//
//

import Foundation

open class SurveyTableViewDelegate : NSObject, UITableViewDelegate {

   var surveyQuestions : SurveyQuestions

   public init(_ surveyQuestions : SurveyQuestions) {
      self.surveyQuestions = surveyQuestions
   }

   open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      TableUIUpdater.updateTable(self.surveyQuestions.selectedRowAt(indexPath), tableView: tableView)
      tableView.deselectRow(at: indexPath, animated: false)
   }

}

Fix jerkiness of scrolling by giving better estimates for height

//
//  SurveyTableViewDelegate.swift
//  Pods
//
//  Created by Nora Mullaney on 3/15/17.
//
//

import Foundation

open class SurveyTableViewDelegate : NSObject, UITableViewDelegate {

   var surveyQuestions : SurveyQuestions
   var heightAtIndexPath = NSMutableDictionary()

   public init(_ surveyQuestions : SurveyQuestions) {
      self.surveyQuestions = surveyQuestions
   }

   open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      TableUIUpdater.updateTable(self.surveyQuestions.selectedRowAt(indexPath), tableView: tableView)
      tableView.deselectRow(at: indexPath, animated: false)
   }

   open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
      if let height = heightAtIndexPath.object(forKey: indexPath) as? NSNumber {
         return CGFloat(height.floatValue)
      } else {
         return UITableViewAutomaticDimension
      }
   }

   open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
      let height = cell.frame.size.height
      self.heightAtIndexPath.setObject(height, forKey: indexPath as NSCopying)
   }
}