hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
1e57552ab21dfd5a67020d4085994ffbcf1dc15d | 1,077 | //
// RecurrenceFrequency.swift
// RRuleSwift
//
// Created by Xin Hong on 16/3/28.
// Copyright © 2016年 Teambition. All rights reserved.
//
public enum RecurrenceFrequency {
case yearly
case monthly
case weekly
case daily
case hourly
case minutely
case secondly
internal func toString() -> String {
switch self {
case .secondly: return "SECONDLY"
case .minutely: return "MINUTELY"
case .hourly: return "HOURLY"
case .daily: return "DAILY"
case .weekly: return "WEEKLY"
case .monthly: return "MONTHLY"
case .yearly: return "YEARLY"
}
}
internal static func frequency(from string: String) -> RecurrenceFrequency? {
switch string {
case "SECONDLY": return .secondly
case "MINUTELY": return .minutely
case "HOURLY": return .hourly
case "DAILY": return .daily
case "WEEKLY": return .weekly
case "MONTHLY": return .monthly
case "YEARLY": return .yearly
default: return nil
}
}
}
| 25.046512 | 81 | 0.604457 |
1ee2441f5c436a06be989975820906748d34b16d | 2,904 | import UIKit
@objc(FloatGeneratorNodeData) public class FloatGeneratorNodeData: NodeData, UITextFieldDelegate
{
var value : Dynamic<Float> = Dynamic<Float>(0)
override class var defaultTitle: String { return "Float Generator (float a)" }
override class var customViewHeight: CGFloat { return 100 }
override class var defaultCanHavePreview: Bool { return false }
override class var defaultPreviewOutportIndex: Int { return -1 }
override class var defaultInPorts: Array<NodePortData>
{
return []
}
override class var defaultOutPorts: Array<NodePortData>
{
return [
FloatNodePortData(title: "A")
]
}
// single node shader block, need to override
override func singleNodeExpressionRule() -> String
{
let result : String =
"""
\(shaderCommentHeader())
\(declareInPortsExpression())
\(outPorts[0].requiredType.defaultCGType) \(outPorts[0].getPortVariableName()) = \(value.value);
"""
return result
}
// preview shader expression gl_FragColor only, need to override
override func shaderFinalColorExperssion() -> String
{
return String(format: "gl_FragColor = vec4(\(outPorts[0].getPortVariableName()),\(outPorts[0].getPortVariableName()),\(outPorts[0].getPortVariableName()),1.0);")
}
override func setupCustomView(view: UIView)
{
let inputField : UITextField = UITextField(frame: view.bounds.inset(by: UIEdgeInsets.init(top: 8, left: 8, bottom: 8, right: 8)))
view.addSubview(inputField)
inputField.backgroundColor = UIColor.clear
inputField.font = UIFont.init(name: Constant.fontBoldName, size: 80)
inputField.adjustsFontSizeToFitWidth = true
inputField.minimumFontSize = 28
inputField.placeholder = "Value"
inputField.text = "\(value.value)"
inputField.keyboardType = .decimalPad
inputField.delegate = self
value.bind { (newValue) in
NotificationCenter.default.post(name: NSNotification.Name( Constant.notificationNameShaderModified), object: nil)
}
}
// MARK - UITextFieldDelegate
public func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
if let text = textField.text, let nextValue = Float(text)
{
value.value = nextValue
textField.text = "\(nextValue)"
}
return true
}
public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool
{
if let text = textField.text, let nextValue = Float(text)
{
value.value = nextValue
textField.text = "\(nextValue)"
}
return true
}
override class func nodeType() -> NodeType
{
return NodeType.Generator
}
}
| 33.767442 | 169 | 0.63843 |
2fde80d244879dcf97513855d972ff573a5ff1ad | 1,539 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import AWSSDKSwiftCore
//MARK: Paginators
extension MediaStoreData {
/// Provides a list of metadata entries about folders and objects in the specified folder.
public func listItemsPaginator(
_ input: ListItemsRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (ListItemsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listItems, tokenKey: \ListItemsResponse.nextToken, on: eventLoop, onPage: onPage)
}
}
extension MediaStoreData.ListItemsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> MediaStoreData.ListItemsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
path: self.path
)
}
}
| 32.744681 | 158 | 0.637427 |
e86d391386dab65e5bb6f17ca5a707046cb522f1 | 344 | //
// FollowRequests.swift
// IGHelper
//
// Created by Andrei Dobysh on 10/23/19.
// Copyright © 2019 Andrei Dobysh. All rights reserved.
//
import Foundation
struct FollowRequests: Codable {
let value: String
public func contain(username: String) -> Bool {
return value.contains("\"text\":\"\(username)\"")
}
}
| 19.111111 | 57 | 0.642442 |
64c8ccf19a47a10ea58f1f1a1aab9e7ad6c8b6dd | 1,692 | //
// NNItemCollectionViewController.swift
// NNMintFurniture
//
// Created by 柳钟宁 on 2017/8/15.
// Copyright © 2017年 zhongNing. All rights reserved.
//
import UIKit
let NNItemCollectionViewControllerID = "NNItemCollectionViewControllerID"
class NNItemCollectionViewController: NNBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "UICollectionView瀑布流"
// 布局
let layout = NNItemCollectionViewFlowLayout()
// 创建collectionView
let collectionView = UICollectionView.init(frame: view.bounds, collectionViewLayout: layout)
view.addSubview(collectionView)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.white
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: NNItemCollectionViewControllerID)
}
}
// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension NNItemCollectionViewController : UICollectionViewDataSource, UICollectionViewDelegate {
// MARK: 多少组
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
// MARK: 每一组有多少个cell
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 30
}
// MARK: Cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NNItemCollectionViewControllerID, for: indexPath)
cell.backgroundColor = UIColor.blue
return cell
}
}
| 33.84 | 124 | 0.73227 |
7a72b682129b13c9bcf36df0f33b65fc99e89150 | 4,570 | //
// Xcore
// Copyright © 2015 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
extension Picker {
/// A convenience method to display a picker with list of options
/// that conforms to `OptionsRepresentable` protocol.
///
/// **Example:**
///
/// ```swift
/// enum CompassPoint: Int, CaseIterable, OptionsRepresentable {
/// case north, south, east, west
/// }
///
/// Picker.present(selected: CompassPoint.allCases.first) { (option: CompassPoint) -> Void in
/// print("selected option:" option)
/// }
/// ```
@discardableResult
public static func present<T: OptionsRepresentable>(
selected option: T? = nil,
configure: ((Picker) -> Void)? = nil,
_ handler: @escaping (_ option: T) -> Void
) -> Picker {
let model = BasicPickerModel(selected: option) { option in
handler(option)
}
let picker = Picker(model: model)
configure?(picker)
picker.present()
return picker
}
/// A convenience method to display a picker with list of options.
///
/// **Example:**
///
/// ```swift
/// let options = ["Year", "Month", "Day"]
/// Picker.present(options: options, selected: options.first) { option in
/// print("selected option:" option)
/// }
/// ```
@discardableResult
public static func present(
options: [String],
selected option: String? = nil,
_ handler: @escaping (_ option: String) -> Void
) -> Picker {
let model = BasicTextPickerModel(options: options, selected: option) { option in
handler(option)
}
let picker = Picker(model: model)
picker.present()
return picker
}
}
// MARK: - BasicPickerModel
private final class BasicPickerModel<T: OptionsRepresentable>: PickerModel {
private var options: [T] = T.allCases
private var selectedOption: T
private var selectionCallback: (T) -> Void
init(selected option: T? = nil, handler: @escaping (T) -> Void) {
let allCases = T.allCases
if let option = option, let index = allCases.firstIndex(of: option) {
selectedOption = allCases[index]
} else {
selectedOption = T.allCases.first!
}
selectionCallback = handler
}
private func setSelectedOption(_ option: T? = nil) {
let allCases = T.allCases
guard !allCases.isEmpty else {
return
}
if let option = option, let index = allCases.firstIndex(of: option) {
selectedOption = allCases[index]
} else {
selectedOption = T.allCases.first!
}
}
func selectedElement(at component: Int) -> Int {
options.firstIndex(of: selectedOption) ?? 0
}
func numberOfElements(at component: Int) -> Int {
options.count
}
func element(at component: Int, row: Int) -> Picker.RowModel {
let option = options[row]
return .init(image: option.image, title: option.description)
}
func pickerDidTapDone() {
selectionCallback(selectedOption)
}
func pickerDidSelectValue(value: Int, at component: Int) {
selectedOption = options[value]
}
func pickerDidDismiss() {
}
func pickerReloadAllComponents() {
options = T.allCases
setSelectedOption(selectedOption)
}
}
// MARK: - BasicTextPickerModel
private final class BasicTextPickerModel: PickerModel {
private let options: [String]
private var selectedOption: String
private var selectionCallback: (String) -> Void
init(options: [String], selected option: String? = nil, handler: @escaping (String) -> Void) {
self.options = options
if let option = option, let index = options.firstIndex(of: option) {
selectedOption = options[index]
} else {
selectedOption = options.first!
}
selectionCallback = handler
}
func selectedElement(at component: Int) -> Int {
options.firstIndex(of: selectedOption) ?? 0
}
func numberOfElements(at component: Int) -> Int {
options.count
}
func element(at component: Int, row: Int) -> Picker.RowModel {
.init(title: options[row])
}
func pickerDidTapDone() {
selectionCallback(selectedOption)
}
func pickerDidSelectValue(value: Int, at component: Int) {
selectedOption = options[value]
}
func pickerDidDismiss() {
}
}
| 26.725146 | 98 | 0.6 |
6a0478773ef45036933a4e78b3caee18ddadf733 | 59,733 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import struct Utility.Version
import class Foundation.NSDate
public enum DependencyResolverError: Error, Equatable, CustomStringConvertible {
/// The resolver was unable to find a solution to the input constraints.
case unsatisfiable
/// The resolver encountered a versioned container which has a revision dependency.
case incompatibleConstraints(
dependency: (AnyPackageContainerIdentifier, String),
revisions: [(AnyPackageContainerIdentifier, String)])
public static func == (lhs: DependencyResolverError, rhs: DependencyResolverError) -> Bool {
switch (lhs, rhs) {
case (.unsatisfiable, .unsatisfiable):
return true
case (.unsatisfiable, _):
return false
case (.incompatibleConstraints(let lDependency, let lRevisions),
.incompatibleConstraints(let rDependency, let rRevisions)):
return lDependency == rDependency && lRevisions == rRevisions
case (.incompatibleConstraints, _):
return false
}
}
public var description: String {
switch self {
case .unsatisfiable:
return "unable to resolve dependencies"
case let .incompatibleConstraints(dependency, revisions):
let stream = BufferedOutputByteStream()
stream <<< "the package \(dependency.0.identifier) @ \(dependency.1) contains incompatible dependencies:\n"
for (i, revision) in revisions.enumerated() {
stream <<< " "
stream <<< "\(revision.0.identifier)" <<< " @ " <<< revision.1
if i != revisions.count - 1 {
stream <<< "\n"
}
}
return stream.bytes.asString!
}
}
}
/// An abstract definition for a set of versions.
public enum VersionSetSpecifier: Hashable, CustomStringConvertible {
/// The universal set.
case any
/// The empty set.
case empty
/// A non-empty range of version.
case range(Range<Version>)
/// The exact version that is required.
case exact(Version)
/// Compute the intersection of two set specifiers.
public func intersection(_ rhs: VersionSetSpecifier) -> VersionSetSpecifier {
switch (self, rhs) {
case (.any, _):
return rhs
case (_, .any):
return self
case (.empty, _):
return .empty
case (_, .empty):
return .empty
case (.range(let lhs), .range(let rhs)):
let start = Swift.max(lhs.lowerBound, rhs.lowerBound)
let end = Swift.min(lhs.upperBound, rhs.upperBound)
if start < end {
return .range(start..<end)
} else {
return .empty
}
case (.exact(let v), _):
if rhs.contains(v) {
return self
}
return .empty
case (_, .exact(let v)):
if contains(v) {
return rhs
}
return .empty
}
}
//FIXME: Remove in 4.2
public var hashValue: Int {
switch (self) {
case .any:
return 0xB58D
case .empty:
return 0x7121
case .range(let range):
return 0x4CF3 ^ (range.lowerBound.hashValue &* 31) ^ range.upperBound.hashValue
case .exact(let version):
return 0xD04F ^ version.hashValue
}
}
/// Check if the set contains a version.
public func contains(_ version: Version) -> Bool {
switch self {
case .empty:
return false
case .range(let range):
return range.contains(version: version)
case .any:
return true
case .exact(let v):
return v == version
}
}
public var description: String {
switch self {
case .any:
return "any"
case .empty:
return "empty"
case .range(let range):
var upperBound = range.upperBound
// Patch the version range representation. This shouldn't be
// required once we have custom version range structure.
if upperBound.minor == .max && upperBound.patch == .max {
upperBound = Version(upperBound.major + 1, 0, 0)
}
if upperBound.minor != .max && upperBound.patch == .max {
upperBound = Version(upperBound.major, upperBound.minor + 1, 0)
}
return range.lowerBound.description + "..<" + upperBound.description
case .exact(let version):
return version.description
}
}
public static func == (_ lhs: VersionSetSpecifier, _ rhs: VersionSetSpecifier) -> Bool {
switch (lhs, rhs) {
case (.any, .any):
return true
case (.any, _):
return false
case (.empty, .empty):
return true
case (.empty, _):
return false
case (.range(let lhs), .range(let rhs)):
return lhs == rhs
case (.range, _):
return false
case (.exact(let lhs), .exact(let rhs)):
return lhs == rhs
case (.exact, _):
return false
}
}
}
/// An identifier which unambiguously references a package container.
///
/// This identifier is used to abstractly refer to another container when
/// encoding dependencies across packages.
public protocol PackageContainerIdentifier: Hashable { }
/// A type-erased package container identifier.
public struct AnyPackageContainerIdentifier: PackageContainerIdentifier {
/// The underlying identifier, represented as AnyHashable.
public let identifier: AnyHashable
/// Creates a type-erased identifier that wraps up the given instance.
init<T: PackageContainerIdentifier>(_ identifier: T) {
self.identifier = AnyHashable(identifier)
}
}
/// A container of packages.
///
/// This is the top-level unit of package resolution, i.e. the unit at which
/// versions are associated.
///
/// It represents a package container (e.g., a source repository) which can be
/// identified unambiguously and which contains a set of available package
/// versions and the ability to retrieve the dependency constraints for each of
/// those versions.
///
/// We use the "container" terminology here to differentiate between two
/// conceptual notions of what the package is: (1) informally, the repository
/// containing the package, but from which a package cannot be loaded by itself
/// and (2) the repository at a particular version, at which point the package
/// can be loaded and dependencies enumerated.
///
/// This is also designed in such a way to extend naturally to multiple packages
/// being contained within a single repository, should we choose to support that
/// later.
public protocol PackageContainer {
/// The type of packages contained.
associatedtype Identifier: PackageContainerIdentifier
/// The identifier for the package.
var identifier: Identifier { get }
/// Get the list of versions which are available for the package.
///
/// The list will be returned in sorted order, with the latest version *first*.
/// All versions will not be requested at once. Resolver will request the next one only
/// if the previous one did not satisfy all constraints.
func versions(filter isIncluded: (Version) -> Bool) -> AnySequence<Version>
// FIXME: We should perhaps define some particularly useful error codes
// here, so the resolver can handle errors more meaningfully.
//
/// Fetch the declared dependencies for a particular version.
///
/// This property is expected to be efficient to access, and cached by the
/// client if necessary.
///
/// - Precondition: `versions.contains(version)`
/// - Throws: If the version could not be resolved; this will abort
/// dependency resolution completely.
func getDependencies(at version: Version) throws -> [PackageContainerConstraint<Identifier>]
/// Fetch the declared dependencies for a particular revision.
///
/// This property is expected to be efficient to access, and cached by the
/// client if necessary.
///
/// - Throws: If the revision could not be resolved; this will abort
/// dependency resolution completely.
func getDependencies(at revision: String) throws -> [PackageContainerConstraint<Identifier>]
/// Fetch the dependencies of an unversioned package container.
///
/// NOTE: This method should not be called on a versioned container.
func getUnversionedDependencies() throws -> [PackageContainerConstraint<Identifier>]
/// Get the updated identifier at a bound version.
///
/// This can be used by the containers to fill in the missing information that is obtained
/// after the container is available. The updated identifier is returned in result of the
/// dependency resolution.
func getUpdatedIdentifier(at boundVersion: BoundVersion) throws -> Identifier
}
/// An interface for resolving package containers.
public protocol PackageContainerProvider {
associatedtype Container: PackageContainer
/// Get the container for a particular identifier asynchronously.
func getContainer(
for identifier: Container.Identifier,
skipUpdate: Bool,
completion: @escaping (Result<Container, AnyError>) -> Void
)
}
/// An individual constraint onto a container.
public struct PackageContainerConstraint<T: PackageContainerIdentifier>: CustomStringConvertible, Equatable {
public typealias Identifier = T
/// The requirement of this constraint.
public enum Requirement: Hashable {
/// The requirement is specified by the version set.
case versionSet(VersionSetSpecifier)
/// The requirement is specified by the revision.
///
/// The revision string (identifier) should be valid and present in the
/// container. Only one revision requirement per container is possible
/// i.e. two revision requirements for same container will lead to
/// unsatisfiable resolution. The revision requirement can either come
/// from initial set of constraints or from dependencies of a revision
/// requirement.
case revision(String)
/// Un-versioned requirement i.e. a version should not resolved.
case unversioned
}
/// The identifier for the container the constraint is on.
public let identifier: Identifier
/// The constraint requirement.
public let requirement: Requirement
/// Create a constraint requiring the given `container` satisfying the
/// `requirement`.
public init(container identifier: Identifier, requirement: Requirement) {
self.identifier = identifier
self.requirement = requirement
}
/// Create a constraint requiring the given `container` satisfying the
/// `versionRequirement`.
public init(container identifier: Identifier, versionRequirement: VersionSetSpecifier) {
self.init(container: identifier, requirement: .versionSet(versionRequirement))
}
public var description: String {
return "Constraint(\(identifier), \(requirement))"
}
public static func == (lhs: PackageContainerConstraint, rhs: PackageContainerConstraint) -> Bool {
return lhs.identifier == rhs.identifier && lhs.requirement == rhs.requirement
}
}
/// Delegate interface for dependency resoler status.
public protocol DependencyResolverDelegate {
associatedtype Identifier: PackageContainerIdentifier
}
// FIXME: This should be nested, but cannot be currently.
//
/// A bound version for a package within an assignment.
public enum BoundVersion: Equatable, CustomStringConvertible {
/// The assignment should not include the package.
///
/// This is different from the absence of an assignment for a particular
/// package, which only indicates the assignment is agnostic to its
/// version. This value signifies the package *may not* be present.
case excluded
/// The version of the package to include.
case version(Version)
/// The package assignment is unversioned.
case unversioned
/// The package assignment is this revision.
case revision(String)
public var description: String {
switch self {
case .excluded:
return "excluded"
case .version(let version):
return version.description
case .unversioned:
return "unversioned"
case .revision(let identifier):
return identifier
}
}
}
// FIXME: Maybe each package should just return this, instead of a list of
// `PackageContainerConstraint`s. That won't work if we decide this should
// eventually map based on the `Container` rather than the `Identifier`, though,
// so they are separate for now.
//
/// A container for constraints for a set of packages.
///
/// This data structure is only designed to represent satisfiable constraint
/// sets, it cannot represent sets including containers which have an empty
/// constraint.
public struct PackageContainerConstraintSet<C: PackageContainer>: Collection, Hashable {
public typealias Container = C
public typealias Identifier = Container.Identifier
public typealias Requirement = PackageContainerConstraint<Identifier>.Requirement
public typealias Index = Dictionary<Identifier, Requirement>.Index
public typealias Element = Dictionary<Identifier, Requirement>.Element
/// The set of constraints.
private var constraints: [Identifier: Requirement]
/// Create an empty constraint set.
public init() {
self.constraints = [:]
}
/// Create an constraint set from known values.
///
/// The initial constraints should never be unsatisfiable.
init(_ constraints: [Identifier: Requirement]) {
assert(constraints.values.filter({ $0 == .versionSet(.empty) }).isEmpty)
self.constraints = constraints
}
/// The list of containers with entries in the set.
var containerIdentifiers: AnySequence<Identifier> {
return AnySequence<C.Identifier>(constraints.keys)
}
/// Get the version set specifier associated with the given package `identifier`.
public subscript(identifier: Identifier) -> Requirement {
return constraints[identifier] ?? .versionSet(.any)
}
//FIXME: Remove in 4.2? Perhaps?
public var hashValue: Int {
var result = 0
for c in self.constraints {
result ^= c.key.hashValue &* 0x62F ^ c.value.hashValue
}
return result
}
/// Create a constraint set by merging the `requirement` for container `identifier`.
///
/// - Returns: The new set, or nil the resulting set is unsatisfiable.
private func merging(
requirement: Requirement, for identifier: Identifier
) -> PackageContainerConstraintSet<C>? {
switch (requirement, self[identifier]) {
case (.versionSet(let newSet), .versionSet(let currentSet)):
// Try to intersect two version set requirements.
let intersection = currentSet.intersection(newSet)
if intersection == .empty {
return nil
}
var result = self
result.constraints[identifier] = .versionSet(intersection)
return result
case (.unversioned, .unversioned):
return self
case (.unversioned, _):
// Unversioned requirements always *wins*.
var result = self
result.constraints[identifier] = requirement
return result
case (_, .unversioned):
// Unversioned requirements always *wins*.
return self
// The revision cases are deliberately placed below the unversioned
// cases because unversioned has more priority.
case (.revision(let lhs), .revision(let rhs)):
// We can merge two revisions if they have the same identifier.
if lhs == rhs { return self }
return nil
// We can merge the revision requiement if it currently does not have a requirement.
case (.revision, .versionSet(.any)):
var result = self
result.constraints[identifier] = requirement
return result
// Otherwise, we can't merge the revision requirement.
case (.revision, _):
return nil
// Exisiting revision requirements always *wins*.
case (_, .revision):
return self
}
}
/// Create a constraint set by merging `constraint`.
///
/// - Returns: The new set, or nil the resulting set is unsatisfiable.
public func merging(_ constraint: PackageContainerConstraint<Identifier>) -> PackageContainerConstraintSet<C>? {
return merging(requirement: constraint.requirement, for: constraint.identifier)
}
/// Create a new constraint set by merging the given constraint set.
///
/// - Returns: False if the merger has made the set unsatisfiable; i.e. true
/// when the resulting set is satisfiable, if it was already so.
func merging(
_ constraints: PackageContainerConstraintSet<Container>
) -> PackageContainerConstraintSet<C>? {
var result = self
for (key, requirement) in constraints {
guard let merged = result.merging(requirement: requirement, for: key) else {
return nil
}
result = merged
}
return result
}
// MARK: Collection Conformance
public var startIndex: Index {
return constraints.startIndex
}
public var endIndex: Index {
return constraints.endIndex
}
public func index(after index: Index) -> Index {
return constraints.index(after: index)
}
public subscript(position: Index) -> Element {
return constraints[position]
}
}
// FIXME: Actually make efficient.
//
/// A container for version assignments for a set of packages, exposed as a
/// sequence of `Container` to `BoundVersion` bindings.
///
/// This is intended to be an efficient data structure for accumulating a set of
/// version assignments along with efficient access to the derived information
/// about the assignment (for example, the unified set of constraints it
/// induces).
///
/// The set itself is designed to only ever contain a consistent set of
/// assignments, i.e. each assignment should satisfy the induced
/// `constraints`, but this invariant is not explicitly enforced.
struct VersionAssignmentSet<C: PackageContainer>: Equatable, Sequence {
typealias Container = C
typealias Identifier = Container.Identifier
// FIXME: Does it really make sense to key on the identifier here. Should we
// require referential equality of containers and use that to simplify?
//
/// The assignment records.
fileprivate var assignments: OrderedDictionary<Identifier, (container: Container, binding: BoundVersion)>
/// Create an empty assignment.
init() {
assignments = [:]
}
/// The assignment for the given container `identifier.
subscript(identifier: Identifier) -> BoundVersion? {
get {
return assignments[identifier]?.binding
}
}
/// The assignment for the given `container`.
subscript(container: Container) -> BoundVersion? {
get {
return self[container.identifier]
}
set {
// We disallow deletion.
let newBinding = newValue!
// Validate this is a valid assignment.
assert(isValid(binding: newBinding, for: container))
assignments[container.identifier] = (container: container, binding: newBinding)
}
}
/// Create a new assignment set by merging in the bindings from `assignment`.
///
/// - Returns: The new assignment, or nil if the merge cannot be made (the
/// assignments contain incompatible versions).
func merging(_ assignment: VersionAssignmentSet<Container>) -> VersionAssignmentSet<Container>? {
// In order to protect the assignment set, we first have to test whether
// the merged constraint sets are satisfiable.
//
// FIXME: This is very inefficient; we should decide whether it is right
// to handle it here or force the main resolver loop to handle the
// discovery of this property.
guard constraints.merging(assignment.constraints) != nil else {
return nil
}
// The induced constraints are satisfiable, so we *can* union the
// assignments without breaking our internal invariant on
// satisfiability.
var result = self
for (container, binding) in assignment {
if let existing = result[container] {
if existing != binding {
return nil
}
} else {
result[container] = binding
}
}
return result
}
// FIXME: We need to cache this.
//
/// The combined version constraints induced by the assignment.
///
/// This consists of the merged constraints which need to be satisfied on
/// each package as a result of the versions selected in the assignment.
///
/// The resulting constraint set is guaranteed to be non-empty for each
/// mapping, assuming the invariants on the set are followed.
var constraints: PackageContainerConstraintSet<Container> {
// Collect all of the constraints.
var result = PackageContainerConstraintSet<Container>()
/// Merge the provided constraints into result.
func merge(constraints: [PackageContainerConstraint<Identifier>]) {
for constraint in constraints {
guard let merged = result.merging(constraint) else {
preconditionFailure("unsatisfiable constraint set")
}
result = merged
}
}
for (_, (container: container, binding: binding)) in assignments {
switch binding {
case .unversioned, .excluded:
// If the package is unversioned or excluded, it doesn't contribute.
continue
case .revision(let identifier):
// FIXME: Need caching and error handling here. See the FIXME below.
merge(constraints: try! container.getDependencies(at: identifier))
case .version(let version):
// If we have a version, add the constraints from that package version.
//
// FIXME: We should cache this too, possibly at a layer
// different than above (like the entry record).
//
// FIXME: Error handling, except that we probably shouldn't have
// needed to refetch the dependencies at this point.
merge(constraints: try! container.getDependencies(at: version))
}
}
return result
}
// FIXME: This is currently very inefficient.
//
/// Check if the given `binding` for `container` is valid within the assignment.
func isValid(binding: BoundVersion, for container: Container) -> Bool {
switch binding {
case .excluded:
// A package can be excluded if there are no constraints on the
// package (it has not been requested by any other package in the
// assignment).
return constraints[container.identifier] == .versionSet(.any)
case .version(let version):
// A version is valid if it is contained in the constraints.
if case .versionSet(let versionSet) = constraints[container.identifier] {
return versionSet.contains(version)
}
return false
case .revision(let identifier):
// If we already have a revision constraint, it should be same as
// the one we're trying to set.
if case .revision(let existingRevision) = constraints[container.identifier] {
return existingRevision == identifier
}
// Otherwise, it is always valid to set a revision binding. Note
// that there are rules that prevents versioned constraints from
// having revision constraints, but that is handled by the resolver.
return true
case .unversioned:
// An unversioned binding is always valid.
return true
}
}
/// Check if the assignment is valid and complete.
func checkIfValidAndComplete() -> Bool {
// Validity should hold trivially, because it is an invariant of the collection.
for (_, assignment) in assignments {
if !isValid(binding: assignment.binding, for: assignment.container) {
return false
}
}
// Check completeness, by simply looking at all the entries in the induced constraints.
for identifier in constraints.containerIdentifiers {
// Verify we have a non-excluded entry for this key.
switch assignments[identifier]?.binding {
case .unversioned?, .version?, .revision?:
continue
case .excluded?, nil:
return false
}
}
return true
}
// MARK: Sequence Conformance
// FIXME: This should really be a collection, but that takes significantly
// more work given our current backing collection.
typealias Iterator = AnyIterator<(Container, BoundVersion)>
func makeIterator() -> Iterator {
var it = assignments.makeIterator()
return AnyIterator {
if let (_, next) = it.next() {
return (next.container, next.binding)
} else {
return nil
}
}
}
}
func == <C>(lhs: VersionAssignmentSet<C>, rhs: VersionAssignmentSet<C>) -> Bool {
if lhs.assignments.count != rhs.assignments.count { return false }
for (container, lhsBinding) in lhs {
switch rhs[container] {
case let rhsBinding? where lhsBinding == rhsBinding:
continue
default:
return false
}
}
return true
}
/// A general purpose package dependency resolver.
///
/// This is a general purpose solver for the problem of:
///
/// Given an input list of constraints, where each constraint identifies a
/// container and version requirements, and, where each container supplies a
/// list of additional constraints ("dependencies") for an individual version,
/// then, choose an assignment of containers to versions such that:
///
/// 1. The assignment is complete: there exists an assignment for each container
/// listed in the union of the input constraint list and the dependency list for
/// every container in the assignment at the assigned version.
///
/// 2. The assignment is correct: the assigned version satisfies each constraint
/// referencing its matching container.
///
/// 3. The assignment is maximal: there is no other assignment satisfying #1 and
/// #2 such that all assigned version are greater than or equal to the versions
/// assigned in the result.
///
/// NOTE: It does not follow from #3 that this solver attempts to give an
/// "optimal" result. There may be many possible solutions satisfying #1, #2,
/// and #3, and optimality requires additional information (e.g. a
/// prioritization among packages).
///
/// As described, this problem is NP-complete (*). This solver currently
/// implements a basic depth-first greedy backtracking algorithm, and honoring
/// the order of dependencies as specified in the manifest file. The solver uses
/// persistent data structures to manage the accumulation of state along the
/// traversal, so the backtracking is not explicit, rather it is an implicit
/// side effect of the underlying copy-on-write data structures.
///
/// The resolver will always merge the complete set of immediate constraints for
/// a package (i.e., the version ranges of its immediate dependencies) into the
/// constraint set *before* traversing into any dependency. This property allows
/// packages to manually work around performance issues in the resolution
/// algorithm by _lifting_ problematic dependency constraints up to be immediate
/// dependencies.
///
/// There is currently no external control offered by the solver over _which_
/// solution satisfying the properties above is selected, if more than one are
/// possible. In practice, the algorithm is designed such that it will
/// effectively prefer (i.e., optimize for the newest version of) dependencies
/// which are earliest in the depth-first, pre-order, traversal.
///
/// (*) Via reduction from 3-SAT: Introduce a package for each variable, with
/// two versions representing true and false. For each clause `C_n`, introduce a
/// package `P(C_n)` representing the clause, with three versions; one for each
/// satisfying assignment of values to a literal with the corresponding precise
/// constraint on the input packages. Finally, construct an input constraint
/// list including a dependency on each clause package `P(C_n)` and an
/// open-ended version constraint. The given input is satisfiable iff the input
/// 3-SAT instance is.
public class DependencyResolver<
P: PackageContainerProvider,
D: DependencyResolverDelegate
> where P.Container.Identifier == D.Identifier {
public typealias Provider = P
public typealias Delegate = D
public typealias Container = Provider.Container
public typealias Identifier = Container.Identifier
public typealias Binding = (container: Identifier, binding: BoundVersion)
/// The type of the constraints the resolver operates on.
///
/// Technically this is a container constraint, but that is currently the
/// only kind of constraints we operate on.
public typealias Constraint = PackageContainerConstraint<Identifier>
/// The type of constraint set the resolver operates on.
typealias ConstraintSet = PackageContainerConstraintSet<Container>
/// The type of assignment the resolver operates on.
typealias AssignmentSet = VersionAssignmentSet<Container>
/// The container provider used to load package containers.
public let provider: Provider
/// The resolver's delegate.
public let delegate: Delegate?
/// Should resolver prefetch the containers.
private let isPrefetchingEnabled: Bool
/// Skip updating containers while fetching them.
private let skipUpdate: Bool
// FIXME: @testable private
//
/// Contains any error encountered during dependency resolution.
var error: Swift.Error?
/// Key used to cache a resolved subtree.
private struct ResolveSubtreeCacheKey: Hashable {
let container: Container
let allConstraints: ConstraintSet
var hashValue: Int {
return container.identifier.hashValue ^ allConstraints.hashValue
}
static func ==(lhs: ResolveSubtreeCacheKey, rhs: ResolveSubtreeCacheKey) -> Bool {
return lhs.container.identifier == rhs.container.identifier && lhs.allConstraints == rhs.allConstraints
}
}
/// Cache for subtree resolutions.
private var _resolveSubtreeCache: [ResolveSubtreeCacheKey: AnySequence<AssignmentSet>] = [:]
/// Puts the resolver in incomplete mode.
///
/// In this mode, no new containers will be requested from the provider.
/// Instead, if a container is not already present in the resolver, it will
/// skipped without raising an error. This is useful to avoid cloning
/// repositories from network when trying to partially resolve the constraints.
///
/// Note that the input constraints will always be fetched.
public var isInIncompleteMode = false
public init(
_ provider: Provider,
_ delegate: Delegate? = nil,
isPrefetchingEnabled: Bool = false,
skipUpdate: Bool = false
) {
self.provider = provider
self.delegate = delegate
self.isPrefetchingEnabled = isPrefetchingEnabled
self.skipUpdate = skipUpdate
}
/// The dependency resolver result.
public enum Result {
/// A valid and complete assignment was found.
case success([Binding])
/// The dependency graph was unsatisfiable.
///
/// The payload may contain conflicting constraints and pins.
///
/// - parameters:
/// - dependencies: The package dependencies which make the graph unsatisfiable.
/// - pins: The pins which make the graph unsatisfiable.
case unsatisfiable(dependencies: [Constraint], pins: [Constraint])
/// The resolver encountered an error during resolution.
case error(Swift.Error)
}
/// Execute the resolution algorithm to find a valid assignment of versions.
///
/// If a valid assignment is not found, the resolver will go into incomplete
/// mode and try to find the conflicting constraints.
public func resolve(
dependencies: [Constraint],
pins: [Constraint]
) -> Result {
do {
// Reset the incomplete mode and run the resolver.
self.isInIncompleteMode = false
let constraints = dependencies
return try .success(resolve(constraints: constraints, pins: pins))
} catch DependencyResolverError.unsatisfiable {
// FIXME: can we avoid this do..catch nesting?
do {
// If the result is unsatisfiable, try to debug.
let debugger = ResolverDebugger(self)
let badConstraints = try debugger.debug(dependencies: dependencies, pins: pins)
return .unsatisfiable(dependencies: badConstraints.dependencies, pins: badConstraints.pins)
} catch {
return .error(error)
}
} catch {
return .error(error)
}
}
/// Execute the resolution algorithm to find a valid assignment of versions.
///
/// - Parameters:
/// - constraints: The contraints to solve. It is legal to supply multiple
/// constraints for the same container identifier.
/// - Returns: A satisfying assignment of containers and their version binding.
/// - Throws: DependencyResolverError, or errors from the underlying package provider.
public func resolve(constraints: [Constraint], pins: [Constraint] = []) throws -> [(container: Identifier, binding: BoundVersion)] {
return try resolveAssignment(constraints: constraints, pins: pins).map({ assignment in
let (container, binding) = assignment
let identifier = try self.isInIncompleteMode ? container.identifier : container.getUpdatedIdentifier(at: binding)
// Get the updated identifier from the container.
return (identifier, binding)
})
}
/// Execute the resolution algorithm to find a valid assignment of versions.
///
/// - Parameters:
/// - constraints: The contraints to solve. It is legal to supply multiple
/// constraints for the same container identifier.
/// - Returns: A satisfying assignment of containers and versions.
/// - Throws: DependencyResolverError, or errors from the underlying package provider.
func resolveAssignment(constraints: [Constraint], pins: [Constraint] = []) throws -> AssignmentSet {
// Create a constraint set with the input pins.
var allConstraints = ConstraintSet()
for constraint in pins {
if let merged = allConstraints.merging(constraint) {
allConstraints = merged
} else {
// FIXME: We should issue a warning if the pins can't be merged
// for some reason.
}
}
// Create an assignment for the input constraints.
let mergedConstraints = merge(
constraints: constraints,
into: AssignmentSet(),
subjectTo: allConstraints,
excluding: [:])
// Prefetch the pins.
if !isInIncompleteMode && isPrefetchingEnabled {
prefetch(containers: pins.map({ $0.identifier }))
}
guard let assignment = mergedConstraints.first(where: { _ in true }) else {
// Throw any error encountered during resolution.
if let error = error {
throw error
}
throw DependencyResolverError.unsatisfiable
}
return assignment
}
// FIXME: This needs to a way to return information on the failure, or we
// will need to have it call the delegate directly.
//
// FIXME: @testable private
//
/// Resolve an individual container dependency tree.
///
/// This is the primary method in our bottom-up algorithm for resolving
/// dependencies. The inputs define an active set of constraints and set of
/// versions to exclude (conceptually the latter could be merged with the
/// former, but it is convenient to separate them in our
/// implementation). The result is a sequence of all valid assignments for
/// this container's subtree.
///
/// - Parameters:
/// - container: The container to resolve.
/// - constraints: The external constraints which must be honored by the solution.
/// - exclusions: The list of individually excluded package versions.
/// - Returns: A sequence of feasible solutions, starting with the most preferable.
func resolveSubtree(
_ container: Container,
subjectTo allConstraints: ConstraintSet,
excluding allExclusions: [Identifier: Set<Version>]
) -> AnySequence<AssignmentSet> {
// The key that is used to cache this assignement set.
let cacheKey = ResolveSubtreeCacheKey(container: container, allConstraints: allConstraints)
// Check if we have a cache hit for this subtree resolution.
//
// Note: We don't include allExclusions in the cache key so we ignore
// the cache if its non-empty.
//
// FIXME: We can improve the cache miss rate here if we have a cached
// entry with a broader constraint set. The cached sequence can be
// filtered according to the new narrower constraint set.
if allExclusions.isEmpty, let assignments = _resolveSubtreeCache[cacheKey] {
return assignments
}
func validVersions(_ container: Container, in versionSet: VersionSetSpecifier) -> AnySequence<Version> {
let exclusions = allExclusions[container.identifier] ?? Set()
return AnySequence(container.versions(filter: {
versionSet.contains($0) && !exclusions.contains($0)
}))
}
// Helper method to abstract passing common parameters to merge().
//
// FIXME: We must detect recursion here.
func merge(constraints: [Constraint], binding: BoundVersion) -> AnySequence<AssignmentSet> {
// Create an assignment for the container.
var assignment = AssignmentSet()
assignment[container] = binding
return AnySequence(self.merge(
constraints: constraints,
into: assignment, subjectTo: allConstraints, excluding: allExclusions).lazy.map({ result in
// We might not have a complete result in incomplete mode.
if !self.isInIncompleteMode {
assert(result.checkIfValidAndComplete())
}
return result
}))
}
var result: AnySequence<AssignmentSet>
switch allConstraints[container.identifier] {
case .unversioned:
guard let constraints = self.safely({ try container.getUnversionedDependencies() }) else {
return AnySequence([])
}
// Merge the dependencies of unversioned constraint into the assignment.
result = merge(constraints: constraints, binding: .unversioned)
case .revision(let identifier):
guard let constraints = self.safely({ try container.getDependencies(at: identifier) }) else {
return AnySequence([])
}
result = merge(constraints: constraints, binding: .revision(identifier))
case .versionSet(let versionSet):
// The previous valid version that was picked.
var previousVersion: Version? = nil
// Attempt to select each valid version in the preferred order.
result = AnySequence(validVersions(container, in: versionSet).lazy
.flatMap({ version -> AnySequence<AssignmentSet> in
assert(previousVersion != nil ? previousVersion! > version : true,
"container versions are improperly ordered")
previousVersion = version
// If we had encountered any error, return early.
guard self.error == nil else { return AnySequence([]) }
// Get the constraints for this container version and update the assignment to include each one.
// FIXME: Making these methods throwing will kill the lazy behavior.
guard var constraints = self.safely({ try container.getDependencies(at: version) }) else {
return AnySequence([])
}
// Since we don't want to request additional containers in incomplete
// mode, remove any dependency that we don't already have.
if self.isInIncompleteMode {
constraints = constraints.filter({ self.containers[$0.identifier] != nil })
}
// Since this is a versioned container, none of its
// dependencies can have a revision constraints.
let incompatibleConstraints: [(AnyPackageContainerIdentifier, String)]
incompatibleConstraints = constraints.compactMap({
switch $0.requirement {
case .versionSet:
return nil
case .revision(let revision):
return (AnyPackageContainerIdentifier($0.identifier), revision)
case .unversioned:
// FIXME: Maybe we should have metadata inside unversion to signify
// if its a local or edited dependency. We add edited constraints
// as inputs so it shouldn't really matter because an edited
// requirement can't be specified in the manifest file.
return (AnyPackageContainerIdentifier($0.identifier), "local")
}
})
// If we have any revision constraints, set the error and abort.
guard incompatibleConstraints.isEmpty else {
self.error = DependencyResolverError.incompatibleConstraints(
dependency: (AnyPackageContainerIdentifier(container.identifier), version.description),
revisions: incompatibleConstraints)
return AnySequence([])
}
return merge(constraints: constraints, binding: .version(version))
}))
}
if allExclusions.isEmpty {
// Ensure we can cache this sequence.
result = AnySequence(CacheableSequence(result))
_resolveSubtreeCache[cacheKey] = result
}
return result
}
/// Find all solutions for `constraints` with the results merged into the `assignment`.
///
/// - Parameters:
/// - constraints: The input list of constraints to solve.
/// - assignment: The assignment to merge the result into.
/// - allConstraints: An additional set of constraints on the viable solutions.
/// - allExclusions: A set of package assignments to exclude from consideration.
/// - Returns: A sequence of all valid satisfying assignment, in order of preference.
private func merge(
constraints: [Constraint],
into assignment: AssignmentSet,
subjectTo allConstraints: ConstraintSet,
excluding allExclusions: [Identifier: Set<Version>]
) -> AnySequence<AssignmentSet> {
var allConstraints = allConstraints
// Never prefetch when running in incomplete mode.
if !isInIncompleteMode && isPrefetchingEnabled {
prefetch(containers: constraints.map({ $0.identifier }))
}
// Update the active constraint set to include all active constraints.
//
// We want to put all of these constraints in up front so that we are
// more likely to get back a viable solution.
//
// FIXME: We should have a test for this, probably by adding some kind
// of statistics on the number of backtracks.
for constraint in constraints {
guard let merged = allConstraints.merging(constraint) else {
return AnySequence([])
}
allConstraints = merged
}
// Perform an (eager) reduction merging each container into the (lazy)
// sequence of possible assignments.
//
// NOTE: What we are *accumulating* here is a lazy sequence (of
// solutions) satisfying some number of the constraints; the final lazy
// sequence is effectively one which has all of the constraints
// merged. Thus, the reduce itself can be eager since the result is
// lazy.
return AnySequence(constraints
.map({ $0.identifier })
.reduce(AnySequence([(assignment, allConstraints)]), {
(possibleAssignments, identifier) -> AnySequence<(AssignmentSet, ConstraintSet)> in
// If we had encountered any error, return early.
guard self.error == nil else { return AnySequence([]) }
// Get the container.
//
// Failures here will immediately abort the solution, although in
// theory one could imagine attempting to find a solution not
// requiring this container. It isn't clear that is something we
// would ever want to handle at this level.
//
// FIXME: Making these methods throwing will kill the lazy behavior,
guard let container = safely({ try getContainer(for: identifier) }) else {
return AnySequence([])
}
// Return a new lazy sequence merging all possible subtree solutions into all possible incoming
// assignments.
return AnySequence(possibleAssignments.lazy.flatMap({ value -> AnySequence<(AssignmentSet, ConstraintSet)> in
let (assignment, allConstraints) = value
let subtree = self.resolveSubtree(container, subjectTo: allConstraints, excluding: allExclusions)
return AnySequence(subtree.lazy.compactMap({ subtreeAssignment -> (AssignmentSet, ConstraintSet)? in
// We found a valid subtree assignment, attempt to merge it with the
// current solution.
guard let newAssignment = assignment.merging(subtreeAssignment) else {
// The assignment couldn't be merged with the current
// assignment, or the constraint sets couldn't be merged.
//
// This happens when (a) the subtree has a package overlapping
// with a previous subtree assignment, and (b) the subtrees
// needed to resolve different versions due to constraints not
// present in the top-down constraint set.
return nil
}
// Update the working assignment and constraint set.
//
// This should always be feasible, because all prior constraints
// were part of the input constraint request (see comment around
// initial `merge` outside the loop).
guard let merged = allConstraints.merging(subtreeAssignment.constraints) else {
preconditionFailure("unsatisfiable constraints while merging subtree")
}
// We found a valid assignment and updated constraint set.
return (newAssignment, merged)
}))
}))
})
.lazy
.map({ $0.0 }))
}
/// Executes the body and return the value if the body doesn't throw.
/// Returns nil if the body throws and save the error.
private func safely<T>(_ body: () throws -> T) -> T? {
do {
return try body()
} catch {
self.error = error
}
return nil
}
// MARK: Container Management
/// Condition for container management structures.
private let fetchCondition = Condition()
/// The active set of managed containers.
public var containers: [Identifier: Container] {
return fetchCondition.whileLocked({
_fetchedContainers.spm_flatMapValues({
try? $0.dematerialize()
})
})
}
/// The list of fetched containers.
private var _fetchedContainers: [Identifier: Basic.Result<Container, AnyError>] = [:]
/// The set of containers requested so far.
private var _prefetchingContainers: Set<Identifier> = []
/// Get the container for the given identifier, loading it if necessary.
fileprivate func getContainer(for identifier: Identifier) throws -> Container {
return try fetchCondition.whileLocked {
// Return the cached container, if available.
if let container = _fetchedContainers[identifier] {
return try container.dematerialize()
}
// If this container is being prefetched, wait for that to complete.
while _prefetchingContainers.contains(identifier) {
fetchCondition.wait()
}
// The container may now be available in our cache if it was prefetched.
if let container = _fetchedContainers[identifier] {
return try container.dematerialize()
}
// Otherwise, fetch the container synchronously.
let container = try await { provider.getContainer(for: identifier, skipUpdate: skipUpdate, completion: $0) }
self._fetchedContainers[identifier] = Basic.Result(container)
return container
}
}
/// Starts prefetching the given containers.
private func prefetch(containers identifiers: [Identifier]) {
fetchCondition.whileLocked {
// Process each container.
for identifier in identifiers {
// Skip if we're already have this container or are pre-fetching it.
guard _fetchedContainers[identifier] == nil,
!_prefetchingContainers.contains(identifier) else {
continue
}
// Otherwise, record that we're prefetching this container.
_prefetchingContainers.insert(identifier)
provider.getContainer(for: identifier, skipUpdate: skipUpdate) { container in
self.fetchCondition.whileLocked {
// Update the structures and signal any thread waiting
// on prefetching to finish.
self._fetchedContainers[identifier] = container
self._prefetchingContainers.remove(identifier)
self.fetchCondition.signal()
}
}
}
}
}
}
/// The resolver debugger.
///
/// Finds the constraints which results in graph being unresolvable.
private struct ResolverDebugger<
Provider: PackageContainerProvider,
Delegate: DependencyResolverDelegate
> where Provider.Container.Identifier == Delegate.Identifier {
typealias Identifier = Provider.Container.Identifier
typealias Constraint = PackageContainerConstraint<Identifier>
enum Error: Swift.Error {
/// Reached the time limit without completing the algorithm.
case reachedTimeLimit
}
/// Reference to the resolver.
unowned let resolver: DependencyResolver<Provider, Delegate>
/// Create a new debugger.
init(_ resolver: DependencyResolver<Provider, Delegate>) {
self.resolver = resolver
}
/// The time limit in seconds after which we abort finding a solution.
let timeLimit = 10.0
/// Returns the constraints which should be removed in order to make the
/// graph resolvable.
///
/// We use delta debugging algoritm to find the smallest set of constraints
/// which can be removed from the input in order to make the graph
/// satisfiable.
///
/// This algorithm can be exponential, so we abort after the predefined time limit.
func debug(
dependencies inputDependencies: [Constraint],
pins inputPins: [Constraint]
) throws -> (dependencies: [Constraint], pins: [Constraint]) {
// Form the dependencies array.
//
// We iterate over the inputs and fetch all the dependencies for
// unversioned requirements as the unversioned requirements are not
// relevant to the dependency resolution.
var dependencies = [Constraint]()
for constraint in inputDependencies {
if constraint.requirement == .unversioned {
// Ignore the errors here.
do {
let container = try resolver.getContainer(for: constraint.identifier)
dependencies += try container.getUnversionedDependencies()
} catch {}
} else {
dependencies.append(constraint)
}
}
// Form a set of all unversioned dependencies.
let unversionedDependencies = Set(inputDependencies.filter({ $0.requirement == .unversioned }).map({ $0.identifier }))
// Remove the unversioned constraints from dependencies and pins.
dependencies = dependencies.filter({ !unversionedDependencies.contains($0.identifier) })
let pins = inputPins.filter({ !unversionedDependencies.contains($0.identifier) })
// Put the resolver in incomplete mode to avoid cloning new repositories.
resolver.isInIncompleteMode = true
let deltaAlgo = DeltaAlgorithm<ResolverChange>()
let allPackages = Set(dependencies.map({ $0.identifier }))
// Compute the set of changes.
let allChanges: Set<ResolverChange> = {
var set = Set<ResolverChange>()
set.formUnion(dependencies.map({ ResolverChange.allowPackage($0.identifier) }))
set.formUnion(pins.map({ ResolverChange.allowPin($0.identifier) }))
return set
}()
// Compute the current time.
let startTime = NSDate().timeIntervalSince1970
var timeLimitReached = false
// Run the delta debugging algorithm.
let badChanges = try deltaAlgo.run(changes: allChanges) { changes in
// Check if we reached the time limits.
timeLimitReached = timeLimitReached || (NSDate().timeIntervalSince1970 - startTime) >= timeLimit
// If we reached the time limit, throw.
if timeLimitReached {
throw Error.reachedTimeLimit
}
// Find the set of changes we want to allow in this predicate.
let allowedChanges = allChanges.subtracting(changes)
// Find the packages which are allowed and disallowed to participate
// in this changeset.
let allowedPackages = Set(allowedChanges.compactMap({ $0.allowedPackage }))
let disallowedPackages = allPackages.subtracting(allowedPackages)
// Start creating constraints.
//
// First, add all the package dependencies.
var constraints = dependencies
// Set all disallowed packages to unversioned, so they stay out of resolution.
constraints += disallowedPackages.map({
Constraint(container: $0, requirement: .unversioned)
})
let allowedPins = Set(allowedChanges.compactMap({ $0.allowedPin }))
// It is always a failure if this changeset contains a pin of
// a disallowed package.
if allowedPins.first(where: disallowedPackages.contains) != nil {
return false
}
// Finally, add the allowed pins.
constraints += pins.filter({ allowedPins.contains($0.identifier) })
return try satisfies(constraints)
}
// Filter the input with found result and return.
let badDependencies = Set(badChanges.compactMap({ $0.allowedPackage }))
let badPins = Set(badChanges.compactMap({ $0.allowedPin }))
return (
dependencies: dependencies.filter({ badDependencies.contains($0.identifier) }),
pins: pins.filter({ badPins.contains($0.identifier) })
)
}
/// Returns true if the constraints are satisfiable.
func satisfies(_ constraints: [Constraint]) throws -> Bool {
do {
_ = try resolver.resolve(constraints: constraints, pins: [])
return true
} catch DependencyResolverError.unsatisfiable {
return false
}
}
/// Represents a single change which should introduced during delta debugging.
enum ResolverChange: Hashable {
/// Allow the package with the given identifier.
case allowPackage(Identifier)
/// Allow the pins with the given identifier.
case allowPin(Identifier)
/// Returns the allowed pin identifier.
var allowedPin: Identifier? {
if case let .allowPin(identifier) = self {
return identifier
}
return nil
}
// Returns the allowed package identifier.
var allowedPackage: Identifier? {
if case let .allowPackage(identifier) = self {
return identifier
}
return nil
}
}
}
| 40.690054 | 136 | 0.628045 |
e48a547337a646d33c3fa16c93c8820556217e2f | 8,605 | //
// Includes.swift
// JSONAPI
//
// Created by Mathew Polzin on 11/10/18.
//
import Poly
public typealias Include = EncodableJSONPoly
/// A structure holding zero or more included Resource Objects.
/// The resources are accessed by their type using a subscript.
///
/// If you have
///
/// let includes: Includes<Include2<Thing1, Thing2>> = ...
///
/// then you can access all `Thing1` included resources with
///
/// let includedThings = includes[Thing1.self]
public struct Includes<I: Include>: Encodable, Equatable {
public static var none: Includes { return .init(values: []) }
public let values: [I]
public init(values: [I]) {
self.values = values
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
guard I.self != NoIncludes.self else {
throw JSONAPICodingError.illegalEncoding("Attempting to encode Include0, which should be represented by the absense of an 'included' entry altogether.", path: encoder.codingPath)
}
for value in values {
try container.encode(value)
}
}
public var count: Int {
return values.count
}
}
extension Includes: Decodable where I: Decodable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
// If not parsing includes, no need to loop over them.
guard I.self != NoIncludes.self else {
values = []
return
}
var valueAggregator = [I]()
var idx = 0
while !container.isAtEnd {
do {
valueAggregator.append(try container.decode(I.self))
idx = idx + 1
} catch let error as PolyDecodeNoTypesMatchedError {
let errors: [ResourceObjectDecodingError] = error
.individualTypeFailures
.compactMap { decodingError in
switch decodingError.error {
case .typeMismatch(_, let context),
.valueNotFound(_, let context),
.keyNotFound(_, let context),
.dataCorrupted(let context):
return context.underlyingError as? ResourceObjectDecodingError
@unknown default:
return nil
}
}
guard errors.count == error.individualTypeFailures.count else {
throw IncludesDecodingError(error: error, idx: idx, totalIncludesCount: container.count ?? 0)
}
throw IncludesDecodingError(
error: IncludeDecodingError(failures: errors),
idx: idx,
totalIncludesCount: container.count ?? 0
)
} catch let error {
throw IncludesDecodingError(error: error, idx: idx, totalIncludesCount: container.count ?? 0)
}
}
values = valueAggregator
}
}
extension Includes {
public func appending(_ other: Includes<I>) -> Includes {
return Includes(values: values + other.values)
}
}
public func +<I: Include>(_ left: Includes<I>, _ right: Includes<I>) -> Includes<I> {
return left.appending(right)
}
extension Includes: CustomStringConvertible {
public var description: String {
return "Includes(\(String(describing: values))"
}
}
extension Includes where I == NoIncludes {
public init() {
values = []
}
}
// MARK: - 0 includes
public typealias Include0 = Poly0
public typealias NoIncludes = Include0
// MARK: - 1 include
public typealias Include1 = Poly1
extension Includes where I: _Poly1 {
public subscript(_ lookup: I.A.Type) -> [I.A] {
return values.compactMap(\.a)
}
}
// MARK: - 2 includes
public typealias Include2 = Poly2
extension Includes where I: _Poly2 {
public subscript(_ lookup: I.B.Type) -> [I.B] {
return values.compactMap(\.b)
}
}
// MARK: - 3 includes
public typealias Include3 = Poly3
extension Includes where I: _Poly3 {
public subscript(_ lookup: I.C.Type) -> [I.C] {
return values.compactMap(\.c)
}
}
// MARK: - 4 includes
public typealias Include4 = Poly4
extension Includes where I: _Poly4 {
public subscript(_ lookup: I.D.Type) -> [I.D] {
return values.compactMap(\.d)
}
}
// MARK: - 5 includes
public typealias Include5 = Poly5
extension Includes where I: _Poly5 {
public subscript(_ lookup: I.E.Type) -> [I.E] {
return values.compactMap(\.e)
}
}
// MARK: - 6 includes
public typealias Include6 = Poly6
extension Includes where I: _Poly6 {
public subscript(_ lookup: I.F.Type) -> [I.F] {
return values.compactMap(\.f)
}
}
// MARK: - 7 includes
public typealias Include7 = Poly7
extension Includes where I: _Poly7 {
public subscript(_ lookup: I.G.Type) -> [I.G] {
return values.compactMap(\.g)
}
}
// MARK: - 8 includes
public typealias Include8 = Poly8
extension Includes where I: _Poly8 {
public subscript(_ lookup: I.H.Type) -> [I.H] {
return values.compactMap(\.h)
}
}
// MARK: - 9 includes
public typealias Include9 = Poly9
extension Includes where I: _Poly9 {
public subscript(_ lookup: I.I.Type) -> [I.I] {
return values.compactMap(\.i)
}
}
// MARK: - 10 includes
public typealias Include10 = Poly10
extension Includes where I: _Poly10 {
public subscript(_ lookup: I.J.Type) -> [I.J] {
return values.compactMap(\.j)
}
}
// MARK: - 11 includes
public typealias Include11 = Poly11
extension Includes where I: _Poly11 {
public subscript(_ lookup: I.K.Type) -> [I.K] {
return values.compactMap(\.k)
}
}
// MARK: - DecodingError
public struct IncludesDecodingError: Swift.Error, Equatable {
public let error: Swift.Error
/// The zero-based index of the include that failed to decode.
public let idx: Int
/// The total count of includes in the document that failed to decode.
///
/// In other words, "of `totalIncludesCount` includes, the `(idx + 1)`th
/// include failed to decode.
public let totalIncludesCount: Int
public static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.idx == rhs.idx
&& String(describing: lhs) == String(describing: rhs)
}
}
extension IncludesDecodingError: CustomStringConvertible {
public var description: String {
let ordinalSuffix: String
if (idx % 100) + 1 > 9 && (idx % 100) + 1 < 20 {
// the teens
ordinalSuffix = "th"
} else {
switch ((idx % 10) + 1) {
case 1:
ordinalSuffix = "st"
case 2:
ordinalSuffix = "nd"
case 3:
ordinalSuffix = "rd"
default:
ordinalSuffix = "th"
}
}
let ordinalDescription = "\(idx + 1)\(ordinalSuffix)"
return "Out of the \(totalIncludesCount) includes in the document, the \(ordinalDescription) one failed to parse: \(error)"
}
}
public struct IncludeDecodingError: Swift.Error, Equatable, CustomStringConvertible {
public let failures: [ResourceObjectDecodingError]
public var description: String {
// concise error when all failures are mismatched JSON:API types:
if case let .jsonTypeMismatch(foundType: foundType)? = failures.first?.cause,
failures.allSatisfy({ $0.cause.isTypeMismatch }) {
let expectedTypes = failures
.compactMap { "'\($0.resourceObjectJsonAPIType)'" }
.joined(separator: ", ")
return "Found JSON:API type '\(foundType)' but expected one of \(expectedTypes)"
}
// concise error when all but failures but one are type mismatches because
// we can assume the correct type was found but there was some other error:
let nonTypeMismatches = failures.filter({ !$0.cause.isTypeMismatch})
if nonTypeMismatches.count == 1, let nonTypeMismatch = nonTypeMismatches.first {
return String(describing: nonTypeMismatch)
}
// fall back to just describing all of the reasons it could not have been any of the available
// types:
return failures
.enumerated()
.map {
"\nCould not have been Include Type `\($0.element.resourceObjectJsonAPIType)` because:\n\($0.element)"
}.joined(separator: "\n")
}
}
| 30.732143 | 190 | 0.602905 |
0829e71a84b467250be77b20045e27c490fa0f78 | 5,197 | // The MIT License (MIT)
// Copyright (c) 2015 JohnLui <[email protected]> https://github.com/johnlui
// 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.
//
// JSONND.swift
// JSONNeverDie
//
// Created by 吕文翰 on 15/10/7.
//
import Foundation
public struct JSONND {
public static var debug = false
public var data: Any!
public init(string: String, encoding: String.Encoding = String.Encoding.utf8) {
do {
if let data = string.data(using: encoding) {
let d = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
self.data = d as AnyObject!
}
} catch let error as NSError {
let e = NSError(domain: "JSONNeverDie.JSONParseError", code: error.code, userInfo: error.userInfo)
if JSONND.debug { NSLog(e.localizedDescription) }
}
}
fileprivate init(any: AnyObject) {
let j: JSONND = [any]
self.data = j.arrayValue.first?.data
}
internal init(JSONdata: AnyObject!) {
self.data = JSONdata
}
public init() {
self.init(JSONdata: nil)
}
public init(dictionary: [String: Any]) {
self.init(any: dictionary as AnyObject)
}
public init(array: [Any]) {
self.init(any: array as AnyObject)
}
public subscript (index: String) -> JSONND {
if let jsonDictionary = self.data as? Dictionary<String, AnyObject> {
if let value = jsonDictionary[index] {
return JSONND(JSONdata: value)
} else {
if JSONND.debug { NSLog("JSONNeverDie: No such key '\(index)'") }
}
}
return JSONND(JSONdata: nil)
}
public var RAW: String? {
get {
if let _ = self.data {
do {
let d = try JSONSerialization.data(withJSONObject: self.data, options: .prettyPrinted)
return NSString(data: d, encoding: String.Encoding.utf8.rawValue) as String?
} catch { return nil }
// can not test Errors here.
// It seems that NSJSONSerialization.dataWithJSONObject() method dose not support do-try-catch in Swift 2 now.
}
return nil
}
}
public var RAWValue: String {
get {
return self.RAW ?? ""
}
}
public var int: Int? {
get {
if let number = self.data as? NSNumber {
return number.intValue
}
if let number = self.data as? NSString {
return number.integerValue
}
return nil
}
}
public var intValue: Int {
get {
return self.int ?? 0
}
}
public var double: Double? {
get {
if let number = self.data as? NSNumber {
return number.doubleValue
}
if let number = self.data as? NSString {
return number.doubleValue
}
return nil
}
}
public var doubleValue: Double {
get {
return self.double ?? 0.0
}
}
public var string: String? {
get {
return self.data as? String
}
}
public var stringValue: String {
get {
return self.string ?? ""
}
}
public var bool: Bool? {
get {
return self.data as? Bool
}
}
public var boolValue: Bool {
get {
return self.bool ?? false
}
}
public var array: [JSONND]? {
get {
if let _ = self.data {
if let arr = self.data as? Array<AnyObject> {
var result = Array<JSONND>()
for i in arr {
result.append(JSONND(JSONdata: i))
}
return result
}
return nil
}
return nil
}
}
public var arrayValue: [JSONND] {
get {
return self.array ?? []
}
}
}
| 30.570588 | 126 | 0.55532 |
67b254b53b859edcc6c06f1a70b07a7c43a6e557 | 1,094 | //
// DynamicValue.swift
// DragabbleViewController
//
// Created by Kedar Sukerkar on 21/08/19.
// Copyright © 2019 Kedar Sukerkar. All rights reserved.
//
import Foundation
class DynamicValue<T> {
// MARK: - Properties
typealias CompletionHandler = ((T) -> Void)
var value : T {
didSet {
self.notify()
}
}
private var observers = [String: CompletionHandler]()
// MARK: - Initializer
init(_ value: T) {
self.value = value
}
deinit {
observers.removeAll()
}
// MARK: - Observers
public func addObserver(_ observer: NSObject, completionHandler: @escaping CompletionHandler) {
observers[observer.description] = completionHandler
}
public func addAndNotify(observer: NSObject, completionHandler: @escaping CompletionHandler) {
self.addObserver(observer, completionHandler: completionHandler)
self.notify()
}
private func notify() {
observers.forEach({ $0.value(value) })
}
}
| 19.890909 | 99 | 0.595978 |
22189ed8e85b6c1b35dd5f12a4207ed36b4de25c | 2,202 | //
// Union.swift
// Algorithm
//
// Created by amoyio on 2018/9/15.
// Copyright © 2018年 amoyio. All rights reserved.
//
import Foundation
class UnionSet {
var dataset: [Int] = []
init(capacity: Int) {
for i in 0...capacity {
dataset.append(i)
}
}
var size: Int {
return dataset.count
}
/// 获取第 i 个元素所属的集合序号
func find(index: Int) -> Int {
guard index >= 0 && index < size else { return -1 }
return dataset[index]
}
func isConnected(lIndex:Int, rIndex:Int) -> Bool {
return dataset[lIndex] == dataset[rIndex]
}
func unionElements(lIndex:Int, rIndex:Int) {
guard lIndex != rIndex else { return }
let lSetID = dataset[lIndex]
let rSetID = dataset[rIndex]
if lSetID != rSetID {
for i in 0...dataset.count {
dataset[i] = lSetID
}
}
}
}
class UnionFind {
var parent:[Int] = []
var rank:[Int] = []
init(capacity: Int) {
for i in 0...capacity {
parent.append(i)
rank.append(1)
}
}
var size: Int {
return parent.count
}
/// 获取第 i 个元素所属的集合序号
func find(index:Int) -> Int {
guard index >= 0 && index < size else { return -1 }
var currentIndex = index
while currentIndex != parent[currentIndex] {
// 路径压缩
parent[currentIndex] = parent[parent[currentIndex]]
currentIndex = parent[currentIndex]
}
return currentIndex
}
func isConnected(lIndex:Int, rIndex:Int) -> Bool {
return parent[lIndex] == parent[rIndex]
}
func unionElements(lIndex:Int, rIndex:Int) {
let lIndexID = find(index: lIndex)
let rIndexID = find(index: rIndex)
if lIndexID == rIndexID {
return
}
if rank[lIndexID] < rank[rIndexID] {
parent[lIndexID] = rIndexID
}else if rank[lIndexID] > rank[rIndexID] {
parent[rIndexID] = lIndexID
}else{
parent[lIndexID] = rIndexID
rank[rIndexID] += 1
}
}
}
| 23.677419 | 63 | 0.519982 |
fe251fb2a35273f45d1a73d8e07e5aa5e69e16b1 | 1,357 | import Quick
import Nimble
import Foundation
@testable import MiniApp
class MiniAppURLRequestTests: QuickSpec {
override func spec() {
describe("create url request") {
guard let url = URL(string: mockHost) else {
return
}
let mockBundle = MockBundle()
let environment = Environment(bundle: mockBundle)
context("when subscription key is available") {
it("will set the apikey authorization header") {
mockBundle.mockSubscriptionKey = "mini-subscription-key"
let urlRequest = URLRequest.createURLRequest(url: url, environment: environment)
let headerField = urlRequest.value(forHTTPHeaderField: "apiKey")
expect(headerField).to(equal("ras-mini-subscription-key"))
}
}
context("when subscription key is not available") {
it("will not set the apikey authorization header") {
mockBundle.mockSubscriptionKey = nil
let urlRequest = URLRequest.createURLRequest(url: url, environment: environment)
let headerField = urlRequest.value(forHTTPHeaderField: "apiKey")
expect(headerField).to(beNil())
}
}
}
}
}
| 39.911765 | 100 | 0.576271 |
6117a5fb19850556b9d32d095025a5dc16a7a549 | 1,338 | //
// UIView+Category.swift
// STVideoPlayer
//
// Created by ShaoFeng on 2017/2/28.
// Copyright © 2017年 ShaoFeng. All rights reserved.
//
import Foundation
// MARK: - UIView分类
extension UIView {
/// 切换分辨率时候调用此方法
public func playerResetControlViewForResolution() {
}
/// 重置controlView
public func playerResetControlView() {
}
// public func playerPlayBtnState(state: Bool) {
//
// }
public func playerCancelAutoFadeOutControlView() {
}
// public func playerShowControlView() {
//
// }
//Method cannot be declared public because its parameter uses an internal type
// public func playerModel(playerModel: STPlayerModel) {
//
// }
public func playerCellPlay() {
}
// public func playerDownloadBtnState(state: Bool) {
//
// }
public func playerPlayEnd() {
}
public func playCurrentTime(currentTime: NSInteger, totalTime: NSInteger, sliderValue: CGFloat) {
}
/// 小屏播放
public func playerBottomShrinkPlay() {
}
/// 是否具有切换分别率功能
public func playerResolutionArray(resolutionArray: Array<Any>) {
}
public func playerSetProgress(progress: CGFloat) {
}
}
| 19.391304 | 101 | 0.57997 |
fcec94825ecf1c1294f9e8429a780a5af3c21d16 | 95 | import XCTest
@testable import GrammarTests
XCTMain([
testCase(GrammarTests.allTests),
])
| 13.571429 | 36 | 0.768421 |
fe25827c108aa4d85a3d4ac7da5417fd97e84b54 | 10,437 | //
// ConnectionsViewController.swift
// lnd-gui
//
// Created by Alex Bosworth on 4/4/17.
// Copyright © 2017 Adylitica. All rights reserved.
//
import Cocoa
/** ConnectionsViewController is a view controller for creating invoices.
FIXME: - when there is no chain balance, funds can't be increased, should prompt to lower from another channel
FIXME: - add disconnect option
FIXME: - this should be a new window
FIXME: - when there are no peers it should display an empty peers notification
FIXME: - after adding a peer, the peer should show up
FIXME: - when kind of but not fully selecting a connection it doesn't show the appropriate menu item
FIXME: - need a way to see the channel status, like look at the related transaction
FIXME: - when connecting, the connection should show as grayed out
FIXME: - this should be part of a window with other preferences
FIXME: - allow viewing the fee policies and updating them
*/
class ConnectionsViewController: NSViewController, ErrorReporting {
// MARK: - @IBOutlets
/** Connections table view
*/
@IBOutlet weak var connectionsTableView: NSTableView?
// MARK: - Properties
/** Add peer view controller
*/
var addPeerViewController: AddPeerViewController?
/** Connections
*/
lazy var connections: [Connection] = []
/** Report error
*/
lazy var reportError: (Error) -> () = { _ in }
}
// MARK: - Columns
extension ConnectionsViewController {
/** Table columns
*/
fileprivate enum Column: StoryboardIdentifier {
case balance = "BalanceColumn"
case online = "OnlineColumn"
case ping = "PingColumn"
case publicKey = "PublicKeyColumn"
/** Create from a table column
*/
init?(fromTableColumn col: NSTableColumn?) {
if let id = col?.identifier, let column = type(of: self).init(rawValue: id) { self = column } else { return nil }
}
/** Cell identifier for column cell
*/
var asCellIdentifier: String {
switch self {
case .balance:
return "BalanceCell"
case .online:
return "OnlineCell"
case .ping:
return "PingCell"
case .publicKey:
return "PublicKeyCell"
}
}
/** Column identifier
*/
var asColumnIdentifier: String { return rawValue }
/** Make a cell in column
*/
func makeCell(inTableView tableView: NSTableView, withTitle title: String) -> NSTableCellView? {
let cell = tableView.make(withIdentifier: asCellIdentifier, owner: nil) as? NSTableCellView
cell?.textField?.stringValue = title
return cell
}
}
}
// MARK: - Errors
extension ConnectionsViewController {
/** Failures
*/
enum Failure: Error {
case expectedChannelId
case expectedVC
case unexpectedSegue
}
}
// MARK: - Networking
extension ConnectionsViewController {
/** Get connections JSON errors
*/
private enum GetJsonFailure: String, Error {
case expectedData
case expectedJson
}
/** Show connections
*/
private func show(connections: [Connection]) throws {
self.connections = connections.sorted { $0.publicKey.hexEncoded > $1.publicKey.hexEncoded }
connectionsTableView?.reloadData()
}
/** Refresh connections
*/
func refreshConnections() throws {
try Daemon.getConnections { [weak self] result in
switch result {
case .connections(let connections):
do { try self?.show(connections: connections) } catch { self?.reportError(error) }
case .error(let error):
self?.reportError(error)
}
}
}
}
// MARK: - NSMenuDelegate
extension ConnectionsViewController: NSMenuDelegate {
/** Close channel
*/
func close(_ channel: Channel) throws {
guard let channelId = channel.id else { throw Failure.expectedChannelId }
try Daemon.delete(in: .channels(channelId)) { [weak self] result in
switch result {
case .error(let error):
self?.reportError(error)
case .success:
do { try self?.refreshConnections() } catch { self?.reportError(error) }
}
}
}
/** Decrease channel balance
*/
func decreaseChannelBalance() throws {
guard let clickedConnectionAtRow = connectionsTableView?.clickedRow else { return print("expectedClickedRow") }
guard let connection = connection(at: clickedConnectionAtRow) else { return print("expectedConnection") }
try connection.channels.forEach { try close($0) }
}
/** Increase channel balance
*/
func increaseChannelBalance() {
guard let clickedConnectionAtRow = connectionsTableView?.clickedRow else { return print("expectedClickedRow") }
guard let connection = connection(at: clickedConnectionAtRow) else { return print("expectedConnection") }
guard let _ = connection.peers.first else { return print("expectedPeer") }
do { try openChannel(with: connection) } catch { reportError(error) }
}
/** Init the connections table menu
*/
fileprivate func initMenu() {
connectionsTableView?.menu = NSMenu()
connectionsTableView?.menu?.delegate = self
}
/** Context menu is appearing
*/
func menuNeedsUpdate(_ menu: NSMenu) {
menu.removeAllItems()
guard let selected = connectionsTableView?.selectedRow, let connection = connection(at: selected) else {
menu.addItem(NSMenuItem(title: "Add Peer", action: #selector(segueToAddPeer), keyEquivalent: String()))
return
}
switch connection.balance > Tokens() {
case false:
menu.addItem(NSMenuItem(title: "Increase Channel Balance", action: #selector(increaseChannelBalance), keyEquivalent: String()))
case true:
menu.addItem(NSMenuItem(title: "Decrease Channel Balance", action: #selector(decreaseChannelBalance), keyEquivalent: String()))
}
}
enum Segue: StoryboardIdentifier {
case addPeer = "AddPeerSegue"
var storyboardIdentifier: StoryboardIdentifier { return rawValue }
init?(from segue: NSStoryboardSegue) {
if let id = segue.identifier, let segue = type(of: self).init(rawValue: id) { self = segue } else { return nil }
}
}
/** Prepare for segue
*/
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
let destinationViewController = segue.destinationController
guard let segue = Segue(from: segue) else { return reportError(Failure.unexpectedSegue) }
switch segue {
case .addPeer:
guard let vc = destinationViewController as? AddPeerViewController else { return reportError(Failure.expectedVC) }
self.addPeerViewController = vc
vc.addedPeer = { [weak self] in
do {
try self?.refreshConnections()
} catch {
self?.reportError(error)
}
}
vc.reportError = { [weak self] error in self?.reportError(error) }
}
}
/** Navigate to add peer sheet
*/
func segueToAddPeer() {
performSegue(withIdentifier: Segue.addPeer.storyboardIdentifier, sender: self)
}
/** Open a channel with a connection
*/
func openChannel(with connection: Connection) throws {
let json = ["partner_public_key": connection.publicKey.hexEncoded]
try Daemon.send(json: json, to: .channels(String())) { [weak self] result in
switch result {
case .error(let error):
self?.reportError(error)
case .success(_):
do { try self?.refreshConnections() } catch { self?.reportError(error) }
}
}
}
}
extension ConnectionsViewController: NSTableViewDataSource {
/** Data source error
*/
enum DataSourceError: String, Error {
case expectedKnownColumn
case expectedConnectionForRow
}
/** Number of rows in table
*/
func numberOfRows(in tableView: NSTableView) -> Int {
return connections.count
}
/** Make cell for row at column
*/
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let column = Column(fromTableColumn: tableColumn) else {
print(DataSourceError.expectedKnownColumn)
return nil
}
guard let connection = connection(at: row) else { print(DataSourceError.expectedConnectionForRow); return nil }
let title: String
switch column {
case .balance:
title = connection.balance.formatted(with: .testBitcoin)
case .online:
let hasActivePeer = !connection.peers.isEmpty
guard hasActivePeer else { title = "Offline"; break }
let hasActiveChannel = connection.channels.contains { $0.state == .active }
guard !hasActiveChannel else { title = "Online"; break }
let hasOpeningChannel = connection.channels.contains { $0.state == .opening }
guard !hasOpeningChannel else { title = "Connecting"; break }
let hasClosingChannel = connection.channels.contains { $0.state == .closing }
guard !hasClosingChannel else { title = "Closing"; break }
title = "Online"
case .ping:
guard let ping = connection.bestPing else {
title = " "
break
}
title = "\(ping)ms"
case .publicKey:
title = connection.publicKey.hexEncoded
}
return column.makeCell(inTableView: tableView, withTitle: title)
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
return connection(at: row)
}
/** Get a connection for a row number
*/
fileprivate func connection(at row: Int) -> Connection? {
guard row >= Int() && row < connections.count else { return nil }
return connections[row]
}
}
// MARK: - NSTableViewDelegate
extension ConnectionsViewController: NSTableViewDelegate {}
// MARK: - NSViewController
extension ConnectionsViewController {
/** View will appear
*/
override func viewWillAppear() {
super.viewWillAppear()
do { try refreshConnections() } catch { reportError(error) }
}
/** View loaded
*/
override func viewDidLoad() {
super.viewDidLoad()
initMenu()
}
}
// MARK: - WalletListener
extension ConnectionsViewController: WalletListener {
/** Wallet was updated
*/
func walletUpdated() {
do { try refreshConnections() } catch { reportError(error) }
// FIXME: - animate changes
}
}
| 27.757979 | 133 | 0.65881 |
1d720af81fe465c2a705f0328e8a5af5a237ef38 | 3,481 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
import Foundation
import CityMap
var runner = BenchmarksRunner()
let args = KotlinArray(size: Int32(CommandLine.arguments.count - 1), init: {index in
CommandLine.arguments[Int(truncating: index) + 1]
})
let companion = BenchmarkEntryWithInit.Companion()
var swiftLauncher = SwiftLauncher()
runner.runBenchmarks(args: args, run: { (parser: ArgParser) -> [BenchmarkResult] in
swiftLauncher.add(name: "createMultigraphOfInt", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() },
lambda: { ($0 as! SwiftInteropBenchmarks).createMultigraphOfInt() }))
swiftLauncher.add(name: "fillCityMap", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() },
lambda: { ($0 as! SwiftInteropBenchmarks).fillCityMap() }))
swiftLauncher.add(name: "searchRoutesInSwiftMultigraph", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() },
lambda: { ($0 as! SwiftInteropBenchmarks).searchRoutesInSwiftMultigraph () }))
swiftLauncher.add(name: "searchTravelRoutes", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() },
lambda: { ($0 as! SwiftInteropBenchmarks).searchTravelRoutes() }))
swiftLauncher.add(name: "availableTransportOnMap", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() },
lambda: { ($0 as! SwiftInteropBenchmarks).availableTransportOnMap() }))
swiftLauncher.add(name: "allPlacesMapedByInterests", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() },
lambda: { ($0 as! SwiftInteropBenchmarks).allPlacesMapedByInterests() }))
swiftLauncher.add(name: "getAllPlacesWithStraightRoutesTo", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() },
lambda: { ($0 as! SwiftInteropBenchmarks).getAllPlacesWithStraightRoutesTo() }))
swiftLauncher.add(name: "goToAllAvailablePlaces", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() },
lambda: { ($0 as! SwiftInteropBenchmarks).goToAllAvailablePlaces() }))
swiftLauncher.add(name: "removeVertexAndEdgesSwiftMultigraph", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() },
lambda: { ($0 as! SwiftInteropBenchmarks).removeVertexAndEdgesSwiftMultigraph() }))
swiftLauncher.add(name: "stringInterop", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() },
lambda: { ($0 as! SwiftInteropBenchmarks).stringInterop() }))
swiftLauncher.add(name: "simpleFunction", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() },
lambda: { ($0 as! SwiftInteropBenchmarks).simpleFunction() }))
return swiftLauncher.launch(numWarmIterations: parser.get(name: "warmup") as! Int32,
numberOfAttempts: parser.get(name: "repeat") as! Int32,
prefix: parser.get(name: "prefix") as! String, filters: parser.getAll(name: "filter"),
filterRegexes: parser.getAll(name: "filterRegex"))
}, parseArgs: { (args: KotlinArray, benchmarksListAction: ((ArgParser) -> KotlinUnit)) -> ArgParser? in
return runner.parse(args: args, benchmarksListAction: swiftLauncher.benchmarksListAction) },
collect: { (benchmarks: [BenchmarkResult], parser: ArgParser) -> Void in
runner.collect(results: benchmarks, parser: parser)
}, benchmarksListAction: swiftLauncher.benchmarksListAction) | 71.040816 | 137 | 0.739443 |
ef20849bc3eae67ac11cf148e3007121e61e484f | 811 | //: [Previous](@previous)
//: ## Combinando animações
//: A grande graça desses caras, é podermos combinar as animações, gerando uma combinação de todas as funções de interpolação entre os estados
import UIKit
import PlaygroundSupport
let view = SquareView(frame: .init(x: 0, y: 0, width: 500, height: 800))
let square = view.square
let animation: () -> Void = {
let transform = CGAffineTransform(scaleX: 2, y: 2)
square.transform = transform
.concatenating(.init(rotationAngle: 90))
.concatenating(.init(translationX: 0, y: -200))
square.layer.cornerRadius = 50.0
square.backgroundColor = .blue
}
UIView.animate(withDuration: 2.0, delay: 0.0, options: [.repeat, .autoreverse], animations: animation, completion: nil)
PlaygroundPage.current.liveView = view
//: [Next](@next)
| 35.26087 | 142 | 0.710234 |
2fa8468e7d65aa9f548f2a1178bb3bd723d5b039 | 684 | //
// URL+QueryDict.swift
// ApolloTests
//
// Created by Ellen Shapiro on 10/14/19.
// Copyright © 2019 Apollo GraphQL. All rights reserved.
//
import Foundation
extension URL {
/// Transforms the query items with values into an optional dictionary so it can be subscripted.
var queryItemDictionary: [String: String]? {
return URLComponents(url: self, resolvingAgainstBaseURL: false)?
.queryItems?
.reduce([String: String]()) { dict, queryItem in
guard let value = queryItem.value else {
return dict
}
var updatedDict = dict
updatedDict[queryItem.name] = value
return updatedDict
}
}
}
| 24.428571 | 99 | 0.644737 |
ff72ea018a7074ce5400dafd14084de6fd399155 | 1,564 | //
// RightLargeTableCell.swift
// UICatalog
//
// Created by ichikawa on 2020/10/14.
// Copyright © 2020 ichikawa. All rights reserved.
//
import UIKit
final class LeftLargeTableCell: UITableViewCell {
@IBOutlet private weak var leftLargeItemWidth: NSLayoutConstraint!
@IBOutlet private weak var rightStackViewWidth: NSLayoutConstraint!
@IBOutlet private weak var largeItemView: WEARItemView!
@IBOutlet private weak var smallTopItemView: WEARItemView!
@IBOutlet private weak var smallBottomItemView: WEARItemView!
var smallImageWidth: CGFloat?
var smallImageHeight: CGFloat?
var largeImageWidth: CGFloat?
var largeImageHeight: CGFloat?
override func awakeFromNib() {
super.awakeFromNib()
let frameWidth = UIScreen.main.bounds.width - (8 * 2)
let unitImageWidth = (frameWidth - 16 ) / 3
self.leftLargeItemWidth.constant = unitImageWidth * 2 + 8
self.rightStackViewWidth.constant = unitImageWidth
self.smallImageWidth = unitImageWidth
self.smallImageHeight = smallImageWidth! * 332 / 262
self.largeImageWidth = unitImageWidth * 2 + 8
self.largeImageHeight = self.largeImageWidth! * 332 / 262
self.layoutIfNeeded()
}
func configure(cellId: Int) {
let initalId = cellId * 3 + 1
self.largeItemView.configure(imageId: initalId)
self.smallTopItemView.configure(imageId: initalId + 1)
self.smallBottomItemView.configure(imageId: initalId + 2)
}
}
| 31.918367 | 71 | 0.682864 |
e0cd7d429af23ab50372a6ad50fb41765ec46502 | 3,944 | //
// AcknowViewController.swift
//
// Copyright (c) 2015-2017 Vincent Tourraine (http://www.vtourraine.net)
//
// 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 UIKit
/// Subclass of `UIViewController` that displays a single acknowledgement.
open class AcknowViewController: UIViewController {
/// The main text view.
open var textView: UITextView?
/// The represented acknowledgement.
var acknowledgement: Acknow?
/**
Initializes the `AcknowViewController` instance with an acknowledgement.
- parameter acknowledgement: The represented acknowledgement.
- returns: The new `AcknowViewController` instance.
*/
public init(acknowledgement: Acknow) {
super.init(nibName: nil, bundle: nil)
self.title = acknowledgement.title
self.acknowledgement = acknowledgement
}
/**
Initializes the `AcknowViewController` instance with a coder.
- parameter aDecoder: The archive coder.
- returns: The new `AcknowViewController` instance.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.acknowledgement = Acknow(title: "", text: "", license: nil)
}
// MARK: - View lifecycle
/// Called after the controller's view is loaded into memory.
open override func viewDidLoad() {
super.viewDidLoad()
let textView = UITextView(frame: view.bounds)
textView.alwaysBounceVertical = true
textView.font = UIFont.preferredFont(forTextStyle: .body)
textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
textView.isEditable = false
textView.dataDetectorTypes = .link
view.backgroundColor = UIColor.white
view.addSubview(textView)
self.textView = textView
if #available(iOS 9.0, *) {
textView.translatesAutoresizingMaskIntoConstraints = false
let marginGuide = view.readableContentGuide
NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: marginGuide.topAnchor),
textView.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor),
textView.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor),
textView.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor)])
}
else {
textView.textContainerInset = UIEdgeInsetsMake(12, 10, 12, 10)
}
}
/// Called to notify the view controller that its view has just laid out its subviews.
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Need to set the textView text after the layout is completed, so that the content inset and offset properties can be adjusted automatically.
if let acknowledgement = self.acknowledgement {
textView?.text = acknowledgement.text
}
}
}
| 37.923077 | 150 | 0.700558 |
de4ba317a1c6f628b283c7a92fb601c0e692443f | 851 | // passed
class Solution {
let left: Set = Set("([{")
let right: Set = Set(")]}")
func matches(_ l: Character, _ r:Character) -> Bool {
return (l == "(" && r == ")") ||
(l == "[" && r == "]") ||
(l == "{" && r == "}")
}
func isValid(_ s: String) -> Bool {
var pending = [Character]()
for c in s {
if left.contains(c) {
pending.append(c)
} else if right.contains(c) {
if let l = pending.popLast() {
if !matches(l, c) { // 左右匹配
return false
}
} else { // 多余的右括号
return false
}
}
}
return pending.isEmpty // 多余的左括号
}
}
// test
print(Solution().isValid("[][]{}"))
| 25.029412 | 57 | 0.364277 |
7695d43ea5cf85d09cfb68f74e21d1cc2696a6ea | 2,256 | //
// SwiftCrystal+OSX.swift
// SwiftCrystal
//
// Created by Jun Narumi on 2016/09/05.
// Copyright © 2016年 zenithgear. All rights reserved.
//
import Foundation
extension SwiftCrystal {
func bitmapImageRep(size:CGSize) -> NSBitmapImageRep {
return bitmapImageRep_SCNView(size)
}
func bitmapImageRep_CGLContext(size:CGSize) -> NSBitmapImageRep {
let renderer = OffscreenRendererLegacy();
// let renderer = OffscreenRenderer();
renderer.scene = simpleScene
let image = renderer.imageWithSize(size)
let tiff = image.TIFFRepresentation
let rep = NSBitmapImageRep.init(data: tiff!)
return rep ?? NSBitmapImageRep()
}
func bitmapImageRep_SCNView(size:CGSize) -> NSBitmapImageRep {
let frame = CGRect(origin: CGPoint(), size: size)
// let frame = CGRect(x: 0, y: 0, width: size.width*0.8, height: size.height)
let sceneView = SCNView.init(frame: frame, options: [SCNPreferredRenderingAPIKey:(SCNRenderingAPI.OpenGLLegacy).rawValue as NSNumber])
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.0)
sceneView.autoenablesDefaultLighting = true
sceneView.allowsCameraControl = true
sceneView.backgroundColor = Color.redColor()
sceneView.scene = simpleScene
SCNTransaction.commit()
SCNTransaction.flush()
let image = sceneView.snapshot()
let tiff = image.TIFFRepresentation
let rep = NSBitmapImageRep.init(data: tiff!)
return rep ?? NSBitmapImageRep()
}
var collada: String {
let builder = CrystalCollada()
let latticeColor = symopHasProblem ? SCNVector4(1,0,0,1) : SCNVector4(0.5,0.5,0.5,1)
builder.addLines( cell.latticeLineVertices, emission: latticeColor, diffuse: SCNVector4(0,0,0,1) )
builder.addLines( bondLineVertices, emission: SCNVector4(0.5,0.5,0.5,1), diffuse: SCNVector4(0.5,0.5,0.5,1) )
for (size,posision,color) in atomTuples {
builder.addSphere(size*radiiSize, pos: posision, color: color)
}
return builder.collada
}
var colladaData: NSData? {
return (collada as NSString).dataUsingEncoding(NSUTF8StringEncoding)
}
}
| 40.285714 | 142 | 0.668883 |
7576365f1c8afc54abb3ff34fb1c756ed44ba5f1 | 276 | import Delta
struct ClearCompletedTodosAction: DynamicActionType {
func call() {
let todos = store.completedTodos.first()?.value ?? []
todos.forEach {
todo in
store.dispatch(DeleteTodoAction(todo: todo))
}
}
}
| 21.230769 | 61 | 0.576087 |
28da2149403e277ccbed1bb1df36bc68146be8bf | 968 | //
// File.swift
//
//
// Created by Liam Knowles on 7/14/20.
//
import Foundation
enum RecipeDataStoreError: Error {
case noIngredient
}
class RecipeDataStore: DataStore {
var recipes: [Recipe] = [
]
let ingredientDataStore: IngredientDataStore
init(ingredientDataStore: IngredientDataStore) {
self.ingredientDataStore = ingredientDataStore
}
func generateRecipe() throws -> Recipe {
var ingredients = [Ingredient]()
var numberOfIngredients = (1 ... 10).randomElement()!
for _ in (0 ..< numberOfIngredients) {
guard let ingredient = ingredientDataStore.ingredients.randomElement() else {
throw RecipeDataStoreError.noIngredient
}
ingredients.append(ingredient)
}
let recipe = Recipe(name: "Liam's Recipe", steps: [], ingredients: ingredients)
recipes.append(recipe)
return recipe
}
}
| 24.820513 | 89 | 0.621901 |
16068588eb0934fafbc3bfd56cc3fc0993dd4088 | 985 | //
// Repository.swift
// GithubCLI
//
// Created by Yusuke Kita on 10/3/15.
// Copyright © 2015 kitasuke. All rights reserved.
//
import Foundation
import Himotoki
public struct Repository: Decodable {
let id: Int
let name: String
let fullName: String
let description: String
let language: String?
let watchersCount: Int
let stargazersCount: Int
let forksCount: Int
let url: String
let htmlURL: String
let createdAt: String
let updatedAt: String
public static func decode(e: Extractor) throws -> Repository {
return try build(self.init)(
e <| "id",
e <| "name",
e <| "full_name",
e <| "description",
e <|? "language",
e <| "watchers_count",
e <| "stargazers_count",
e <| "forks_count",
e <| "url",
e <| "html_url",
e <| "created_at",
e <| "updated_at"
)
}
} | 23.452381 | 66 | 0.540102 |
728fa4c0e84782e5db7f733371cf3a4acc16f52b | 4,219 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import CDispatch
public struct DispatchWorkItemFlags : OptionSet, RawRepresentable {
public let rawValue: UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let barrier = DispatchWorkItemFlags(rawValue: 0x1)
@available(OSX 10.10, iOS 8.0, *)
public static let detached = DispatchWorkItemFlags(rawValue: 0x2)
@available(OSX 10.10, iOS 8.0, *)
public static let assignCurrentContext = DispatchWorkItemFlags(rawValue: 0x4)
@available(OSX 10.10, iOS 8.0, *)
public static let noQoS = DispatchWorkItemFlags(rawValue: 0x8)
@available(OSX 10.10, iOS 8.0, *)
public static let inheritQoS = DispatchWorkItemFlags(rawValue: 0x10)
@available(OSX 10.10, iOS 8.0, *)
public static let enforceQoS = DispatchWorkItemFlags(rawValue: 0x20)
}
@available(OSX 10.10, iOS 8.0, *)
public class DispatchWorkItem {
internal var _block: _DispatchBlock
internal var _group: DispatchGroup?
// Temporary for swift-corelibs-foundation
@available(*, deprecated, renamed: "DispatchWorkItem(qos:flags:block:)")
public convenience init(group: DispatchGroup, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], block: @escaping @convention(block) () -> ()) {
self.init(qos: qos, flags: flags, block: block)
}
public init(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], block: @escaping @convention(block) () -> ()) {
_block = dispatch_block_create_with_qos_class(dispatch_block_flags_t(flags.rawValue),
qos.qosClass.rawValue.rawValue, Int32(qos.relativePriority), block)
}
// Used by DispatchQueue.synchronously<T> to provide a @noescape path through
// dispatch_block_t, as we know the lifetime of the block in question.
internal init(flags: DispatchWorkItemFlags = [], noescapeBlock: @noescape () -> ()) {
_block = _swift_dispatch_block_create_noescape(dispatch_block_flags_t(flags.rawValue), noescapeBlock)
}
public func perform() {
_block()
}
public func wait() {
_ = dispatch_block_wait(_block, DispatchTime.distantFuture.rawValue)
}
public func wait(timeout: DispatchTime) -> DispatchTimeoutResult {
return dispatch_block_wait(_block, timeout.rawValue) == 0 ? .success : .timedOut
}
public func wait(wallTimeout: DispatchWallTime) -> DispatchTimeoutResult {
return dispatch_block_wait(_block, wallTimeout.rawValue) == 0 ? .success : .timedOut
}
public func notify(
qos: DispatchQoS = .unspecified,
flags: DispatchWorkItemFlags = [],
queue: DispatchQueue,
execute: @escaping @convention(block) () -> ())
{
if qos != .unspecified || !flags.isEmpty {
let item = DispatchWorkItem(qos: qos, flags: flags, block: execute)
dispatch_block_notify(_block, queue.__wrapped, item._block)
} else {
dispatch_block_notify(_block, queue.__wrapped, execute)
}
}
public func notify(queue: DispatchQueue, execute: DispatchWorkItem) {
dispatch_block_notify(_block, queue.__wrapped, execute._block)
}
public func cancel() {
dispatch_block_cancel(_block)
}
public var isCancelled: Bool {
return dispatch_block_testcancel(_block) != 0
}
}
/// The dispatch_block_t typealias is different from usual closures in that it
/// uses @convention(block). This is to avoid unnecessary bridging between
/// C blocks and Swift closures, which interferes with dispatch APIs that depend
/// on the referential identity of a block. Particularly, dispatch_block_create.
internal typealias _DispatchBlock = @convention(block) () -> Void
internal typealias dispatch_block_t = @convention(block) () -> Void
@_silgen_name("_swift_dispatch_block_create_noescape")
internal func _swift_dispatch_block_create_noescape(_ flags: dispatch_block_flags_t, _ block: @noescape () -> ()) -> _DispatchBlock
| 37.669643 | 162 | 0.722683 |
d9fffad74e273d58c696d618aa6d688b386518ab | 529 | //
// TimedInterval.swift
// StravaZpot
//
// Created by Tomás Ruiz López on 24/10/16.
// Copyright © 2016 SweetZpot AS. All rights reserved.
//
import Foundation
public struct TimedInterval<T : Equatable> {
public let min : T
public let max : T
public let time : Int
}
extension TimedInterval : Equatable {}
public func ==<T>(lhs : TimedInterval<T>, rhs : TimedInterval<T>) -> Bool where T : Equatable {
return lhs.min == rhs.min &&
lhs.max == rhs.max &&
lhs.time == rhs.time
}
| 22.041667 | 95 | 0.627599 |
146c9b7ef6ae59f3a44610018eac9fce7bf586ad | 4,200 | //
// highlight.swift
// qlplayground
//
// Created by 野村 憲男 on 9/19/15.
//
// Copyright (c) 2015 Norio Nomura
//
// 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 class Highlight: NSObject {
/// read bundle
static let bundle = NSBundle(forClass: Highlight.self)
static let script = bundle.URLForResource("highlight.pack", withExtension: "js", subdirectory: "highlight")
.flatMap { try? String(contentsOfURL: $0)} ?? ""
static var css: String {
let style = NSUserDefaults(suiteName: bundle.bundleIdentifier)?.stringForKey("HighlightStyle") ?? "xcode"
return bundle.URLForResource(style, withExtension: "css", subdirectory: "highlight/styles")
.flatMap { try? String(contentsOfURL: $0)} ?? ""
}
/// create NSData from url pointing .swift or .playground
public static func data(URL url: NSURL) -> NSData? {
let fm = NSFileManager.defaultManager()
var isDirectory: ObjCBool = false
guard url.fileURL && url.path.map({ fm.fileExistsAtPath($0, isDirectory: &isDirectory) }) ?? false else {
return nil
}
func escapeHTML(string: String) -> String {
return NSXMLNode.textWithStringValue(string).XMLString
}
/// read contents.swift
let codes: String
if isDirectory {
let keys = [NSURLTypeIdentifierKey]
func isSwiftSourceURL(url: NSURL) -> Bool {
if let typeIdentifier = try? url.resourceValuesForKeys(keys)[NSURLTypeIdentifierKey] as? String
where typeIdentifier == "public.swift-source" {
return true
} else {
return false
}
}
let enumerator = fm.enumeratorAtURL(url, includingPropertiesForKeys: keys, options: [], errorHandler: nil)
let swiftSources = anyGenerator { enumerator?.nextObject() as? NSURL }
.filter(isSwiftSourceURL)
let length = url.path!.characters.count
func subPath(url: NSURL) -> String {
return String(url.path!.characters.dropFirst(length))
}
codes = swiftSources.flatMap {
guard let content = try? String(contentsOfURL: $0) else { return nil }
return "<code>\(subPath($0))</code><pre><code class='swift'>\(escapeHTML(content))</code></pre>"
}
.joinWithSeparator("<hr>")
} else {
codes = (try? String(contentsOfURL: url))
.map {"<pre><code class='swift'>\(escapeHTML($0))</code></pre>"} ?? ""
}
let html = ["<!DOCTYPE html>",
"<html><meta charset=\"utf-8\" /><head>",
"<style>*{margin:0;padding:0}\(css)</style>",
"<script>\(script)</script>",
"<script>hljs.initHighlightingOnLoad();</script>",
"</head><body class=\"hljs\">\(codes)</body></html>"]
.joinWithSeparator("\n")
return html.dataUsingEncoding(NSUTF8StringEncoding)
}
}
| 43.298969 | 118 | 0.613333 |
90c995b5ae549c298f05670d2595993616604757 | 959 | //
// JapaneseNumberDemo_iOSTests.swift
// JapaneseNumberDemo-iOSTests
//
// Created by Daisuke T on 2019/05/01.
// Copyright © 2019 DaisukeT. All rights reserved.
//
import XCTest
@testable import JapaneseNumberDemo_iOS
class JapaneseNumberDemo_iOSTests: XCTestCase {
override func 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.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.4 | 111 | 0.673618 |
e6aa4d9aee30848656eacb3084afe8148041027a | 8,932 | //
// ProfileViewController.swift
// GetStreamActivityFeed
//
// Created by Alexey Bukhtin on 15/01/2019.
// Copyright © 2019 Stream.io Inc. All rights reserved.
//
import UIKit
import SnapKit
import GetStream
class ProfileViewController: UIViewController, BundledStoryboardLoadable {
static var storyboardName = "Profile"
@IBOutlet weak var backgroundImageView: UIImageView! {
didSet {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.white.withAlphaComponent(0).cgColor, UIColor.white.cgColor]
backgroundImageView.layer.addSublayer(gradientLayer)
gradientLayer.frame = backgroundImageView.bounds
}
}
@IBOutlet weak var avatarView: AvatarView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var followersLabel: UILabel!
@IBOutlet weak var followingLabel: UILabel!
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var headerViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var feedContainerView: UIView!
var builder: ProfileBuilder?
var user: User? {
didSet {
if let user = user, let currentUser = Client.shared.currentUser {
isCurrentUser = user.id == currentUser.id
}
}
}
private(set) var isCurrentUser: Bool = false
private var flatFeedViewController: ActivityFeedViewController?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
loadAvatar(onlyTabBarItem: true)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupTabBarItem()
DispatchQueue.main.async { self.loadAvatar(onlyTabBarItem: true) }
}
override func viewDidLoad() {
super.viewDidLoad()
hideBackButtonTitle()
setupTabBarItem()
updateUser()
setupFlatFeed()
if isCurrentUser {
addEditButton()
} else {
addFollowButton()
refreshUser()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.presentTransparentNavigationBar(animated: false)
flatFeedViewController?.reloadData()
}
private func setupFlatFeed() {
guard let userId = user?.id else {
return
}
let feedId = FeedId.user(with: userId)
flatFeedViewController = builder?.activityFeedBuilder?.activityFeedViewController(feedId: feedId)
guard let flatFeedViewController = flatFeedViewController else {
return
}
add(viewController: flatFeedViewController, to: feedContainerView)
headerView.removeFromSuperview()
flatFeedViewController.tableView.tableHeaderView = headerView
let navigationBarHeight = UIApplication.shared.statusBarFrame.height
+ (navigationController?.navigationBar.frame.height ?? 0)
headerView.snp.makeConstraints { make in
make.top.equalToSuperview().offset(-navigationBarHeight)
make.left.right.equalToSuperview()
make.width.equalToSuperview()
}
headerViewHeightConstraint.constant -= navigationBarHeight
guard isCurrentUser else {
return
}
flatFeedViewController.removeActivityAction = { [weak self, weak flatFeedViewController] activity in
guard let self = self else {
return
}
guard activity.original.isUserReposted else {
flatFeedViewController?.presenter?.remove(activity: activity, self.refresh)
return
}
if let repostReaction = activity.original.userRepostReaction {
flatFeedViewController?.presenter?.reactionPresenter
.remove(reaction: repostReaction, activity: activity) { [weak self] in self?.refresh($0.error) }
}
}
}
private func refresh(_ error: Error?) {
if let error = error {
showErrorAlert(error)
} else {
flatFeedViewController?.reloadData()
}
}
private func setupTabBarItem(image: UIImage? = .userIcon) {
tabBarItem = UITabBarItem(title: "Profile", image: image, tag: 4)
}
func updateUser() {
nameLabel.text = user?.name
followersLabel.text = String(user?.followersCount ?? 0)
followingLabel.text = String(user?.followingCount ?? 0)
loadAvatar()
}
func refreshUser() {
user?.refresh(completion: { [weak self] user in
if let user = user {
self?.user = user
self?.updateUser()
}
})
}
}
// MARK: - Navigation Bar
extension ProfileViewController {
private func addEditButton() {
guard let builder = builder else {
return
}
let button = BarButton(title: "Edit Profile", backgroundColor: Appearance.Color.transparentWhite)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
button.addTap { [weak self] _ in
let viewController = builder.editProfileNavigationController { $0.completion = self?.updateEditedUser }
self?.present(viewController, animated: true)
}
}
private func updateEditedUser(_ user: User) {
avatarView.image = nil
backgroundImageView.image = nil
self.user = user
updateUser()
}
private func addFollowButton() {
guard let flatFeedPresenter = flatFeedViewController?.presenter else {
return
}
let button = BarButton(title: "Follow", backgroundColor: Appearance.Color.blue)
button.setTitle("Updating...", backgroundColor: Appearance.Color.transparentWhite, for: .disabled)
button.setTitle("Following", backgroundColor: Appearance.Color.transparentWhite, for: .selected)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
button.addTap { [weak flatFeedPresenter] in
if let button = $0 as? BarButton,
let feedId = flatFeedPresenter?.flatFeed.feedId,
let userFeed = User.current?.feed {
let isFollowing = button.isSelected
button.isEnabled = false
if isFollowing {
userFeed.unfollow(fromTarget: feedId) {
button.isEnabled = true
button.isSelected = !($0.error == nil)
}
} else {
userFeed.follow(toTarget: feedId) {
button.isEnabled = true
button.isSelected = $0.error == nil
}
}
}
}
// Update the current state.
button.isEnabled = false
User.current?.isFollow(toTarget: flatFeedPresenter.flatFeed.feedId) { [weak self] in
button.isEnabled = true
if let error = $2 {
self?.showErrorAlert(error)
} else {
button.isSelected = $0
}
}
}
}
// MARK: - Avatar
extension ProfileViewController {
private func loadAvatar(onlyTabBarItem: Bool = false) {
user?.loadAvatar { [weak self] image in
guard let self = self else {
return
}
if let image = image {
let avatarWidth = onlyTabBarItem ? 0 : self.avatarView.bounds.width
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
self?.updateAvatar(image: image, avatarWidth: avatarWidth, onlyTabBarItem: onlyTabBarItem)
}
} else if !onlyTabBarItem {
self.avatarView.image = nil
self.backgroundImageView.image = nil
self.tabBarItem = UITabBarItem(title: "Profile", image: .userIcon, tag: 4)
}
}
}
private func updateAvatar(image: UIImage, avatarWidth: CGFloat, onlyTabBarItem: Bool) {
let avatarImage = image.square(with: avatarWidth)
let tabBarImage = image.square(with: 25).rounded.transparent(alpha: 0.8).original
DispatchQueue.main.async {
self.tabBarItem = UITabBarItem(title: "Profile", image: tabBarImage, tag: 4)
if !onlyTabBarItem {
self.avatarView.image = avatarImage
self.backgroundImageView.image = image
}
}
}
}
| 33.70566 | 116 | 0.58867 |
38127e2162453d6d7aeedf1971efe84365212851 | 6,248 | //
// HSDrawLayerProtocol.swift
// HSStockChartDemo
//
// Created by Hanson on 2017/2/28.
// Copyright © 2017年 hanson. All rights reserved.
//
import Foundation
import UIKit
protocol HSDrawLayerProtocol {
var theme: HSStockChartTheme { get }
func getTextLayer(text: String, foregroundColor: UIColor, backgroundColor: UIColor, frame: CGRect) -> CATextLayer
func getCrossLineLayer(frame: CGRect, pricePoint: CGPoint, volumePoint: CGPoint, model: AnyObject?) -> CAShapeLayer
}
extension HSDrawLayerProtocol {
var theme: HSStockChartTheme {
return HSStockChartTheme()
}
/// 获取字符图层
func getTextLayer(text: String, foregroundColor: UIColor, backgroundColor: UIColor, frame: CGRect) -> CATextLayer {
let textLayer = CATextLayer()
textLayer.frame = frame
textLayer.string = text
textLayer.fontSize = 10
textLayer.foregroundColor = foregroundColor.cgColor
textLayer.backgroundColor = backgroundColor.cgColor
textLayer.alignmentMode = kCAAlignmentCenter
textLayer.contentsScale = UIScreen.main.scale
return textLayer
}
/// 获取纵轴的标签图层
func getYAxisMarkLayer(frame: CGRect, text: String, y: CGFloat, isLeft: Bool) -> CATextLayer {
let textSize = theme.getTextSize(text: text)
let yAxisLabelEdgeInset: CGFloat = 5
var labelX: CGFloat = 0
if isLeft {
labelX = yAxisLabelEdgeInset
} else {
labelX = frame.width - textSize.width - yAxisLabelEdgeInset
}
let labelY: CGFloat = y - textSize.height / 2.0
let yMarkLayer = getTextLayer(text: text, foregroundColor: theme.textColor, backgroundColor: UIColor.clear, frame: CGRect(x: labelX, y: labelY, width: textSize.width, height: textSize.height))
return yMarkLayer
}
/// 获取长按显示的十字线及其标签图层
func getCrossLineLayer(frame: CGRect, pricePoint: CGPoint, volumePoint: CGPoint, model: AnyObject?) -> CAShapeLayer {
let highlightLayer = CAShapeLayer()
let corssLineLayer = CAShapeLayer()
var volMarkLayer = CATextLayer()
var yAxisMarkLayer = CATextLayer()
var bottomMarkLayer = CATextLayer()
var bottomMarkerString = ""
var yAxisMarkString = ""
var volumeMarkerString = ""
guard let model = model else { return highlightLayer }
if model.isKind(of: HSKLineModel.self) {
let entity = model as! HSKLineModel
yAxisMarkString = entity.close.toStringWithFormat(".2")
bottomMarkerString = entity.date.toDate("yyyyMMddHHmmss")?.toString("MM-dd") ?? ""
volumeMarkerString = entity.volume.toStringWithFormat(".2")
} else if model.isKind(of: HSTimeLineModel.self){
let entity = model as! HSTimeLineModel
yAxisMarkString = entity.price.toStringWithFormat(".2")
bottomMarkerString = entity.time
volumeMarkerString = entity.volume.toStringWithFormat(".2")
} else{
return highlightLayer
}
let linePath = UIBezierPath()
// 竖线
linePath.move(to: CGPoint(x: pricePoint.x, y: 0))
linePath.addLine(to: CGPoint(x: pricePoint.x, y: frame.height))
// 横线
linePath.move(to: CGPoint(x: frame.minX, y: pricePoint.y))
linePath.addLine(to: CGPoint(x: frame.maxX, y: pricePoint.y))
// 标记交易量的横线
linePath.move(to: CGPoint(x: frame.minX, y: volumePoint.y))
linePath.addLine(to: CGPoint(x: frame.maxX, y: volumePoint.y))
// 交叉点
//linePath.addArc(withCenter: pricePoint, radius: 3, startAngle: 0, endAngle: 180, clockwise: true)
corssLineLayer.lineWidth = theme.lineWidth
corssLineLayer.strokeColor = theme.crossLineColor.cgColor
corssLineLayer.fillColor = theme.crossLineColor.cgColor
corssLineLayer.path = linePath.cgPath
// 标记标签大小
let yAxisMarkSize = theme.getTextSize(text: yAxisMarkString)
let volMarkSize = theme.getTextSize(text: volumeMarkerString)
let bottomMarkSize = theme.getTextSize(text: bottomMarkerString)
var labelX: CGFloat = 0
var labelY: CGFloat = 0
// 纵坐标标签
if pricePoint.x > frame.width / 2 {
labelX = frame.minX
} else {
labelX = frame.maxX - yAxisMarkSize.width
}
labelY = pricePoint.y - yAxisMarkSize.height / 2.0
yAxisMarkLayer = getTextLayer(text: yAxisMarkString, foregroundColor: UIColor.white, backgroundColor: theme.textColor, frame: CGRect(x: labelX, y: labelY, width: yAxisMarkSize.width, height: yAxisMarkSize.height))
// 底部时间标签
let maxX = frame.maxX - bottomMarkSize.width
labelX = pricePoint.x - bottomMarkSize.width / 2.0
labelY = frame.height * theme.uperChartHeightScale
if labelX > maxX {
labelX = frame.maxX - bottomMarkSize.width
} else if labelX < frame.minX {
labelX = frame.minX
}
bottomMarkLayer = getTextLayer(text: bottomMarkerString, foregroundColor: UIColor.white, backgroundColor: theme.textColor, frame: CGRect(x: labelX, y: labelY, width: bottomMarkSize.width, height: bottomMarkSize.height))
// 交易量右标签
if pricePoint.x > frame.width / 2 {
labelX = frame.minX
} else {
labelX = frame.maxX - volMarkSize.width
}
let maxY = frame.maxY - volMarkSize.height
labelY = volumePoint.y - volMarkSize.height / 2.0
labelY = labelY > maxY ? maxY : labelY
volMarkLayer = getTextLayer(text: volumeMarkerString, foregroundColor: UIColor.white, backgroundColor: theme.textColor, frame: CGRect(x: labelX, y: labelY, width: volMarkSize.width, height: volMarkSize.height))
highlightLayer.addSublayer(corssLineLayer)
highlightLayer.addSublayer(yAxisMarkLayer)
highlightLayer.addSublayer(bottomMarkLayer)
highlightLayer.addSublayer(volMarkLayer)
return highlightLayer
}
}
| 39.544304 | 227 | 0.636684 |
223bba6e610270d4c8fb29e9e1c5bd7c9f423348 | 53,401 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
import UIKit
// MARK: BadgeFieldDelegate
@available(*, deprecated, renamed: "BadgeFieldDelegate")
public typealias MSBadgeFieldDelegate = BadgeFieldDelegate
@objc(MSFBadgeFieldDelegate)
public protocol BadgeFieldDelegate: AnyObject {
@objc optional func badgeField(_ badgeField: BadgeField, badgeDataSourceForText text: String) -> BadgeViewDataSource
@objc optional func badgeField(_ badgeField: BadgeField, willChangeTextFieldContentWithText newText: String)
@objc optional func badgeFieldDidChangeTextFieldContent(_ badgeField: BadgeField, isPaste: Bool)
@objc optional func badgeField(_ badgeField: BadgeField, shouldBadgeText text: String, forSoftBadgingString badgingString: String) -> Bool
/**
`didAddBadge` and `didDeleteBadge` won't be called in the following case:
add/delete were not triggered by a user action. In this case, handle the consequences of a add/delete after the external class called setupViewWithBadgeDataSources or addBadgeWithDataSource
*/
@objc optional func badgeField(_ badgeField: BadgeField, didAddBadge badge: BadgeView)
@objc optional func badgeField(_ badgeField: BadgeField, didDeleteBadge badge: BadgeView)
/**
`shouldAddBadgeForBadgeDataSource` defaults to true. Called only if the add results from a user action.
*/
@objc optional func badgeField(_ badgeField: BadgeField, shouldAddBadgeForBadgeDataSource badgeDataSource: BadgeViewDataSource) -> Bool
@objc optional func badgeField(_ badgeField: BadgeField, newBadgeForBadgeDataSource badgeDataSource: BadgeViewDataSource) -> BadgeView
@objc optional func badgeField(_ badgeField: BadgeField, newMoreBadgeForBadgeDataSources badgeDataSources: [BadgeViewDataSource]) -> BadgeView
@objc optional func badgeFieldContentHeightDidChange(_ badgeField: BadgeField)
@objc optional func badgeField(_ badgeField: BadgeField, didTapSelectedBadge badge: BadgeView)
@objc optional func badgeField(_ badgeField: BadgeField, shouldDragBadge badge: BadgeView) -> Bool // defaults to true
/**
`destinationBadgeField` is nil if the badge is animated back to its original field.
`newBadge` is nil if the destination field returned false to `badgeField:shouldAddBadgeForBadgeDataSource` when the user dropped the badge.
*/
@objc optional func badgeField(_ originbadgeField: BadgeField, didEndDraggingOriginBadge originBadge: BadgeView, toBadgeField destinationBadgeField: BadgeField?, withNewBadge newBadge: BadgeView?)
@objc optional func badgeFieldShouldBeginEditing(_ badgeField: BadgeField) -> Bool
@objc optional func badgeFieldDidBeginEditing(_ badgeField: BadgeField)
@objc optional func badgeFieldDidEndEditing(_ badgeField: BadgeField)
/**
`badgeFieldShouldReturn` is called only when there's no text in the text field, otherwise `BadgeField` badges the text and doesn't call this.
*/
@objc optional func badgeFieldShouldReturn(_ badgeField: BadgeField) -> Bool
/// This is called to check if we should make badges inactive on textFieldDidEndEditing.
/// If not implemented, the default value assumed is false.
@objc optional func badgeFieldShouldKeepBadgesActiveOnEndEditing(_ badgeField: BadgeField) -> Bool
}
// MARK: - BadgeField Colors
public extension Colors {
struct BadgeField {
public static var background: UIColor = surfacePrimary
public static var label: UIColor = textSecondary
public static var placeholder: UIColor = textSecondary
}
}
// MARK: - BadgeField
@available(*, deprecated, renamed: "BadgeField")
public typealias MSBadgeField = BadgeField
/**
BadgeField is a UIView that acts as a UITextField that can contains badges with enclosed text.
It supports:
* badge selection. Selection leaves the order of pills unchanged.
* badge drag and drop between multiple BadgeFields
* placeholder (hidden when text is not empty) or introduction text (not hidden when text is not empty)
* custom input accessory view
* max number of lines, with custom "+XX" badge to indicate badges that are not displayed
* voiceover and dynamic text sizing
*/
@objc(MSFBadgeField)
open class BadgeField: UIView {
private struct Constants {
static let badgeHeight: CGFloat = 26
static let badgeMarginHorizontal: CGFloat = 5
static let badgeMarginVertical: CGFloat = 5
static let emptyTextFieldString: String = ""
static let dragAndDropMinimumPressDuration: TimeInterval = 0.2
static let dragAndDropScaleAnimationDuration: TimeInterval = 0.3
static let dragAndDropScaleFactor: CGFloat = 1.10
static let dragAndDropPositioningAnimationDuration: TimeInterval = 0.2
static let labelMarginRight: CGFloat = 5
static let textStyleFont: UIFont = TextStyle.subhead.font
static let textFieldMinWidth: CGFloat = 100
}
@objc open var label: String = "" {
didSet {
labelView.text = label
updateLabelsVisibility()
textField.accessibilityLabel = label
setNeedsLayout()
}
}
@objc open var placeholder: String = "" {
didSet {
placeholderView.text = placeholder
updateLabelsVisibility()
textField.accessibilityLabel = placeholder
setNeedsLayout()
}
}
/**
The max number of lines on which the badges should be laid out. If badges can't fit in the available number of lines, the textfield will add a `moreBadge` at the end of the last displayed line.
Set `numberOfLines` to 0 to remove any limit for the number of lines.
The default value is 0.
Note: Drag and drop should not be used with text fields that have a `numberOfLines` != 0. The resulting behavior is unknown.
*/
@objc open var numberOfLines: Int = 0 {
didSet {
updateConstrainedBadges()
updateBadgesVisibility()
setNeedsLayout()
}
}
/// Indicates whether or not the badge field is "editable". Note: if `isEditable` is false and in "non-editable" mode, the user CAN select badges but CAN'T add, delete or drag badge views.
@objc open var isEditable: Bool = true {
didSet {
if !isEditable {
resignFirstResponder()
}
textField.isUserInteractionEnabled = isEditable
selectedBadgeTextField.isUserInteractionEnabled = isEditable
}
}
/// `isActive` is a proxy property that is transmitted to all the badge views. Badge views should have their style altered if this is true. But this is the decision of whoever implement a new badge view abstract class. Note that this does not change the touch handling behavior in any way.
@objc open var isActive: Bool = false {
didSet {
badges.forEach { $0.isActive = isActive }
moreBadge?.isActive = isActive
}
}
/// Set `allowsDragAndDrop`to determine whether or not the dragging and dropping of badges between badge fields is allowed.
@objc open var allowsDragAndDrop: Bool = true
/**
"Soft" means that the `badgeField` badges the text only under certain conditions.
It's the delegate's responsibility to define these conditions, via `badgeField(_, shouldBadgeText:, forSoftBadgingString:)`
*/
@objc open var softBadgingCharacters: String = ""
/**
"Hard" means that the `badgeField` badges the text as soon as one of these character is used.
*/
@objc open var hardBadgingCharacters: String = ""
@objc public private(set) var badges: [BadgeView] = []
@objc public var badgeDataSources: [BadgeViewDataSource] { return badges.map { $0.dataSource! } }
@objc public weak var badgeFieldDelegate: BadgeFieldDelegate?
var deviceOrientationIsChanging: Bool {
originalDeviceOrientation != UIDevice.current.orientation
}
private var originalDeviceOrientation: UIDeviceOrientation = UIDevice.current.orientation
private var cachedContentHeight: CGFloat = 0 {
didSet {
if cachedContentHeight != oldValue {
badgeFieldDelegate?.badgeFieldContentHeightDidChange?(self)
invalidateIntrinsicContentSize()
}
}
}
/// Keeps a copy of the original numberOfLines when the text field begins editing
private var originalNumberOfLines: Int = 0
@objc public init() {
super.init(frame: .zero)
backgroundColor = Colors.BadgeField.background
labelView.font = Constants.textStyleFont
labelView.textColor = Colors.BadgeField.label
addSubview(labelView)
placeholderView.font = Constants.textStyleFont
placeholderView.textColor = Colors.BadgeField.placeholder
addSubview(placeholderView)
updateLabelsVisibility()
setupTextField(textField)
resetTextFieldContent()
addSubview(textField)
setupTextField(selectedBadgeTextField)
selectedBadgeTextField.delegate = self
selectedBadgeTextField.frame = .zero
selectedBadgeTextField.text = Constants.emptyTextFieldString
addSubview(selectedBadgeTextField)
setupDraggingWindow()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleBadgeFieldTapped(_:)))
addGestureRecognizer(tapGesture)
textField.addTarget(self, action: #selector(textFieldTextChanged), for: .editingChanged)
textField.addObserver(self, forKeyPath: #keyPath(UITextField.selectedTextRange), options: .new, context: nil)
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(handleOrientationChanged), name: UIDevice.orientationDidChangeNotification, object: nil)
// An accessible container must set isAccessibilityElement to false
isAccessibilityElement = false
}
public required init?(coder aDecoder: NSCoder) {
preconditionFailure("init(coder:) has not been implemented")
}
deinit {
textField.removeObserver(self, forKeyPath: #keyPath(UITextField.selectedTextRange), context: nil)
UIDevice.current.endGeneratingDeviceOrientationNotifications()
}
/**
Sets up the view using the badge data sources.
*/
@objc open func setup(dataSources: [BadgeViewDataSource]) {
for badge in badges {
badge.removeFromSuperview()
}
badges.removeAll()
selectedBadge = nil
resetTextFieldContent()
for dataSource in dataSources {
addBadge(withDataSource: dataSource, updateConstrainedBadges: false)
}
setNeedsLayout()
}
/**
Updates the view using existing data sources. This is a bit of a hack since it's better to assume `BadgeViewDataSource` is immutable, but this is necessary to update badge style without losing the current state.
*/
@objc open func reload() {
badges.forEach { $0.reload() }
setNeedsLayout()
}
private func setupTextField(_ textField: UITextField) {
textField.font = Constants.textStyleFont
textField.autocapitalizationType = .none
textField.autocorrectionType = .no
textField.keyboardType = .emailAddress
textField.delegate = self
}
private func setupDraggingWindow() {
// The dragging window must be on top of any other window (keyboard, status bar etc.)
draggingWindow.windowLevel = UIWindow.Level(rawValue: .greatestFiniteMagnitude)
draggingWindow.backgroundColor = .clear
draggingWindow.isHidden = true
}
// MARK: Layout
open override func layoutSubviews() {
super.layoutSubviews()
// `constrainedBadges` depends on the view width, so we should update it on each width change
updateConstrainedBadges()
let contentHeight = self.contentHeight(forBoundingWidth: bounds.width)
// Give the view controller a chance to relayout itself if necessary
cachedContentHeight = contentHeight
let topMargin = UIScreen.main.middleOrigin(frame.height, containedSizeValue: contentHeight)
labelView.frame = CGRect(x: 0, y: topMargin, width: labelViewWidth, height: Constants.badgeHeight)
var left = labelViewRightOffset
var lineIndex = 0
for (index, badge) in currentBadges.enumerated() {
// Don't layout the dragged badge
if badge == draggedBadge {
continue
}
badge.frame = calculateBadgeFrame(badge: badge, badgeIndex: index, lineIndex: &lineIndex, left: &left, topMargin: topMargin, boundingWidth: bounds.width)
}
let textFieldSize = textField.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
let textFieldHeight = UIScreen.main.roundToDevicePixels(textFieldSize.height)
let textFieldVerticalOffset = UIScreen.main.middleOrigin(Constants.badgeHeight, containedSizeValue: textFieldHeight)
let shouldAppendToCurrentLine = left + Constants.textFieldMinWidth <= frame.width
if !shouldAppendToCurrentLine {
lineIndex += 1
left = 0
}
textField.frame = CGRect(
x: left,
y: topMargin + offsetForLine(at: lineIndex) + textFieldVerticalOffset,
width: frame.width - left,
height: textFieldHeight
)
placeholderView.frame = CGRect(x: 0, y: topMargin, width: frame.width, height: Constants.badgeHeight)
flipSubviewsForRTL()
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: size.width, height: contentHeight(forBoundingWidth: size.width))
}
open override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: contentHeight(forBoundingWidth: frame.width))
}
private func shouldDragBadge(_ badge: BadgeView) -> Bool {
if allowsDragAndDrop {
return badgeFieldDelegate?.badgeField?(self, shouldDragBadge: badge) ?? true
}
return false
}
private func updateConstrainedBadges() {
// Remove previous moreBadge
moreBadge?.removeFromSuperview()
constrainedBadges.removeAll()
// No max number of lines, no need to compute these badges
if !shouldUseConstrainedBadges {
return
}
// Loop on all badges
var left = labelViewRightOffset
var lineIndex = 0
for (index, badge) in badges.enumerated() {
let (shouldBreak, newLeft, newLineIndex) = addNextBadge(badge, badgeIndex: index, currentLeft: left, currentLineIndex: lineIndex)
if shouldBreak {
break
}
left = newLeft
lineIndex = newLineIndex
}
updateBadgesVisibility()
}
private func addNextBadge(_ badge: BadgeView, badgeIndex: Int, currentLeft: CGFloat, currentLineIndex: Int) -> (Bool, CGFloat, Int) {
let isLastDisplayedLine = currentLineIndex == numberOfLines - 1
let isFirstBadge = badgeIndex == 0
let isFirstBadgeOfCurrentLine = isFirstBadge || currentLeft == 0
var moreBadgeOffset: CGFloat = 0
let moreBadges = badges[(badgeIndex + 1)...]
if !moreBadges.isEmpty {
let moreBadgesDataSources = moreBadges.compactMap { $0.dataSource }
let moreBadge = createMoreBadge(withDataSources: moreBadgesDataSources)
moreBadgeOffset = Constants.badgeMarginHorizontal + width(forBadge: moreBadge,
isFirstBadge: false,
isFirstBadgeOfLastDisplayedLine: false,
moreBadgeOffset: 0,
boundingWidth: frame.width)
}
let badgeWidth = width(forBadge: badge,
isFirstBadge: isFirstBadge,
isFirstBadgeOfLastDisplayedLine: isFirstBadgeOfCurrentLine,
moreBadgeOffset: moreBadgeOffset,
boundingWidth: frame.width)
let enoughSpaceAvailable = currentLeft + badgeWidth + moreBadgeOffset <= frame.width
let shouldAppend = isFirstBadgeOfCurrentLine || enoughSpaceAvailable
if !shouldAppend {
if isLastDisplayedLine {
// No space for both badge and "+X" badge: Add "+X+1" badge instead (if needed)
let moreBadges = badges[badgeIndex...]
if !moreBadges.isEmpty {
let moreBadgesDataSources = moreBadges.compactMap { $0.dataSource }
let moreBadge = createMoreBadge(withDataSources: moreBadgesDataSources)
self.moreBadge = moreBadge
constrainedBadges.append(moreBadge)
addSubview(moreBadge)
}
// Stop adding badges (we don't care about returning correct newCurrentLeft and newCurrentLineIndex here)
return (true, 0, 0)
} else {
return addNextBadge(badge, badgeIndex: badgeIndex, currentLeft: 0, currentLineIndex: currentLineIndex + 1)
}
}
// Badge should be appended on current line: append and keep looping on following badges
constrainedBadges.append(badge)
return (false, currentLeft + badgeWidth + Constants.badgeMarginHorizontal, currentLineIndex)
}
private func frameForBadge(_ badgeToInsert: BadgeView, boundingWidth: CGFloat) -> CGRect {
let badges = currentBadges
let contentHeight = self.contentHeight(forBoundingWidth: bounds.width)
let topMargin = UIScreen.main.middleOrigin(frame.height, containedSizeValue: contentHeight)
var left = labelViewRightOffset
var lineIndex = 0
for (index, badge) in badges.enumerated() {
let frame = calculateBadgeFrame(badge: badge, badgeIndex: index, lineIndex: &lineIndex, left: &left, topMargin: topMargin, boundingWidth: boundingWidth)
if badge == badgeToInsert {
return frame
}
}
// Unknown badge label: return the frame that the badge would have if it was added to this field
return calculateBadgeFrame(badge: badgeToInsert, badgeIndex: badges.count, lineIndex: &lineIndex, left: &left, topMargin: topMargin, boundingWidth: boundingWidth)
}
/**
Use this method if you don't know yet which moreBadge should be added, typically if you're computing the badges that should be displayed when a constrained number of lines is set.
*/
private func width(forBadge badge: BadgeView, isFirstBadge: Bool, isFirstBadgeOfLastDisplayedLine: Bool, moreBadgeOffset: CGFloat = -1, boundingWidth: CGFloat) -> CGFloat {
let badgeFittingSize = badge.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
let badgeFittingWidth = UIScreen.main.roundToDevicePixels(badgeFittingSize.width)
var badgeMaxWidth = boundingWidth
// First badge: remove the size taken by the introduction label
if isFirstBadge {
badgeMaxWidth -= labelViewRightOffset
}
// First badge of last displayed line: remove the space taken by the moreBadge
if isFirstBadgeOfLastDisplayedLine {
badgeMaxWidth -= moreBadgeOffset == -1 ? calculateMoreBadgeOffset() : moreBadgeOffset
}
return min(badgeMaxWidth, badgeFittingWidth)
}
private func calculateMoreBadgeOffset() -> CGFloat {
if shouldUseConstrainedBadges, let moreBadge = moreBadge {
let moreBadgeSize = moreBadge.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
let moreBadgeWidth = UIScreen.main.roundToDevicePixels(moreBadgeSize.width)
return moreBadgeWidth + Constants.badgeMarginHorizontal
} else {
return 0
}
}
@objc open func heightThatFits(numberOfLines: Int) -> CGFloat {
// Vertical margin not applicable to top line
let heightForAllLines = CGFloat(numberOfLines) * (Constants.badgeHeight + Constants.badgeMarginVertical)
return heightForAllLines - Constants.badgeMarginVertical
}
private func contentHeight(forBoundingWidth boundingWidth: CGFloat) -> CGFloat {
var left = labelViewRightOffset
var lineIndex = 0
for (index, badge) in currentBadges.enumerated() {
calculateBadgeFrame(badge: badge, badgeIndex: index, lineIndex: &lineIndex, left: &left, topMargin: 0, boundingWidth: bounds.width)
}
let isFirstResponderOrHasTextFieldContent = isFirstResponder || !textFieldContent.isEmpty
if isEditable && isFirstResponderOrHasTextFieldContent && left + Constants.textFieldMinWidth > boundingWidth {
lineIndex += 1
}
let textFieldSize = textField.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
let textFieldHeight = UIScreen.main.roundToDevicePixels(textFieldSize.height)
let contentHeight = heightThatFits(numberOfLines: lineIndex + 1)
return max(textFieldHeight, contentHeight)
}
@discardableResult
private func calculateBadgeFrame(badge: BadgeView, badgeIndex: Int, lineIndex: inout Int, left: inout CGFloat, topMargin: CGFloat, boundingWidth: CGFloat) -> CGRect {
let isFirstBadge = badgeIndex == 0
let isFirstBadgeOfCurrentLine = isFirstBadge || left == 0
let isLastDisplayedLine = shouldUseConstrainedBadges && lineIndex == numberOfLines - 1
let badgeWidth = width(forBadge: badge,
isFirstBadge: isFirstBadge,
isFirstBadgeOfLastDisplayedLine: isFirstBadgeOfCurrentLine && isLastDisplayedLine,
boundingWidth: boundingWidth)
// Not enough space on current line
let enoughSpaceAvailableOnCurrentLine = left + badgeWidth <= frame.width
let shouldAppendToCurrentLine = isFirstBadgeOfCurrentLine || enoughSpaceAvailableOnCurrentLine
if !shouldAppendToCurrentLine {
lineIndex += 1
left = 0
// Badge width may change to accomodate `moreBadge`, recursively layout
return calculateBadgeFrame(badge: badge, badgeIndex: badgeIndex, lineIndex: &lineIndex, left: &left, topMargin: topMargin, boundingWidth: boundingWidth)
}
let badgeFrame = CGRect(x: left, y: topMargin + offsetForLine(at: lineIndex), width: badgeWidth, height: Constants.badgeHeight)
left += badgeWidth + Constants.badgeMarginHorizontal
return badgeFrame
}
private func offsetForLine(at lineIndex: Int) -> CGFloat {
return CGFloat(lineIndex) * (Constants.badgeHeight + Constants.badgeMarginVertical)
}
// MARK: Badges
private var badgingCharacters: String { return softBadgingCharacters + hardBadgingCharacters }
/**
The approach taken to handle the numberOfLines feature is to have a separate set of badges. It might look like this choice implies some code duplication, however this feature is almost only about layout (except the moreBadge). Handling numberOfLines directly in the layout process would lead to even more duplication: layoutSubviews, contentHeightForBoundingWidth and frameForBadge. This approach isolates the complexity of numberOfLines in a single method: updateConstrainedBadges that we have to call in the appropriate places.
*/
private var constrainedBadges: [BadgeView] = []
private var currentBadges: [BadgeView] { return shouldUseConstrainedBadges ? constrainedBadges : badges }
private var shouldUseConstrainedBadges: Bool { return numberOfLines != 0 }
/**
This badge is added to the end of the last displayed line if all the badges don't fit in the numberOfLines. It will look like "+5", for example, to indicate the number of badges that are not being displayed.
*/
private var moreBadge: BadgeView? {
didSet {
if let moreBadge = moreBadge {
moreBadge.delegate = self
moreBadge.isActive = isActive
moreBadge.isUserInteractionEnabled = false
}
}
}
private var selectedBadge: BadgeView? {
didSet {
if selectedBadge == oldValue {
return
}
oldValue?.isSelected = false
selectedBadge?.isSelected = true
}
}
var draggedBadge: BadgeView?
private var draggedBadgeTouchCenterOffset: CGPoint?
private var draggingWindow = UIWindow()
/// Shows all badges when text field starts editing and resorts back to constrained badges (if originalNumberOfLines > 0) when editing ends
private var showAllBadgesForEditing: Bool = false {
didSet {
if showAllBadgesForEditing {
originalNumberOfLines = numberOfLines
}
numberOfLines = showAllBadgesForEditing ? 0 : originalNumberOfLines
}
}
/// Badges the current text field content
@objc open func badgeText() {
badgeText(textFieldContent, force: true)
}
// For performance reasons, addBadges:withDataSources should be used when multiple badges must be added
@objc open func addBadges(withDataSources dataSources: [BadgeViewDataSource]) {
for dataSource in dataSources {
addBadge(withDataSource: dataSource, updateConstrainedBadges: false)
}
updateConstrainedBadges()
}
@objc open func addBadge(withDataSource dataSource: BadgeViewDataSource, fromUserAction: Bool = false, updateConstrainedBadges: Bool = true) {
let badge = createBadge(withDataSource: dataSource)
addBadge(badge)
updateLabelsVisibility()
selectedBadge = nil
if updateConstrainedBadges {
self.updateConstrainedBadges()
}
setNeedsLayout()
if fromUserAction {
badgeFieldDelegate?.badgeField?(self, didAddBadge: badge)
}
}
@objc open func deleteBadges(withDataSource dataSource: BadgeViewDataSource) {
badges.forEach { badge in
if badge.dataSource == dataSource {
deleteBadge(badge, fromUserAction: false, updateConstrainedBadges: false)
}
}
updateConstrainedBadges()
}
@objc open func deleteAllBadges() {
deleteAllBadges(fromUserAction: false)
}
@objc open func selectBadge(_ badge: BadgeView) {
// Do nothing if badge already selected
if selectedBadge == badge {
return
}
selectedBadge = badge
selectedBadgeTextField.becomeFirstResponder()
}
func addBadge(_ badge: BadgeView) {
badge.delegate = self
badge.isActive = isActive
badges.append(badge)
addSubview(badge)
// Configure drag gesture
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(_:)))
longPressGestureRecognizer.minimumPressDuration = Constants.dragAndDropMinimumPressDuration
badge.addGestureRecognizer(longPressGestureRecognizer)
}
@discardableResult
private func badgeText(_ text: String, force forceBadge: Bool) -> Bool {
if text.isEmpty {
return false
}
let badgeStrings = extractBadgeStrings(from: text, badgingCharacters: badgingCharacters, hardBadgingCharacters: hardBadgingCharacters, forceBadge: forceBadge, shouldBadge: { (badgeString, softBadgingString) -> Bool in
return badgeFieldDelegate?.badgeField?(self, shouldBadgeText: badgeString, forSoftBadgingString: softBadgingString) ?? true
})
var didBadge = false
// Add badges
for badgeString in badgeStrings {
// Append badge if needed
if let badgeDataSource = badgeFieldDelegate?.badgeField?(self, badgeDataSourceForText: badgeString) {
if shouldAddBadge(forBadgeDataSource: badgeDataSource) {
addBadge(withDataSource: badgeDataSource, fromUserAction: true, updateConstrainedBadges: true)
}
// Consider that we badge even if the delegate prevented via `shouldAddBadgeForBadgeDataSource`
didBadge = true
}
}
if didBadge {
resetTextFieldContent()
}
setNeedsLayout()
return didBadge
}
private func createBadge(withDataSource dataSource: BadgeViewDataSource) -> BadgeView {
var badge: BadgeView
if let badgeFromDelegate = badgeFieldDelegate?.badgeField?(self, newBadgeForBadgeDataSource: dataSource) {
badge = badgeFromDelegate
} else {
badge = BadgeView(dataSource: dataSource)
}
return badge
}
private func createMoreBadge(withDataSources dataSources: [BadgeViewDataSource]) -> BadgeView {
// If no delegate, fallback to default "+X" moreBadge
var moreBadge: BadgeView
if let moreBadgeFromDelegate = badgeFieldDelegate?.badgeField?(self, newMoreBadgeForBadgeDataSources: dataSources) {
moreBadge = moreBadgeFromDelegate
} else {
moreBadge = BadgeView(dataSource: BadgeViewDataSource(text: "+\(dataSources.count)", style: .default))
}
return moreBadge
}
private func deleteAllBadges(fromUserAction: Bool) {
let badgesCopy = badges
for badge in badgesCopy {
deleteBadge(badge, fromUserAction: fromUserAction, updateConstrainedBadges: false)
}
updateConstrainedBadges()
selectedBadge = nil
}
func deleteBadge(_ badge: BadgeView, fromUserAction: Bool, updateConstrainedBadges: Bool) {
badge.removeFromSuperview()
badges.remove(at: badges.firstIndex(of: badge)!)
if updateConstrainedBadges {
self.updateConstrainedBadges()
}
updateLabelsVisibility()
if fromUserAction {
badgeFieldDelegate?.badgeField?(self, didDeleteBadge: badge)
}
}
private func deleteSelectedBadge(fromUserAction: Bool) {
if let selectedBadge = selectedBadge {
deleteBadge(selectedBadge, fromUserAction: fromUserAction, updateConstrainedBadges: true)
self.selectedBadge = nil
}
}
private func shouldAddBadge(forBadgeDataSource dataSource: BadgeViewDataSource) -> Bool {
return badgeFieldDelegate?.badgeField?(self, shouldAddBadgeForBadgeDataSource: dataSource) ?? true
}
private func updateBadgesVisibility() {
badges.forEach { $0.isHidden = shouldUseConstrainedBadges }
constrainedBadges.forEach { $0.isHidden = !shouldUseConstrainedBadges }
moreBadge?.isHidden = !shouldUseConstrainedBadges
}
// MARK: Text field
@objc open var textFieldContent: String {
return textField.text!.trimmed()
}
@objc open func resetTextFieldContent() {
textField.text = Constants.emptyTextFieldString
}
private let textField = PasteControlTextField()
/**
The approach taken with selectedBadgeTextField is to use an alternate UITextField, invisible to the user, to handle all the actions that are related to the existing badges.
*/
private let selectedBadgeTextField = UITextField()
private var switchingTextFieldResponders: Bool = false
// MARK: Label view and placeholder view
private let labelView = UILabel()
private let placeholderView = UILabel()
private var labelViewRightOffset: CGFloat {
return labelView.isHidden ? 0 : labelViewWidth + Constants.labelMarginRight
}
private var labelViewWidth: CGFloat {
if labelView.isHidden {
return 0
}
let labelSize = labelView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
return UIScreen.main.roundToDevicePixels(labelSize.width)
}
private func updateLabelsVisibility(textFieldContent: String? = nil) {
let textFieldContent = textFieldContent ?? self.textFieldContent
labelView.isHidden = label.isEmpty
placeholderView.isHidden = !labelView.isHidden || !badges.isEmpty || !textFieldContent.isEmpty
setNeedsLayout()
}
// MARK: Gestures
@objc func handleBadgeFieldTapped(_ recognizer: UITapGestureRecognizer) {
let tapPoint = recognizer.location(in: self)
let tappedView = hitTest(tapPoint, with: nil)
if tappedView == self {
selectedBadge = nil
textField.becomeFirstResponder()
}
}
// MARK: UIResponder
@discardableResult
open override func becomeFirstResponder() -> Bool {
return textField.becomeFirstResponder()
}
open override var isFirstResponder: Bool {
return textField.isFirstResponder || selectedBadgeTextField.isFirstResponder
}
@discardableResult
open override func resignFirstResponder() -> Bool {
return textField.resignFirstResponder() || selectedBadgeTextField.resignFirstResponder()
}
// MARK: Observations
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard keyPath == #keyPath(UITextField.selectedTextRange), object as? UITextField == textField else {
return
}
// Invalid change
guard let newSelectedTextRange = change?[NSKeyValueChangeKey.newKey] as? UITextRange else {
return
}
// Prevent selection to be before or to include zero width space
let startTextPositionValue = textField.offset(from: textField.beginningOfDocument, to: newSelectedTextRange.start)
if startTextPositionValue == 0 {
if let afterEmptySpaceTextPosition = textField.position(from: newSelectedTextRange.start, in: .right, offset: 1) {
let afterEmptySpaceTextRange = textField.textRange(from: afterEmptySpaceTextPosition, to: newSelectedTextRange.end)
textField.selectedTextRange = afterEmptySpaceTextRange
}
}
}
@objc func textFieldTextChanged() {
badgeFieldDelegate?.badgeFieldDidChangeTextFieldContent?(self, isPaste: textField.isPaste)
textField.isPaste = false
}
@objc private func handleOrientationChanged() {
// Hack: to avoid properly handling rotations for the dragging window (which is annoying and overkill for this feature), let's just reset the dragging window
resetDraggingWindow()
originalDeviceOrientation = UIDevice.current.orientation
}
// MARK: Accessibility
open override func accessibilityElementCount() -> Int {
var elementsCount = 0
if isIntroductionLabelAccessible() {
elementsCount += 1
}
elementsCount += shouldUseConstrainedBadges ? constrainedBadges.count : badges.count
// counting the trailing text field used to add more badges
elementsCount += 1
return elementsCount
}
open override func accessibilityElement(at index: Int) -> Any? {
if isIntroductionLabelAccessible() && index == 0 {
return labelView
}
let offsetIndex = isIntroductionLabelAccessible() ? index - 1 : index
let activeBadges = shouldUseConstrainedBadges ? constrainedBadges : badges
if offsetIndex < activeBadges.count {
return activeBadges[offsetIndex]
}
return textField
}
open override func index(ofAccessibilityElement element: Any) -> Int {
if element as? UILabel == labelView {
return 0
}
let activeBadges = shouldUseConstrainedBadges ? constrainedBadges : badges
if let badge = element as? BadgeView, let index = activeBadges.firstIndex(of: badge) {
return isIntroductionLabelAccessible() ? index + 1 : index
}
return accessibilityElementCount() - 1
}
private func isIntroductionLabelAccessible() -> Bool {
// No badge: introduction will be read as part of the text field
if badges.isEmpty {
return false
}
// No introduction
if labelView.isHidden || label.isEmpty {
return false
}
return true
}
@objc public func voiceOverFocusOnTextFieldAndAnnounce(_ announcement: String?) {
guard let announcement = announcement, !announcement.isEmpty else {
UIAccessibility.post(notification: .screenChanged, argument: textField)
return
}
let previousAccessibilityLabel = textField.accessibilityLabel
// Update the accessibilityLabel to include the desired announcement
textField.accessibilityLabel = "\(announcement). \(previousAccessibilityLabel ?? "")"
UIAccessibility.post(notification: .screenChanged, argument: textField)
// Reset the accessibility to the proper label
// Allow the label to get reset on a delay so the notification has time to fire before it changes
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in
self?.textField.accessibilityLabel = previousAccessibilityLabel
}
}
// MARK: Drag and drop
@objc private func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) {
// Invalid window (happens when the compose screen is not on screen)
guard let containingWindow = window else {
return
}
// Was not first responder, check if we should begin editing
if !isFirstResponder && badgeFieldDelegate?.badgeFieldShouldBeginEditing?(self) == false {
cancelRunningGesture(gesture)
return
}
let draggedBadge = gesture.view as! BadgeView
switch gesture.state {
case .began:
// Already dragging another badge: cancel this new gesture
if !draggingWindow.isHidden {
cancelRunningGesture(gesture)
return
}
// Select badge
selectBadge(draggedBadge)
// Not editable: cancel running gesture
if !isEditable {
cancelRunningGesture(gesture)
return
}
// Drag and drop disabled: cancel running gesture
if !shouldDragBadge(draggedBadge) {
cancelRunningGesture(gesture)
return
}
// Start dragging
startDraggingBadge(draggedBadge, gestureRecognizer: gesture)
case .changed:
// Change draggedBadge to position of drag
let position = gesture.location(in: containingWindow)
let centerOffset = draggedBadgeTouchCenterOffset ?? .zero
draggedBadge.center = CGPoint(x: position.x - centerOffset.x, y: position.y - centerOffset.y)
case .ended:
// Find field under gesture end location
let hitBadgeField: BadgeField?
if let hitView = containingWindow.hitTest(gesture.location(in: containingWindow), with: nil) {
hitBadgeField = hitView as? BadgeField ?? hitView.findSuperview(of: BadgeField.self) as? BadgeField
} else {
hitBadgeField = nil
}
// Animate to hovered field or hovered view is not a field or is the original field so animate badge back to origin
if let hoveredBadgeField = hitBadgeField, hoveredBadgeField != self {
animateDraggedBadgeToBadgeField(hoveredBadgeField)
} else {
moveDraggedBadgeBackToOriginalPosition(animated: true)
}
default:
// Cancelled or failed
moveDraggedBadgeBackToOriginalPosition(animated: false)
}
}
private func startDraggingBadge(_ badge: BadgeView, gestureRecognizer: UIGestureRecognizer) {
guard let containingWindow = window else {
return
}
// Already dragging badge
if draggedBadge == badge {
return
}
draggedBadge = badge
// Dragging badge offset
let touchLocation = gestureRecognizer.location(in: badge)
draggedBadgeTouchCenterOffset = CGPoint(x: round(touchLocation.x - badge.frame.width / 2), y: round(touchLocation.y - badge.frame.height / 2))
// Dragging window becomes front window
draggingWindow.isHidden = false
// Move dragged badge to main window
draggedBadge!.frame = convert(draggedBadge!.frame, to: containingWindow)
draggingWindow.addSubview(draggedBadge!)
// Animate scale
UIView.animate(withDuration: Constants.dragAndDropScaleAnimationDuration) {
self.draggedBadge!.layer.transform = CATransform3DMakeScale(Constants.dragAndDropScaleFactor, Constants.dragAndDropScaleFactor, 1)
}
}
private func moveDraggedBadgeBackToOriginalPosition(animated: Bool) {
// Invalid window (happens when the compose screen is not on screen)
guard let containingWindow = window else {
return
}
// "Cache" dragged badge (because we reset it below but we still need pointer to it)
guard let draggedBadge = draggedBadge else {
return
}
// Compute original position
let destinationFrameInSelf = frameForBadge(draggedBadge, boundingWidth: frame.width)
let destinationFrameInWindow = convert(destinationFrameInSelf, to: containingWindow)
// Move to original position
let moveBadgeToOriginalPosition = {
draggedBadge.layer.transform = CATransform3DIdentity
draggedBadge.frame = destinationFrameInWindow
}
// Move to original field
let moveBadgeToOriginalTextField = {
self.addSubview(draggedBadge)
self.draggedBadge = nil
self.setNeedsLayout()
}
if animated {
UIView.animate(withDuration: Constants.dragAndDropPositioningAnimationDuration, delay: 0.0, options: .beginFromCurrentState, animations: {
moveBadgeToOriginalPosition()
}, completion: { _ in
moveBadgeToOriginalTextField()
// Reset dragging window: need to execute this after a delay to avoid blinking
self.perform(#selector(self.hideDraggingWindow), with: nil, afterDelay: 0.1)
self.badgeFieldDelegate?.badgeField?(self, didEndDraggingOriginBadge: draggedBadge, toBadgeField: self, withNewBadge: nil)
})
} else {
moveBadgeToOriginalPosition()
moveBadgeToOriginalTextField()
hideDraggingWindow()
badgeFieldDelegate?.badgeField?(self, didEndDraggingOriginBadge: draggedBadge, toBadgeField: self, withNewBadge: nil)
}
}
func animateDraggedBadgeToBadgeField(_ destinationBadgeField: BadgeField) {
guard let containingWindow = window else {
cancelBadgeDraggingIfNeeded()
return
}
// "Cache" dragged badge (because we reset it below but we still need pointer to it)
guard let draggedBadge = draggedBadge else {
cancelBadgeDraggingIfNeeded()
return
}
// Compute destination position
let destinationFrameInHoveredBadgeField = destinationBadgeField.frameForBadge(draggedBadge, boundingWidth: destinationBadgeField.frame.width)
let destinationFrameInWindow = destinationBadgeField.convert(destinationFrameInHoveredBadgeField, to: containingWindow)
// Animate to destination position
UIView.animate(withDuration: Constants.dragAndDropPositioningAnimationDuration, delay: 0.0, options: .beginFromCurrentState, animations: {
draggedBadge.layer.transform = CATransform3DIdentity
draggedBadge.frame = destinationFrameInWindow
}, completion: { _ in
// Update destination field
let newlyCreatedBadge: BadgeView? = {
guard let dataSource = draggedBadge.dataSource, destinationBadgeField.shouldAddBadge(forBadgeDataSource: dataSource) else {
return nil
}
destinationBadgeField.addBadge(withDataSource: dataSource, fromUserAction: true, updateConstrainedBadges: true)
let lastBadge = destinationBadgeField.badges.last!
destinationBadgeField.selectBadge(lastBadge)
return lastBadge
}()
// Update origin field
self.deleteBadge(draggedBadge, fromUserAction: true, updateConstrainedBadges: true)
self.selectedBadge = nil
self.updateLabelsVisibility()
draggedBadge.removeFromSuperview()
self.draggedBadge = nil
self.setNeedsLayout()
// Reset dragging window: need to execute this after a delay to avoid blinking
self.perform(#selector(self.hideDraggingWindow), with: nil, afterDelay: 0.1)
self.badgeFieldDelegate?.badgeField?(self, didEndDraggingOriginBadge: draggedBadge, toBadgeField: destinationBadgeField, withNewBadge: newlyCreatedBadge)
})
}
@objc private func hideDraggingWindow() {
draggingWindow.isHidden = true
}
private func cancelRunningGesture(_ gesture: UIGestureRecognizer) {
// Doing this will deliver a Failed state on the next gesture update. This is Apple's recommended way.
gesture.isEnabled = false
gesture.isEnabled = true
}
func cancelBadgeDraggingIfNeeded() {
if draggedBadge == nil {
return
}
// Animate back to origin
moveDraggedBadgeBackToOriginalPosition(animated: false)
}
private func resetDraggingWindow() {
guard let containingWindow = window else {
return
}
cancelBadgeDraggingIfNeeded()
// Reinstanciate a window with fresh orientation
draggingWindow = UIWindow()
draggingWindow.frame = containingWindow.frame
setupDraggingWindow()
}
}
// MARK: - BadgeField: BadgeViewDelegate
extension BadgeField: BadgeViewDelegate {
public func didSelectBadge(_ badge: BadgeView) {
selectBadge(badge)
}
public func didTapSelectedBadge(_ badge: BadgeView) {
badgeFieldDelegate?.badgeField?(self, didTapSelectedBadge: badge)
}
}
// MARK: - BadgeField: UITextFieldDelegate
extension BadgeField: UITextFieldDelegate {
// The switchingTextFieldResponders logic relies on the fact that when we're switching between 2 text fields A -> B, the order of the callbacks are
// textFieldShouldBeginEditing called for B
// textFieldDidEndEditing called for A
// textFieldDidBeginEditing called for B
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if !isEditable {
return false
}
// No text field was selected before, check if we should begin editing
if textField == selectedBadgeTextField && !self.textField.isFirstResponder ||
textField == self.textField && !selectedBadgeTextField.isFirstResponder {
if badgeFieldDelegate?.badgeFieldShouldBeginEditing?(self) == false {
// Deselect in case this was triggered by a select
selectedBadge = nil
return false
}
}
switchingTextFieldResponders = true
return true
}
public func textFieldDidBeginEditing(_ textField: UITextField) {
showAllBadgesForEditing = true
switchingTextFieldResponders = false
badgeFieldDelegate?.badgeFieldDidBeginEditing?(self)
isActive = true
}
public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
// Don't end editing on orientation change
return !deviceOrientationIsChanging
}
public func textFieldDidEndEditing(_ textField: UITextField) {
if textField == selectedBadgeTextField {
selectedBadge = nil
}
if !switchingTextFieldResponders {
badgeText()
updateLabelsVisibility()
badgeFieldDelegate?.badgeFieldDidEndEditing?(self)
}
let shouldKeepBadgesActiveOnEndEditing = badgeFieldDelegate?.badgeFieldShouldKeepBadgesActiveOnEndEditing?(self) ?? false
showAllBadgesForEditing = shouldKeepBadgesActiveOnEndEditing
isActive = shouldKeepBadgesActiveOnEndEditing
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.textField {
if let text = textField.text, text.trimmed().isEmpty {
let shouldReturn = badgeFieldDelegate?.badgeFieldShouldReturn?(self) ?? true
if shouldReturn {
resignFirstResponder()
}
return false
}
badgeText()
return false
}
if textField == selectedBadgeTextField {
deleteSelectedBadge(fromUserAction: true)
self.textField.becomeFirstResponder()
return true
}
return true
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == selectedBadgeTextField {
deleteSelectedBadge(fromUserAction: true)
// Insert the new char at beginning of text field
if let formerTextFieldText = self.textField.text {
let newTextFieldText = NSMutableString(string: formerTextFieldText)
newTextFieldText.insert(string, at: 1)
self.textField.text = newTextFieldText as String
badgeFieldDelegate?.badgeField?(self, willChangeTextFieldContentWithText: self.textField.text!.trimmed())
}
updateLabelsVisibility()
self.textField.becomeFirstResponder()
return false
}
if textField == self.textField {
guard let textFieldText = textField.text else {
return true
}
let newString = (textFieldText as NSString).replacingCharacters(in: range, with: string)
// Badging character detected
let badgingCharactersSet = CharacterSet(charactersIn: badgingCharacters)
if let range = newString.rangeOfCharacter(from: badgingCharactersSet), !range.isEmpty {
let didBadge = badgeText(newString, force: false)
if !didBadge {
// Placeholder
updateLabelsVisibility(textFieldContent: newString.trimmed())
badgeFieldDelegate?.badgeField?(self, willChangeTextFieldContentWithText: newString.trimmed())
}
return !didBadge
}
updateLabelsVisibility(textFieldContent: newString.trimmed())
// Handle delete key
if string.isEmpty {
// Delete on selected text: delete selection
if textField.selectedTextRange?.isEmpty == false {
badgeFieldDelegate?.badgeField?(self, willChangeTextFieldContentWithText: newString.trimmed())
return true
}
// Delete backward on visible character: delete character
let textPositionValue = textField.offset(from: textField.beginningOfDocument, to: textField.selectedTextRange!.start)
if textPositionValue != Constants.emptyTextFieldString.count {
badgeFieldDelegate?.badgeField?(self, willChangeTextFieldContentWithText: newString.trimmed())
return true
}
// Delete backward on zero width space
if let lastBadge = badges.last {
selectBadge(lastBadge)
selectedBadgeTextField.becomeFirstResponder()
}
return false
}
badgeFieldDelegate?.badgeField?(self, willChangeTextFieldContentWithText: newString.trimmed())
}
return true
}
}
// MARK: - PasteControlTextField
private class PasteControlTextField: UITextField {
/**
Note: This is a signal that indicates that this is under a paste context. This pasteSignal is reset in 'textFieldTextChanged' method of 'BadgeField' right after the delegate method is called
*/
fileprivate var isPaste: Bool = false
override func paste(_ sender: Any?) {
isPaste = true
super.paste(sender)
}
}
| 43.134895 | 534 | 0.668864 |
09a2de67380f737f5ecca7f1926ce4c42bdc0242 | 445 | //
// IPSecConfigurationCell.swift
// AVVPNService
//
// Created by Andrey Vasilev on 21.04.2020.
// Copyright © 2020 Andrey Vasilev. All rights reserved.
//
import UIKit
class IPSecConfigurationCell: UITableViewCell {
@IBOutlet weak var serverTextField: UITextField!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var sharedTextField: UITextField!
}
| 23.421053 | 57 | 0.752809 |
d7643efe2edb76579a8e6d6c243600b87527805c | 3,243 | //
// UIScrollView+Extensions.swift
// AppmazoKit
//
// Created by James Hickman on 5/17/18.
// Copyright © 2018 Appmazo, LLC. All rights reserved.
//
import UIKit
extension UIScrollView {
private struct Key {
static var keyboardObserver = "keyboardObserver"
}
public class KeyboardObserver: NSObject {
static var keyboardFrame = CGRect.zero
weak var scrollView: UIScrollView?
var originalContentInset: CGFloat = 0.0
deinit {
NotificationCenter.default.removeObserver(self)
}
init(scrollView: UIScrollView) {
self.scrollView = scrollView
super.init()
originalContentInset = scrollView.contentInset.bottom
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(_ notification: Notification) {
guard let keyboardData: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue, let scrollView = scrollView else { return }
KeyboardObserver.keyboardFrame = keyboardData.cgRectValue
scrollView.adjustBottomInset(forKeyboardFrame: keyboardData.cgRectValue)
}
@objc func keyboardDidHide(_ notification: Notification) {
guard let scrollView = scrollView else { return }
scrollView.contentInset.bottom = originalContentInset
scrollView.scrollIndicatorInsets.bottom = originalContentInset
}
}
/**
Automatically changes the scroll view's content size to accommodate the keyboard.
*/
public var automaticallytAdjustsInsetsForKeyboard: Bool {
get {
return !(keyboardObserver == nil)
}
set {
let keyboardObserverIsNil = keyboardObserver == nil
if newValue == true && keyboardObserverIsNil {
keyboardObserver = KeyboardObserver(scrollView: self)
} else if newValue == false && !keyboardObserverIsNil {
keyboardObserver = nil
}
}
}
/**
Manually changes the scroll view's content size to accommodate the keyboard.
*/
public func adjustInsetsForKeyboard() {
adjustBottomInset(forKeyboardFrame: KeyboardObserver.keyboardFrame)
}
private var keyboardObserver: KeyboardObserver? {
get { return objc_getAssociatedObject(self, &Key.keyboardObserver) as? KeyboardObserver }
set { objc_setAssociatedObject(self, &Key.keyboardObserver, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
private func adjustBottomInset(forKeyboardFrame frame: CGRect) {
let keyboardFrame = convert(frame, from: nil)
let bottomInset = bounds.intersection(keyboardFrame).size.height + (keyboardObserver?.originalContentInset ?? 0.0)
contentInset.bottom = bottomInset
scrollIndicatorInsets.bottom = bottomInset
}
}
| 38.607143 | 166 | 0.666667 |
913009d4e806634aa212a4ad3b48bf276fc0b9fa | 884 | //
// TargetsFilter.swift
//
//
// Created by Thibault Wittemberg on 2020-06-01.
//
public extension Xccov.Filters {
enum Targets {}
}
public extension Xccov.Filters.Targets {
static func filter(coverageReport: CoverageReport, targetsToExclude: [String]) -> CoverageReport {
guard !targetsToExclude.isEmpty else { return coverageReport }
let targetsToKeep = coverageReport.targets.filter { !$0.name.contains(elementsOf: targetsToExclude) }
let filteredCoverageReport = CoverageReport(executableLines: coverageReport.executableLines,
targets: targetsToKeep,
lineCoverage: coverageReport.lineCoverage,
coveredLines: coverageReport.coveredLines)
return filteredCoverageReport
}
}
| 36.833333 | 109 | 0.61991 |
33fe23c0ddbfc1524d3aa116b123987afd63299e | 1,601 | //
// PChainApiInfo.swift
//
//
// Created by Yehor Popovych on 01.09.2021.
//
import Foundation
import BigInt
public class AvalanchePChainApiInfo: AvalancheBaseVMApiInfo {
public let txFee: BigUInt
public let creationTxFee: BigUInt
public let minConsumption: Double
public let maxConsumption: Double
public let maxStakingDuration: BigUInt
public let maxSupply: BigUInt
public let minStake: BigUInt
public let minStakeDuration: UInt
public let maxStakeDuration: UInt
public let minDelegationStake: BigUInt
public let minDelegationFee: BigUInt
public init(
minConsumption: Double, maxConsumption: Double, maxStakingDuration: BigUInt,
maxSupply: BigUInt, minStake: BigUInt, minStakeDuration: UInt,
maxStakeDuration: UInt, minDelegationStake: BigUInt, minDelegationFee: BigUInt,
txFee: BigUInt, creationTxFee: BigUInt, blockchainID: BlockchainID,
alias: String? = nil, vm: String = "platformvm"
) {
self.minConsumption = minConsumption; self.maxConsumption = maxConsumption
self.maxStakingDuration = maxStakingDuration; self.maxSupply = maxSupply
self.minStake = minStake; self.minStakeDuration = minStakeDuration
self.maxStakeDuration = maxStakeDuration; self.minDelegationStake = minDelegationStake
self.minDelegationFee = minDelegationFee; self.txFee = txFee; self.creationTxFee = creationTxFee
super.init(blockchainID: blockchainID, alias: alias, vm: vm)
}
override public var apiPath: String {
return "/ext/\(chainId)"
}
}
| 37.232558 | 104 | 0.725172 |
69f95175bc9361a3c8307dd6eda1c41c447f3303 | 3,624 | //
// SheetView.swift
// Neves_Example
//
// Created by 周健平 on 2020/12/3.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import UIKit
// MARK: - 事件模型
struct SheetAction: PopActionCompatible {
typealias Execute = (SheetView, Self, Int) -> ()
/// 标题
let title: String
/// 是否点击选项后关闭弹窗
let isAfterExecToClose: Bool
/// 点击事件
let execute: Execute?
/// 标题颜色
let titleColor: UIColor
/// 构造器
init(title: String, titleColor: UIColor = .rgb(212, 209, 216), isAfterExecToClose: Bool = true, execute: Execute?) {
self.title = title
self.titleColor = titleColor
self.isAfterExecToClose = isAfterExecToClose
self.execute = execute
}
}
class SheetView: UIView, PopActionViewCompatible {
// MARK: - 公开属性
let style: PopStyle = .sheet
let contentView = UIView()
let actions: [SheetAction]
// MARK: - 初始化&反初始化
init(_ actions: [SheetAction]) {
self.actions = actions
super.init(frame: PortraitScreenBounds)
layer.backgroundColor = UIColor.rgb(0, 0, 0, a: 0).cgColor
let contentInserts = UIEdgeInsets(top: 25, left: 25, bottom: 25 + DiffTabBarH, right: 25)
let itemBgColor: UIColor = .rgb(63, 59, 84)
let itemTitleFont: UIFont = .systemFont(ofSize: 15)
let itemWidth: CGFloat = PortraitScreenWidth - contentInserts.left - contentInserts.right
let itemHeight: CGFloat = 40
let itemSpace: CGFloat = 15
var y: CGFloat = contentInserts.top
for i in 0..<actions.count {
let action = actions[i]
let btn = UIButton(type: .system)
btn.frame = CGRect(origin: [contentInserts.left, y], size: [itemWidth, itemHeight])
btn.layer.cornerRadius = itemHeight * 0.5
btn.layer.masksToBounds = true
btn.backgroundColor = itemBgColor
btn.setTitle(action.title, for: .normal)
btn.setTitleColor(action.titleColor, for: .normal)
btn.titleLabel?.font = itemTitleFont
btn.tag = i
btn.addTarget(self, action: #selector(didClickBtn(_:)), for: .touchUpInside)
contentView.addSubview(btn)
y += itemHeight
if i == (actions.count - 1) {
y += contentInserts.bottom
} else {
y += itemSpace
}
}
contentView.frame = [0, PortraitScreenHeight, PortraitScreenWidth, y]
let bgLayer = CAShapeLayer()
bgLayer.fillColor = UIColor.rgb(51, 46, 68).cgColor
bgLayer.borderWidth = 0
bgLayer.path = UIBezierPath(roundedRect: contentView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: [10, 10]).cgPath
contentView.layer.insertSublayer(bgLayer, at: 0)
addSubview(contentView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
JPrint("弹窗小妹死了")
}
// MARK: - 创建+弹出
@discardableResult
static func show(onView view: UIView? = nil, actions: [SheetAction]) -> SheetView? {
show(onView: view) { SheetView(actions) }
}
// MARK: - 点击空白关闭
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let point = touch.location(in: self)
if contentView.frame.contains(point) == false { close() }
}
// MARK: - 监听按钮点击
@objc func didClickBtn(_ sender: UIButton) { execAction(sender.tag) }
}
| 32.945455 | 140 | 0.599062 |
1ce56e459a941295b120fa8cdf1ca417af4b934d | 45,685 | //
// ParseFileTests.swift
// ParseSwift
//
// Created by Corey Baker on 12/23/20.
// Copyright © 2020 Parse Community. All rights reserved.
//
import Foundation
import XCTest
@testable import ParseSwift
class ParseFileTests: XCTestCase { // swiftlint:disable:this type_body_length
let temporaryDirectory = "\(NSTemporaryDirectory())test/"
struct FileUploadResponse: Codable {
let name: String
let url: URL
}
override func setUpWithError() throws {
try super.setUpWithError()
guard let url = URL(string: "http://localhost:1337/1") else {
XCTFail("Should create valid URL")
return
}
ParseSwift.initialize(applicationId: "applicationId",
clientKey: "clientKey",
masterKey: "masterKey",
serverURL: url,
testing: true)
guard let fileManager = ParseFileManager() else {
throw ParseError(code: .unknownError, message: "Should have initialized file manage")
}
try fileManager.createDirectoryIfNeeded(temporaryDirectory)
}
override func tearDownWithError() throws {
try super.tearDownWithError()
MockURLProtocol.removeAll()
#if !os(Linux) && !os(Android)
try KeychainStore.shared.deleteAll()
#endif
try ParseStorage.shared.deleteAll()
guard let fileManager = ParseFileManager(),
let defaultDirectoryPath = fileManager.defaultDataDirectoryPath else {
throw ParseError(code: .unknownError, message: "Should have initialized file manage")
}
let directory = URL(fileURLWithPath: temporaryDirectory, isDirectory: true)
let expectation1 = XCTestExpectation(description: "Delete files1")
fileManager.removeDirectoryContents(directory) { error in
guard let error = error else {
expectation1.fulfill()
return
}
XCTFail(error.localizedDescription)
expectation1.fulfill()
}
let directory2 = defaultDirectoryPath
.appendingPathComponent(ParseConstants.fileDownloadsDirectory, isDirectory: true)
let expectation2 = XCTestExpectation(description: "Delete files2")
fileManager.removeDirectoryContents(directory2) { _ in
expectation2.fulfill()
}
wait(for: [expectation1, expectation2], timeout: 20.0)
}
func testUploadCommand() throws {
guard let url = URL(string: "http://localhost/") else {
XCTFail("Should have created url")
return
}
let file = ParseFile(name: "a", cloudURL: url)
let command = try file.uploadFileCommand()
XCTAssertNotNil(command)
XCTAssertEqual(command.path.urlComponent, "/files/a")
XCTAssertEqual(command.method, API.Method.POST)
XCTAssertNil(command.params)
XCTAssertNil(command.body)
let file2 = ParseFile(cloudURL: url)
let command2 = try file2.uploadFileCommand()
XCTAssertNotNil(command2)
XCTAssertEqual(command2.path.urlComponent, "/files/file")
XCTAssertEqual(command2.method, API.Method.POST)
XCTAssertNil(command2.params)
XCTAssertNil(command2.body)
}
func testUploadCommandDontAllowUpdate() throws {
guard let url = URL(string: "http://localhost/") else {
XCTFail("Should have created url")
return
}
var file = ParseFile(cloudURL: url)
file.url = url
XCTAssertThrowsError(try file.uploadFileCommand())
}
func testDeleteCommand() {
guard let url = URL(string: "http://localhost/") else {
XCTFail("Should have created url")
return
}
var file = ParseFile(name: "a", cloudURL: url)
file.url = url
let command = file.deleteFileCommand()
XCTAssertNotNil(command)
XCTAssertEqual(command.path.urlComponent, "/files/a")
XCTAssertEqual(command.method, API.Method.DELETE)
XCTAssertNil(command.params)
XCTAssertNil(command.body)
var file2 = ParseFile(cloudURL: url)
file2.url = url
let command2 = file2.deleteFileCommand()
XCTAssertNotNil(command2)
XCTAssertEqual(command2.path.urlComponent, "/files/file")
XCTAssertEqual(command2.method, API.Method.DELETE)
XCTAssertNil(command2.params)
XCTAssertNil(command2.body)
}
func testDownloadCommand() {
guard let url = URL(string: "http://localhost/") else {
XCTFail("Should have created url")
return
}
var file = ParseFile(name: "a", cloudURL: url)
file.url = url
let command = file.downloadFileCommand()
XCTAssertNotNil(command)
XCTAssertEqual(command.path.urlComponent, "/files/a")
XCTAssertEqual(command.method, API.Method.GET)
XCTAssertNil(command.params)
XCTAssertNil(command.body)
let file2 = ParseFile(cloudURL: url)
let command2 = file2.downloadFileCommand()
XCTAssertNotNil(command2)
XCTAssertEqual(command2.path.urlComponent, "/files/file")
XCTAssertEqual(command2.method, API.Method.GET)
XCTAssertNil(command2.params)
XCTAssertNil(command2.body)
}
func testLocalUUID() throws {
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
let parseFile = ParseFile(name: "sampleData.txt", data: sampleData)
let localId = parseFile.localId
XCTAssertNotNil(localId)
XCTAssertEqual(localId,
parseFile.localId,
"localId should remain the same no matter how many times the getter is called")
}
func testFileEquality() throws {
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
guard let url1 = URL(string: "https://parseplatform.org/img/logo.svg"),
let url2 = URL(string: "https://parseplatform.org/img/logo2.svg") else {
throw ParseError(code: .unknownError, message: "Should have created urls")
}
var parseFile1 = ParseFile(name: "sampleData.txt", data: sampleData)
parseFile1.url = url1
var parseFile2 = ParseFile(name: "sampleData2.txt", data: sampleData)
parseFile2.url = url2
var parseFile3 = ParseFile(name: "sampleData3.txt", data: sampleData)
parseFile3.url = url1
XCTAssertNotEqual(parseFile1, parseFile2, "different urls, url takes precedence over localId")
XCTAssertEqual(parseFile1, parseFile3, "same urls")
parseFile1.url = nil
parseFile2.url = nil
XCTAssertNotEqual(parseFile1, parseFile2, "no urls, but localIds shoud be different")
let uuid = UUID()
parseFile1.localId = uuid
parseFile2.localId = uuid
XCTAssertEqual(parseFile1, parseFile2, "no urls, but localIds shoud be the same")
}
func testSave() throws {
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
let parseFile = ParseFile(name: "sampleData.txt",
data: sampleData,
metadata: ["Testing": "123"],
tags: ["Hey": "now"])
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_sampleData.txt") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let savedFile = try parseFile.save()
XCTAssertEqual(savedFile.name, response.name)
XCTAssertEqual(savedFile.url, response.url)
}
func testSaveWithSpecifyingMime() throws {
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
let parseFile = ParseFile(data: sampleData, mimeType: "application/txt")
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_file") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let savedFile = try parseFile.save()
XCTAssertEqual(savedFile.name, response.name)
XCTAssertEqual(savedFile.url, response.url)
}
func testSaveLocalFile() throws {
let tempFilePath = URL(fileURLWithPath: "\(temporaryDirectory)sampleData.txt")
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
try sampleData.write(to: tempFilePath)
let parseFile = ParseFile(name: "sampleData.txt", localURL: tempFilePath)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_sampleData.txt") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let savedFile = try parseFile.save()
XCTAssertEqual(savedFile.name, response.name)
XCTAssertEqual(savedFile.url, response.url)
XCTAssertEqual(savedFile.localURL, tempFilePath)
}
func testSaveFileStream() throws {
let tempFilePath = URL(fileURLWithPath: "\(temporaryDirectory)sampleData.dat")
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
try sampleData.write(to: tempFilePath)
let parseFile = ParseFile(name: "sampleData.data", localURL: tempFilePath)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_sampleData.txt") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
guard let stream = InputStream(fileAtPath: tempFilePath.relativePath) else {
throw ParseError(code: .unknownError, message: "Should have created file stream")
}
try parseFile.save(options: [], stream: stream, progress: nil)
}
func testSaveFileStreamProgress() throws {
let tempFilePath = URL(fileURLWithPath: "\(temporaryDirectory)sampleData.dat")
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
try sampleData.write(to: tempFilePath)
let parseFile = ParseFile(name: "sampleData.data", localURL: tempFilePath)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_sampleData.txt") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
guard let stream = InputStream(fileAtPath: tempFilePath.relativePath) else {
throw ParseError(code: .unknownError, message: "Should have created file stream")
}
try parseFile.save(stream: stream) { (_, _, totalWritten, totalExpected) in
let currentProgess = Double(totalWritten)/Double(totalExpected) * 100
XCTAssertGreaterThan(currentProgess, -1)
}
}
func testSaveFileStreamCancel() throws {
let tempFilePath = URL(fileURLWithPath: "\(temporaryDirectory)sampleData.dat")
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
try sampleData.write(to: tempFilePath)
let parseFile = ParseFile(name: "sampleData.data", localURL: tempFilePath)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_sampleData.txt") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
guard let stream = InputStream(fileAtPath: tempFilePath.relativePath) else {
throw ParseError(code: .unknownError, message: "Should have created file stream")
}
try parseFile.save(stream: stream) { (task, _, totalWritten, totalExpected) in
let currentProgess = Double(totalWritten)/Double(totalExpected) * 100
if currentProgess > 10 {
task.cancel()
}
}
}
func testUpdateFileError() throws {
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
var parseFile = ParseFile(name: "sampleData.txt",
data: sampleData,
metadata: ["Testing": "123"],
tags: ["Hey": "now"])
parseFile.url = URL(string: "http://localhost/")
XCTAssertThrowsError(try parseFile.save())
}
func testFetchFileStream() throws {
let tempFilePath = URL(fileURLWithPath: "\(temporaryDirectory)sampleData.dat")
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
try sampleData.write(to: tempFilePath)
let parseFile = ParseFile(name: "sampleData.data", localURL: tempFilePath)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_sampleData.txt") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
guard let stream = InputStream(fileAtPath: tempFilePath.relativePath) else {
throw ParseError(code: .unknownError, message: "Should have created file stream")
}
try parseFile.fetch(stream: stream)
}
func testSaveAysnc() throws {
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
let parseFile = ParseFile(name: "sampleData.txt", data: sampleData)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_sampleData.txt") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.save { result in
switch result {
case .success(let saved):
XCTAssertEqual(saved.name, response.name)
XCTAssertEqual(saved.url, response.url)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testSaveFileProgressAsync() throws {
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
let parseFile = ParseFile(name: "sampleData.txt", data: sampleData)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_sampleData.txt") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.save(progress: { (_, _, totalWritten, totalExpected) in
let currentProgess = Double(totalWritten)/Double(totalExpected) * 100
XCTAssertGreaterThan(currentProgess, -1)
}) { result in // swiftlint:disable:this multiple_closures_with_trailing_closure
switch result {
case .success(let saved):
XCTAssertEqual(saved.name, response.name)
XCTAssertEqual(saved.url, response.url)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testSaveFileCancelAsync() throws {
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
let parseFile = ParseFile(name: "sampleData.txt", data: sampleData)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_sampleData.txt") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.save(progress: { (task, _, totalWritten, totalExpected) in
let currentProgess = Double(totalWritten)/Double(totalExpected) * 100
if currentProgess > 10 {
task.cancel()
}
}) { result in // swiftlint:disable:this multiple_closures_with_trailing_closure
switch result {
case .success(let saved):
XCTAssertEqual(saved.name, response.name)
XCTAssertEqual(saved.url, response.url)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testSaveWithSpecifyingMimeAysnc() throws {
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
let parseFile = ParseFile(data: sampleData, mimeType: "application/txt")
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_file") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.save { result in
switch result {
case .success(let saved):
XCTAssertEqual(saved.name, response.name)
XCTAssertEqual(saved.url, response.url)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testSaveLocalFileAysnc() throws {
let tempFilePath = URL(fileURLWithPath: "\(temporaryDirectory)sampleData.txt")
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
try sampleData.write(to: tempFilePath)
let parseFile = ParseFile(name: "sampleData.txt", localURL: tempFilePath)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_sampleData.txt") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.save { result in
switch result {
case .success(let saved):
XCTAssertEqual(saved.name, response.name)
XCTAssertEqual(saved.url, response.url)
XCTAssertEqual(saved.localURL, tempFilePath)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testUpdateErrorAysnc() throws {
guard let sampleData = "Hello World".data(using: .utf8) else {
throw ParseError(code: .unknownError, message: "Should have converted to data")
}
var parseFile = ParseFile(name: "sampleData.txt", data: sampleData)
parseFile.url = URL(string: "http://localhost/")
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.save { result in
switch result {
case .success:
XCTFail("Should have returned error")
case .failure(let error):
XCTAssertTrue(error.message.contains("File is already"))
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
#if !os(Linux) && !os(Android)
//URL Mocker is not able to mock this in linux and tests fail, so don't run.
func testFetchFileCancelAsync() throws {
// swiftlint:disable:next line_length
guard let parseFileURL = URL(string: "http://localhost:1337/1/files/applicationId/7793939a2e59b98138c1bbf2412a060c_logo.svg") else {
XCTFail("Should create URL")
return
}
var parseFile = ParseFile(name: "7793939a2e59b98138c1bbf2412a060c_logo.svg", cloudURL: parseFileURL)
parseFile.url = parseFileURL
let response = FileUploadResponse(name: "7793939a2e59b98138c1bbf2412a060c_logo.svg",
url: parseFileURL)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.fetch(progress: { (task, _, totalDownloaded, totalExpected) in
let currentProgess = Double(totalDownloaded)/Double(totalExpected) * 100
if currentProgess > 10 {
task.cancel()
}
}) { result in // swiftlint:disable:this multiple_closures_with_trailing_closure
switch result {
case .success(let fetched):
XCTAssertEqual(fetched.name, response.name)
XCTAssertEqual(fetched.url, response.url)
XCTAssertNotNil(fetched.localURL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testFetchFileAysnc() throws {
// swiftlint:disable:next line_length
guard let parseFileURL = URL(string: "http://localhost:1337/1/files/applicationId/7793939a2e59b98138c1bbf2412a060c_logo.svg") else {
XCTFail("Should create URL")
return
}
var parseFile = ParseFile(name: "7793939a2e59b98138c1bbf2412a060c_logo.svg", cloudURL: parseFileURL)
parseFile.url = parseFileURL
let response = FileUploadResponse(name: "7793939a2e59b98138c1bbf2412a060c_logo.svg",
url: parseFileURL)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.fetch { result in
switch result {
case .success(let fetched):
XCTAssertEqual(fetched.name, response.name)
XCTAssertEqual(fetched.url, response.url)
XCTAssertNotNil(fetched.localURL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testFetchFileProgressAsync() throws {
// swiftlint:disable:next line_length
guard let parseFileURL = URL(string: "http://localhost:1337/1/files/applicationId/6f9988ab5faa28f7247664c6ffd9fd85_logo.svg") else {
XCTFail("Should create URL")
return
}
var parseFile = ParseFile(name: "6f9988ab5faa28f7247664c6ffd9fd85_logo.svg", cloudURL: parseFileURL)
parseFile.url = parseFileURL
let response = FileUploadResponse(name: "6f9988ab5faa28f7247664c6ffd9fd85_logo.svg",
url: parseFileURL)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.fetch(progress: { (_, _, totalDownloaded, totalExpected) in
let currentProgess = Double(totalDownloaded)/Double(totalExpected) * 100
XCTAssertGreaterThan(currentProgess, -1)
}) { result in // swiftlint:disable:this multiple_closures_with_trailing_closure
switch result {
case .success(let fetched):
XCTAssertEqual(fetched.name, response.name)
XCTAssertEqual(fetched.url, response.url)
XCTAssertNotNil(fetched.localURL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testSaveCloudFileProgressAysnc() throws {
guard let tempFilePath = URL(string: "https://parseplatform.org/img/logo.svg") else {
XCTFail("Should create URL")
return
}
let parseFile = ParseFile(name: "logo.svg", cloudURL: tempFilePath)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_logo.svg") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.save(progress: { (_, _, totalWritten, totalExpected) in
let currentProgess = Double(totalWritten)/Double(totalExpected) * 100
XCTAssertGreaterThan(currentProgess, -1)
}) { result in // swiftlint:disable:this multiple_closures_with_trailing_closure
switch result {
case .success(let saved):
XCTAssertEqual(saved.name, response.name)
XCTAssertEqual(saved.url, response.url)
XCTAssertEqual(saved.cloudURL, tempFilePath)
XCTAssertNotNil(saved.localURL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testSaveCloudFileAysnc() throws {
guard let tempFilePath = URL(string: "https://parseplatform.org/img/logo.svg") else {
XCTFail("Should create URL")
return
}
let parseFile = ParseFile(name: "logo.svg", cloudURL: tempFilePath)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_logo.svg") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.save { result in
switch result {
case .success(let saved):
XCTAssertEqual(saved.name, response.name)
XCTAssertEqual(saved.url, response.url)
XCTAssertEqual(saved.cloudURL, tempFilePath)
XCTAssertNotNil(saved.localURL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testSaveCloudFile() throws {
guard let tempFilePath = URL(string: "https://parseplatform.org/img/logo.svg") else {
XCTFail("Should create URL")
return
}
let parseFile = ParseFile(name: "logo.svg", cloudURL: tempFilePath)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_logo.svg") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let savedFile = try parseFile.save()
XCTAssertEqual(savedFile.name, response.name)
XCTAssertEqual(savedFile.url, response.url)
XCTAssertEqual(savedFile.cloudURL, tempFilePath)
XCTAssertNotNil(savedFile.localURL)
}
func testFetchFile() throws {
// swiftlint:disable:next line_length
guard let parseFileURL = URL(string: "http://localhost:1337/1/files/applicationId/d3a37aed0672a024595b766f97133615_logo.svg") else {
XCTFail("Should create URL")
return
}
var parseFile = ParseFile(name: "d3a37aed0672a024595b766f97133615_logo.svg", cloudURL: parseFileURL)
parseFile.url = parseFileURL
let response = FileUploadResponse(name: "d3a37aed0672a024595b766f97133615_logo.svg",
url: parseFileURL)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let fetchedFile = try parseFile.fetch()
XCTAssertEqual(fetchedFile.name, response.name)
XCTAssertEqual(fetchedFile.url, response.url)
XCTAssertNotNil(fetchedFile.localURL)
}
func testFetchFileProgress() throws {
// swiftlint:disable:next line_length
guard let parseFileURL = URL(string: "http://localhost:1337/1/files/applicationId/d3a37aed0672a024595b766f97133615_logo.svg") else {
XCTFail("Should create URL")
return
}
var parseFile = ParseFile(name: "d3a37aed0672a024595b766f97133615_logo.svg", cloudURL: parseFileURL)
parseFile.url = parseFileURL
let response = FileUploadResponse(name: "d3a37aed0672a024595b766f97133615_logo.svg",
url: parseFileURL)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let fetchedFile = try parseFile.fetch { (_, _, totalDownloaded, totalExpected) in
let currentProgess = Double(totalDownloaded)/Double(totalExpected) * 100
XCTAssertGreaterThan(currentProgess, -1)
}
XCTAssertEqual(fetchedFile.name, response.name)
XCTAssertEqual(fetchedFile.url, response.url)
XCTAssertNotNil(fetchedFile.localURL)
}
func testDeleteFileAysnc() throws {
// swiftlint:disable:next line_length
guard let parseFileURL = URL(string: "http://localhost:1337/1/files/applicationId/1b0683d529463e173cbf8046d7d9a613_logo.svg") else {
XCTFail("Should create URL")
return
}
var parseFile = ParseFile(name: "1b0683d529463e173cbf8046d7d9a613_logo.svg", cloudURL: parseFileURL)
parseFile.url = parseFileURL
let response = FileUploadResponse(name: "1b0683d529463e173cbf8046d7d9a613_logo.svg",
url: parseFileURL)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.delete(options: [.useMasterKey]) { result in
if case let .failure(error) = result {
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testDeleteFileAysncError() throws {
// swiftlint:disable:next line_length
guard let parseFileURL = URL(string: "http://localhost:1337/1/files/applicationId/1b0683d529463e173cbf8046d7d9a613_logo.svg") else {
XCTFail("Should create URL")
return
}
var parseFile = ParseFile(name: "1b0683d529463e173cbf8046d7d9a613_logo.svg", cloudURL: parseFileURL)
parseFile.url = parseFileURL
let response = ParseError(code: .fileTooLarge, message: "Too large.")
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let expectation1 = XCTestExpectation(description: "ParseFile async")
parseFile.delete(options: [.useMasterKey]) { result in
if case .success = result {
XCTFail("Should have failed with error")
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testDeleteFile() throws {
// swiftlint:disable:next line_length
guard let parseFileURL = URL(string: "http://localhost:1337/1/files/applicationId/d3a37aed0672a024595b766f97133615_logo.svg") else {
XCTFail("Should create URL")
return
}
var parseFile = ParseFile(name: "d3a37aed0672a024595b766f97133615_logo.svg", cloudURL: parseFileURL)
parseFile.url = parseFileURL
let response = FileUploadResponse(name: "d3a37aed0672a024595b766f97133615_logo.svg",
url: parseFileURL)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
try parseFile.delete(options: [.useMasterKey])
}
func testCloudFileProgress() throws {
guard let tempFilePath = URL(string: "https://parseplatform.org/img/logo.svg") else {
XCTFail("Should create URL")
return
}
let parseFile = ParseFile(name: "logo.svg", cloudURL: tempFilePath)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_logo.svg") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let savedFile = try parseFile.save { (_, _, totalWritten, totalExpected) in
let currentProgess = Double(totalWritten)/Double(totalExpected) * 100
XCTAssertGreaterThan(currentProgess, -1)
}
XCTAssertEqual(savedFile.name, response.name)
XCTAssertEqual(savedFile.url, response.url)
XCTAssertEqual(savedFile.cloudURL, tempFilePath)
XCTAssertNotNil(savedFile.localURL)
}
func testCloudFileCancel() throws {
guard let tempFilePath = URL(string: "https://parseplatform.org/img/logo.svg") else {
XCTFail("Should create URL")
return
}
let parseFile = ParseFile(name: "logo.svg", cloudURL: tempFilePath)
// swiftlint:disable:next line_length
guard let url = URL(string: "http://localhost:1337/1/files/applicationId/89d74fcfa4faa5561799e5076593f67c_logo.svg") else {
XCTFail("Should create URL")
return
}
let response = FileUploadResponse(name: "89d74fcfa4faa5561799e5076593f67c_\(parseFile.name)", url: url)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should encode/decode. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
let savedFile = try parseFile.save { (task, _, totalWritten, totalExpected) in
let currentProgess = Double(totalWritten)/Double(totalExpected) * 100
if currentProgess > 10 {
task.cancel()
}
}
XCTAssertEqual(savedFile.name, response.name)
XCTAssertEqual(savedFile.url, response.url)
XCTAssertEqual(savedFile.cloudURL, tempFilePath)
XCTAssertNotNil(savedFile.localURL)
}
#endif
} // swiftlint:disable:this file_length
| 40.180299 | 140 | 0.617577 |
232c378f6bc1ebad767d3ac995b0039bfffba2c5 | 205 | //
// Constants.swift
// Authenticator
//
// Created by Bastiaan Jansen on 08/12/2020.
//
import Foundation
import CoreGraphics
struct Constants {
static let navigationBarIconSize: CGFloat = 25
}
| 14.642857 | 50 | 0.721951 |
01a91488700604cd67cc6342bc6c02cc8171a7dd | 465 | //
// NumericAttribute.swift
// Introspective
//
// Created by Bryan Nova on 8/10/18.
// Copyright © 2018 Bryan Nova. All rights reserved.
//
import Foundation
import HealthKit
public protocol NumericAttribute: GraphableAttribute, ComparableAttribute {
/// Is the specified value valid for this attribute?
func isValid(value: String) -> Bool
func errorMessageFor(invalidValue: String) -> String
func convertToValue(from strValue: String) throws -> Any?
}
| 25.833333 | 75 | 0.752688 |
d720ac3bacb3aa4600bd3bec8455ed6d50a649d2 | 1,487 | //
// InfoController.swift
// Timecode
//
// Created by Matthew Gray on 11/15/16.
// Copyright © 2016 Matthew Gray. All rights reserved.
//
import Foundation
import UIKit
class InfoController: UITableViewController {
@IBOutlet weak var disableSleepingSwitch: UISwitch!
@IBAction func disableSleepingChanged(_ sender: Any) {
UIApplication.shared.isIdleTimerDisabled = true
if (disableSleepingSwitch.isOn) {
UIApplication.shared.isIdleTimerDisabled = true
} else {
UIApplication.shared.isIdleTimerDisabled = false
}
}
override func viewDidLoad() {
//load the setting
super.viewDidLoad()
if (UIApplication.shared.isIdleTimerDisabled) {
disableSleepingSwitch.setOn(true, animated: false)
} else {
disableSleepingSwitch.setOn(false, animated: false)
}
}
@IBAction func website(_ sender: Any) {
UIApplication.shared.openURL(URL(string: "http://www.mattgray.net")!)
}
@IBAction func email(_ sender: Any) {
UIApplication.shared.openURL(URL(string: "mailto:[email protected]")!)
}
@IBAction func twitter(_ sender: Any) {
UIApplication.shared.openURL(URL(string: "http://www.twitter.com/grayma7")!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 27.537037 | 84 | 0.637525 |
21f710ea4acabbba0dd65efe9dae9762351e49d4 | 1,269 | /**
* (C) Copyright IBM Corp. 2019.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
API usage information for the request.
*/
public struct AnalysisResultsUsage: Codable, Equatable {
/**
Number of features used in the API call.
*/
public var features: Int?
/**
Number of text characters processed.
*/
public var textCharacters: Int?
/**
Number of 10,000-character units processed.
*/
public var textUnits: Int?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case features = "features"
case textCharacters = "text_characters"
case textUnits = "text_units"
}
}
| 27 | 82 | 0.687155 |
489c77718f15cffeb8f44d976174467e297b5d44 | 1,402 | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "PetstagramAPI",
platforms: [.macOS(.v10_15)],
dependencies: [
.package(url: "https://github.com/IBM-Swift/Kitura.git", .upToNextMinor(from: "2.8.0")),
.package(url: "https://github.com/IBM-Swift/HeliumLogger.git", from: "1.7.1"),
.package(url: "https://github.com/IBM-Swift/CloudEnvironment.git", from: "9.0.0"),
.package(url: "https://github.com/RuntimeTools/SwiftMetrics.git", from: "2.0.0"),
.package(url: "https://github.com/IBM-Swift/Health.git", from: "1.0.0"),
.package(url: "https://github.com/IBM-Swift/Swift-Kuery-ORM.git", from: "0.6.0"),
.package(url: "https://github.com/IBM-Swift/Swift-Kuery-PostgreSQL.git", from: "2.1.1"),
.package(url: "https://github.com/IBM-Swift/Kitura-OpenAPI.git", from: "1.2.1"),
.package(url: "https://github.com/IBM-Swift/Kitura-CredentialsHTTP.git", from: "2.1.3")
],
targets: [
.target(name: "PetstagramAPI", dependencies: [ .target(name: "Application") ]),
.target(name: "Application", dependencies: [ "Kitura", "HeliumLogger", "CloudEnvironment","SwiftMetrics", "Health", "SwiftKueryORM", "SwiftKueryPostgreSQL", "KituraOpenAPI", "CredentialsHTTP"
]),
.testTarget(name: "ApplicationTests" , dependencies: [.target(name: "Application"), "Kitura", "HeliumLogger" ])
]
)
| 51.925926 | 197 | 0.651213 |
ccec4607f9e263425c49670a8162442a18bc8050 | 961 | import UIKit
@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
@available(iOS 13.0, *)
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
#if targetEnvironment(macCatalyst)
override func buildMenu(with builder: UIMenuBuilder) {
guard builder.system == UIMenuSystem.main else { return }
builder.remove(menu: .file)
builder.remove(menu: .format)
builder.remove(menu: .help)
builder.remove(menu: .services)
}
#endif
}
| 35.592593 | 179 | 0.723205 |
21f771fa9bef38fe9e90cbe3518e6feb4580b157 | 5,075 | //
// TourneyViewController.swift
// Ranger
//
// Created by Geri Borbás on 2019. 12. 02..
// Copyright © 2019. Geri Borbás. All rights reserved.
//
import Cocoa
import CoreGraphics
class TournamentViewController: NSViewController
{
// MARK: - UI
weak var playersTable: PlayersTableViewController?
weak var tableOverlay: TableOverlayViewController?
@IBOutlet weak var summaryLabel: NSTextField!
@IBOutlet weak var statusLabel: NSTextField!
// MARK: - Model
@IBOutlet weak var viewModel: TournamentViewModel!
// MARK: - Lifecycle
override func viewDidLoad()
{
super.viewDidLoad()
// View model hook.
viewModel.delegate = self
// Fetch SharkScope status.
viewModel.fetchSharkScopeStatus{ _ in self.layoutStatus() }
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?)
{
// Wire up child view controller references.
switch segue.destinationController
{
case let playersTableViewController as PlayersTableViewController:
self.playersTable = playersTableViewController
self.playersTable?.delegate = self
case let tableOverlayViewController as TableOverlayViewController:
self.tableOverlay = tableOverlayViewController
self.tableOverlay?.delegate = self
default:
break
}
}
// MARK: - Hooks
func update(with tableWindowInfo: TableWindowInfo)
{
// Inject into view model (may push back changes if any).
viewModel.update(with: tableWindowInfo)
// UI.
alignWindow(to: tableWindowInfo)
}
func alignWindow(to tableWindowInfo: TableWindowInfo)
{
// Only if any.
guard let window = self.view.window
else { return }
// Align.
window.setFrame(tableWindowInfo.UIKitBounds, display: true)
window.order(NSWindow.OrderingMode.above, relativeTo: tableWindowInfo.number)
// Disable drag.
window.isMovable = false
}
// MARK: - User Events
@IBAction func fetchAllDidClick(_ sender: AnyObject)
{
// Checks.
guard let playersTableViewController = self.playersTable else { return }
// Fetch SharkScope for all (gonna push changes back each).
for eachRow in 0...playersTableViewController.tableView.numberOfRows
{ playersTableViewController.viewModel.fetchSharkScopeStatisticsForPlayer(inRow: eachRow) }
}
// MARK: - Layout
func layout()
{
// Summary.
let summary = viewModel.summary(with: summaryLabel.font!)
summaryLabel.attributedStringValue = summary
// Players.
playersTable?.tableView.reloadData()
}
func layoutStatus()
{
// Window tracking.
var windowStatus = ""
if let tournamentInfo = viewModel.tournamentInfo
{ windowStatus = "Tracking tournament \(tournamentInfo.tournamentNumber) table \(tournamentInfo.tableNumber). " }
// PokerTracker.
let pokerTrackerStatus = (viewModel.latestProcessedHandNumber == "") ? "" : "Hand #\(viewModel.latestProcessedHandNumber) processed. "
// Composite (with SharkScope)
statusLabel.stringValue = "\(windowStatus)\(pokerTrackerStatus)\(viewModel.sharkScopeStatus)"
}
func updateWindowShadow()
{
// Only if any.
guard let window = self.view.window
else { return }
window.invalidateShadow()
}
}
// MARK: - Tournament Events
extension TournamentViewController: TournamentViewModelDelegate
{
func tournamentPlayersDidChange(tournamentPlayers: [Model.Player])
{
playersTable?.update(with: tournamentPlayers)
updateWindowShadow()
}
func tournamentDidChange(tournamentInfo: TournamentInfo)
{
playersTable?.update(with: tournamentInfo)
updateWindowShadow()
}
}
// MARK: - Players Table View Controller Events
extension TournamentViewController: PlayersTableViewControllerDelegate
{
func playersTableDidChange()
{
layout()
// Update overlay with processed player data.
if
let players = playersTable?.viewModel.players,
let tournamentInfo = playersTable?.viewModel.tournamentInfo
{
tableOverlay?.update(with: players, tournamentInfo: tournamentInfo)
updateWindowShadow()
}
// Fetch SharkScope status.
viewModel.fetchSharkScopeStatus{ _ in self.layoutStatus() }
}
}
// MARK: - Table Overlay Events
extension TournamentViewController: TableOverlayViewControllerDelegate
{
func seatDidClick(seatViewController: SeatViewController)
{ playersTable?.selectRow(at: seatViewController.seat) }
}
| 26.570681 | 142 | 0.628768 |
0a1e64e96d3a2a148117dc2643fd804b2aa4722a | 1,003 | //
// ProteinCell.swift
// protein
//
// Created by kudakwashe on 2019/11/13.
// Copyright © 2019 WeThinkCode. All rights reserved.
//
import UIKit
class ProteinCell: UITableViewCell {
let titleLbl: UILabel = {
let lbl = UILabel()
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(titleLbl)
titleLbl.topAnchor.constraint(equalTo: topAnchor).isActive = true
titleLbl.leftAnchor.constraint(equalTo: leftAnchor, constant: 20).isActive = true
titleLbl.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
titleLbl.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 27.861111 | 89 | 0.665005 |
2fd9c10602c3d7f62e5f8b6edcf4744569611ae6 | 1,532 | //
// String.swift
// CommandLineKit
//
// Created by Bas van Kuijck on 20/10/2017.
//
import Foundation
typealias CaptureGroupResult = (Range<String.Index>, String)
extension String {
func capturedGroups(withRegex pattern: String,
options: NSRegularExpression.Options = []) -> [CaptureGroupResult] {
let regex: NSRegularExpression
do {
regex = try NSRegularExpression(pattern: pattern, options: options)
} catch {
return []
}
guard let match = regex.matches(in: self, range: NSRange(location: 0, length: self.count)).first else {
return []
}
let lastRangeIndex = match.numberOfRanges - 1
guard lastRangeIndex >= 1 else {
return []
}
return Array(1...lastRangeIndex)
.map { match.range(at: $0) }
.compactMap { index -> CaptureGroupResult? in
guard let range = Range(index, in: self) else {
return nil
}
let matchedString = (self as NSString).substring(with: index)
return (range, matchedString)
}
}
func toConfigurations(with allConfigurations: [String]) -> [String] {
let dicValueConfigurations = components(separatedBy: ",").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
if dicValueConfigurations.first == "*" {
return allConfigurations
}
return dicValueConfigurations
}
}
| 29.461538 | 124 | 0.578982 |
f7ddf0090b0d718d416143e7f0d53150717f6eae | 9,353 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import TSCBasic
import Build
import TSCUtility
import PackageGraph
import PackageModel
/// An enumeration of the errors that can be generated by the run tool.
private enum RunError: Swift.Error {
/// The package manifest has no executable product.
case noExecutableFound
/// Could not find a specific executable in the package manifest.
case executableNotFound(String)
/// There are multiple executables and one must be chosen.
case multipleExecutables([String])
}
extension RunError: CustomStringConvertible {
var description: String {
switch self {
case .noExecutableFound:
return "no executable product available"
case .executableNotFound(let executable):
return "no executable product named '\(executable)'"
case .multipleExecutables(let executables):
let joinedExecutables = executables.joined(separator: ", ")
return "multiple executable products available: \(joinedExecutables)"
}
}
}
public class RunToolOptions: ToolOptions {
/// Returns the mode in with the tool command should run.
var mode: RunMode {
// If we got version option, just print the version and exit.
if shouldPrintVersion {
return .version
}
if shouldLaunchREPL {
return .repl
}
return .run
}
/// If the executable product should be built before running.
var shouldBuild = true
/// If the test should be built.
var shouldBuildTests = false
/// If should launch the Swift REPL.
var shouldLaunchREPL = false
/// The executable product to run.
var executable: String?
/// The arguments to pass to the executable.
var arguments: [String] = []
}
public enum RunMode {
case version
case repl
case run
}
/// swift-run tool namespace
public class SwiftRunTool: SwiftTool<RunToolOptions> {
public convenience init(args: [String]) {
self.init(
toolName: "run",
usage: "[options] [executable [arguments ...]]",
overview: "Build and run an executable product",
args: args,
seeAlso: type(of: self).otherToolNames()
)
}
override func runImpl() throws {
switch options.mode {
case .version:
print(Versioning.currentVersion.completeDisplayString)
case .repl:
// Load a custom package graph which has a special product for REPL.
let graphLoader = { try self.loadPackageGraph(createREPLProduct: self.options.shouldLaunchREPL) }
let buildParameters = try self.buildParameters()
// Construct the build operation.
let buildOp = BuildOperation(
buildParameters: buildParameters,
useBuildManifestCaching: false,
packageGraphLoader: graphLoader,
diagnostics: diagnostics,
stdoutStream: self.stdoutStream
)
// Save the instance so it can be cancelled from the int handler.
self.buildSystemRef.buildSystem = buildOp
// Perform build.
try buildOp.build()
// Execute the REPL.
let arguments = buildOp.buildPlan!.createREPLArguments()
print("Launching Swift REPL with arguments: \(arguments.joined(separator: " "))")
try run(getToolchain().swiftInterpreter, arguments: arguments)
case .run:
// Detect deprecated uses of swift run to interpret scripts.
if let executable = options.executable, isValidSwiftFilePath(executable) {
diagnostics.emit(.runFileDeprecation)
// Redirect execution to the toolchain's swift executable.
let swiftInterpreterPath = try getToolchain().swiftInterpreter
// Prepend the script to interpret to the arguments.
let arguments = [executable] + options.arguments
try run(swiftInterpreterPath, arguments: arguments)
return
}
// Redirect stdout to stderr because swift-run clients usually want
// to ignore swiftpm's output and only care about the tool's output.
self.redirectStdoutToStderr()
if options.shouldBuildTests && !options.shouldBuild {
diagnostics.emit(.mutuallyExclusiveArgumentsError(arguments:
[buildTestsOptionName, skipBuildOptionName]))
return
}
let buildSystem = try createBuildSystem()
let productName = try findProductName(in: buildSystem.getPackageGraph())
if options.shouldBuildTests {
try buildSystem.build(subset: .allIncludingTests)
} else if options.shouldBuild {
try buildSystem.build(subset: .product(productName))
}
let executablePath = try self.buildParameters().buildPath.appending(component: productName)
try run(executablePath, arguments: options.arguments)
}
}
/// Returns the path to the correct executable based on options.
private func findProductName(in graph: PackageGraph) throws -> String {
if let executable = options.executable {
let executableExists = graph.allProducts.contains { $0.type == .executable && $0.name == executable }
guard executableExists else {
throw RunError.executableNotFound(executable)
}
return executable
}
// If the executable is implicit, search through root products.
let rootExecutables = graph.rootPackages
.flatMap { $0.products }
.filter { $0.type == .executable }
.map { $0.name }
// Error out if the package contains no executables.
guard rootExecutables.count > 0 else {
throw RunError.noExecutableFound
}
// Only implicitly deduce the executable if it is the only one.
guard rootExecutables.count == 1 else {
throw RunError.multipleExecutables(rootExecutables)
}
return rootExecutables[0]
}
/// Executes the executable at the specified path.
private func run(_ excutablePath: AbsolutePath, arguments: [String]) throws {
// Make sure we are running from the original working directory.
let cwd: AbsolutePath? = localFileSystem.currentWorkingDirectory
if cwd == nil || originalWorkingDirectory != cwd {
try ProcessEnv.chdir(originalWorkingDirectory)
}
let pathRelativeToWorkingDirectory = excutablePath.relative(to: originalWorkingDirectory)
try exec(path: excutablePath.pathString, args: [pathRelativeToWorkingDirectory.pathString] + arguments)
}
/// Determines if a path points to a valid swift file.
private func isValidSwiftFilePath(_ path: String) -> Bool {
guard path.hasSuffix(".swift") else { return false }
//FIXME: Return false when the path is not a valid path string.
let absolutePath: AbsolutePath
if path.first == "/" {
absolutePath = AbsolutePath(path)
} else {
guard let cwd = localFileSystem.currentWorkingDirectory else {
return false
}
absolutePath = AbsolutePath(cwd, path)
}
return localFileSystem.isFile(absolutePath)
}
override class func defineArguments(parser: ArgumentParser, binder: ArgumentBinder<RunToolOptions>) {
binder.bind(
option: parser.add(option: skipBuildOptionName, kind: Bool.self,
usage: "Skip building the executable product"),
to: { $0.shouldBuild = !$1 })
binder.bind(
option: parser.add(option: buildTestsOptionName, kind: Bool.self,
usage: "Build both source and test targets"),
to: { $0.shouldBuildTests = $1 })
binder.bindArray(
positional: parser.add(
positional: "executable", kind: [String].self, optional: true, strategy: .remaining,
usage: "The executable to run", completion: .function("_swift_executable")),
to: {
$0.executable = $1.first!
$0.arguments = Array($1.dropFirst())
})
binder.bind(
option: parser.add(option: "--repl", kind: Bool.self,
usage: "Launch Swift REPL for the package"),
to: { $0.shouldLaunchREPL = $1 })
}
}
fileprivate let buildTestsOptionName = "--build-tests"
fileprivate let skipBuildOptionName = "--skip-build"
extension SwiftRunTool: ToolName {
static var toolName: String {
return "swift run"
}
}
private extension Diagnostic.Message {
static var runFileDeprecation: Diagnostic.Message {
.warning("'swift run file.swift' command to interpret swift files is deprecated; use 'swift file.swift' instead")
}
}
| 36.678431 | 121 | 0.630814 |
f8ea56a996fd2cfe2c96e9def4c2915f6d5b57d3 | 4,176 | // Copyright 2018-2021 Amazon.com, Inc. or its affiliates. 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.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file 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.
//
// OperationHandler+withContextInputNoOutput.swift
// SmokeOperations
//
#if (os(Linux) && compiler(>=5.5)) || (!os(Linux) && compiler(>=5.5.2)) && canImport(_Concurrency)
import Foundation
import Logging
public extension OperationHandler {
/**
Initializer for async operation handler that has input returns
a result with an empty body.
- Parameters:
- inputProvider: function that obtains the input from the request.
- operation: the handler method for the operation.
- allowedErrors: the errors that can be serialized as responses
from the operation and their error codes.
- operationDelegate: optionally an operation-specific delegate to use when
handling the operation.
*/
init<InputType: Validatable, ErrorType: ErrorIdentifiableByDescription, OperationDelegateType: OperationDelegate>(
serverName: String, operationIdentifer: OperationIdentifer, reportingConfiguration: SmokeReportingConfiguration<OperationIdentifer>,
inputProvider: @escaping (OperationDelegateType.RequestHeadType, Data?) throws -> InputType,
operation: @escaping ((InputType, ContextType, InvocationReportingType) async throws -> ()),
allowedErrors: [(ErrorType, Int)],
operationDelegate: OperationDelegateType)
where RequestHeadType == OperationDelegateType.RequestHeadType,
InvocationReportingType == OperationDelegateType.InvocationReportingType,
ResponseHandlerType == OperationDelegateType.ResponseHandlerType {
/**
* The wrapped input handler takes the provided operation handler and wraps it so that if it
* returns, the responseHandler is called to indicate success. If the provided operation
* throws an error, the responseHandler is called with that error.
*/
func wrappedInputHandler(input: InputType, requestHead: RequestHeadType, context: ContextType,
responseHandler: ResponseHandlerType,
invocationContext: SmokeInvocationContext<InvocationReportingType>) {
Task {
let handlerResult: NoOutputOperationHandlerResult<ErrorType>
do {
try await operation(input, context, invocationContext.invocationReporting)
handlerResult = .success
} catch let smokeReturnableError as SmokeReturnableError {
handlerResult = .smokeReturnableError(smokeReturnableError, allowedErrors)
} catch SmokeOperationsError.validationError(reason: let reason) {
handlerResult = .validationError(reason)
} catch {
handlerResult = .internalServerError(error)
}
OperationHandler.handleNoOutputOperationHandlerResult(
handlerResult: handlerResult,
operationDelegate: operationDelegate,
requestHead: requestHead,
responseHandler: responseHandler,
invocationContext: invocationContext)
}
}
self.init(serverName: serverName, operationIdentifer: operationIdentifer, reportingConfiguration: reportingConfiguration,
inputHandler: wrappedInputHandler,
inputProvider: inputProvider,
operationDelegate: operationDelegate,
ignoreInvocationStrategy: true)
}
}
#endif
| 48.55814 | 144 | 0.664511 |
03bdb1962876593c3164e577742976cf4c667dd9 | 450 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
enum S<T where T:T>:T.a.class A{enum B<T where B:C{func a
| 45 | 78 | 0.742222 |
296ac8d23cf96978e2005462d9389293caafdc67 | 6,800 | //
// UIIVewController + Extensions.swift
// CoreSwift
//
// Created by Валерий Мельников on 19.01.2021.
//
import Foundation
import UIKit
// MARK: - Properties UIViewController's (static)
extension UIViewController {
// MARK: - Static properties
struct Holder {
static var loaderAlert: UIAlertController = UIAlertController()
static var loadingIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
}
var loaderAlert: UIAlertController {
get {
return Holder.loaderAlert
}
set(newValue) {
Holder.loaderAlert = newValue
}
}
var loadingIndicator: UIActivityIndicatorView {
get {
return Holder.loadingIndicator
}
set(newValue) {
Holder.loadingIndicator = newValue
}
}
// MARK: - Actions
func showLoader(_ message: String) {
DispatchQueue.main.async { [weak self] in
guard let `self` = self else {
return
}
self.loaderAlert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
self.loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
self.loadingIndicator.hidesWhenStopped = true
self.loadingIndicator.style = .medium
self.loadingIndicator.startAnimating()
self.loaderAlert.view.addSubview(self.loadingIndicator)
self.present(self.loaderAlert, animated: true, completion: nil)
if #available(iOS 13.0, *) {
UIApplication.shared.windows.first?.isUserInteractionEnabled = false
} else {
UIApplication.shared.beginIgnoringInteractionEvents()
}
}
}
func hideLoader() {
DispatchQueue.main.async { [weak self] in
self?.loaderAlert.dismiss(animated: true, completion: nil)
self?.loadingIndicator.stopAnimating()
if #available(iOS 13.0, *) {
UIApplication.shared.windows.first?.isUserInteractionEnabled = true
} else {
UIApplication.shared.endIgnoringInteractionEvents()
}
}
}
func showEmptyView(_ message: String = "", imageName: String = "photo_image") {
if(emptyImageView == nil) {
_ = initEmptyImageView()
}
emptyImageView?.image = UIImage(named: imageName)
if(emptyLabel == nil) {
_ = initEmptyLabel()
}
let attrs = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 21)]
let boldString = NSAttributedString(string: message, attributes:attrs)
emptyLabel?.attributedText = boldString
emptyImageView?.isHidden = false
emptyLabel?.isHidden = false
view.bringSubviewToFront(emptyImageView!)
view.bringSubviewToFront(emptyLabel!)
}
func hideEmptyView() {
DispatchQueue.main.async { [weak self] in
self?.emptyImageView?.isHidden = true
self?.emptyLabel?.isHidden = true
}
}
}
fileprivate extension UIViewController {
// MARK: - Associated Keys
private struct AssociatedKeys {
static var kEmptyImageView = "key_emptyImageView"
static var kEmptyLabel = "key_emptyLabel"
}
private var emptyImageView: UIImageView? {
get {
guard let imgView = objc_getAssociatedObject(self, &AssociatedKeys.kEmptyImageView) as? UIImageView else {
return initEmptyImageView()
}
return imgView
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.kEmptyImageView, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
private var emptyLabel: UILabel? {
get {
guard let label = objc_getAssociatedObject(self, &AssociatedKeys.kEmptyLabel) as? UILabel else {
return initEmptyLabel()
}
return label
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.kEmptyLabel, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
// MARK: - Init dynamic properties
private func initEmptyImageView() -> UIImageView {
let _emptyImageView = UIImageView(frame: .init(origin: .zero, size: .init(width: 60, height: 60)))
_emptyImageView.contentMode = .scaleAspectFit
_emptyImageView.tintColor = .clear
_emptyImageView.image = UIImage(named: "empty_table")
_emptyImageView.center = view.center
// Add to view
view.addSubview(_emptyImageView)
_emptyImageView.translatesAutoresizingMaskIntoConstraints = false
_emptyImageView.widthAnchor.constraint(equalToConstant: 140).isActive = true
_emptyImageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
_emptyImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0).isActive = true
_emptyImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -(view.frame.size.height - view.frame.size.height * 0.8)).isActive = true
view.layoutIfNeeded()
// Remind
emptyImageView = _emptyImageView
return _emptyImageView
}
private func initEmptyLabel() -> UILabel {
let _emptyLabel = UILabel()
_emptyLabel.numberOfLines = 0
_emptyLabel.textColor = .darkText
_emptyLabel.textAlignment = .center
// Add to view
view.addSubview(_emptyLabel)
_emptyLabel.translatesAutoresizingMaskIntoConstraints = false
_emptyLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 21.0).isActive = true
_emptyLabel.heightAnchor.constraint(lessThanOrEqualToConstant: 140.0).isActive = true
_emptyLabel.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 16).isActive = true
_emptyLabel.trailingAnchor.constraint(greaterThanOrEqualTo: view.trailingAnchor, constant: 16).isActive = true
_emptyLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0).isActive = true
_emptyLabel.topAnchor.constraint(equalTo: emptyImageView!.bottomAnchor, constant: 16).isActive = true
view.layoutIfNeeded()
// Remind
emptyLabel = _emptyLabel
return _emptyLabel
}
}
| 33.333333 | 161 | 0.615 |
2f33ab67d38d6dd0e1607a3711475229f39137f1 | 1,210 | //
// ModalTransition.swift
// MovieGenreSuggestion
//
// Created by Saim Tanveer on 8.3.2022.
//
import UIKit
final class ModalTransition: NSObject {
var isAnimated: Bool = true
var modalTransitionStyle: UIModalTransitionStyle
var modalPresentationStyle: UIModalPresentationStyle
init(isAnimated: Bool = true,
modalTransitionStyle: UIModalTransitionStyle = .coverVertical,
modalPresentationStyle: UIModalPresentationStyle = .automatic) {
self.isAnimated = isAnimated
self.modalTransitionStyle = modalTransitionStyle
self.modalPresentationStyle = modalPresentationStyle
}
}
extension ModalTransition: Transition {
// MARK: - Transition
func open(_ viewController: UIViewController, from: UIViewController, completion: (() -> Void)?) {
viewController.modalPresentationStyle = modalPresentationStyle
viewController.modalTransitionStyle = modalTransitionStyle
from.present(viewController, animated: isAnimated, completion: completion)
}
func close(_ viewController: UIViewController, completion: (() -> Void)?) {
viewController.dismiss(animated: isAnimated, completion: completion)
}
}
| 32.702703 | 102 | 0.730579 |
200be4b9fb6f581fcf414866e4e1e22ddc5127e7 | 174 | //
// ListKit.swift
// ListKit
//
// Created by burt on 2021/09/16.
//
import Foundation
public enum ListKit {
public static let componentContentViewTag = Int.max
}
| 13.384615 | 55 | 0.683908 |
d6b7b179c8b2527a575a67853864f918afb74a34 | 165 | class Foo {
func foo(x: Int
// RUN: %sourcekitd-test -req=format -line=3 -length=1 %s | %FileCheck --strict-whitespace %s
// CHECK: key.sourcetext: " "
| 23.571429 | 93 | 0.618182 |
ab1d2dc6f338c4395d56177dc0ad66f87e27f0f4 | 580 | //
// UserDefaults.swift
// WeatherApp
//
// Created by Jack Wong on 10/17/19.
// Copyright © 2019 David Rifkin. All rights reserved.
//
import Foundation
class UserDefaultsWrapper {
static let manager = UserDefaultsWrapper()
func getSearchString() -> String? {
return UserDefaults.standard.value(forKey: searchStringKey) as? String
}
func store(searchString: String) {
UserDefaults.standard.set(searchString, forKey: searchStringKey)
}
private let searchStringKey = "searchStringKey"
private init() {}
}
| 21.481481 | 78 | 0.667241 |
ac73c9195390ed697137f7c59fab44b35601db28 | 258 | //
// PosterCell.swift
// Flix
//
// Created by Whitney Griffith on 9/9/18.
// Copyright © 2018 Whitney Griffith. All rights reserved.
//
import UIKit
class PosterCell: UICollectionViewCell {
@IBOutlet weak var posterImageView: UIImageView!
}
| 17.2 | 59 | 0.70155 |
395670bff4cf6a133ecc3081d0bc6cc187b1930f | 10,140 | //
// LinkedList.swift
// JasonKit-Foundation
//
// Created by 陆俊杰 on 2019/11/4.
// Copyright © 2019 iftech. All rights reserved.
//
import Foundation
public final class LinkedList<T> {
/// Linked List's Node Class Declaration
public class LinkedListNode<T> {
public var value: T
public var next: LinkedListNode?
public weak var previous: LinkedListNode?
public init(value: T) {
self.value = value
}
}
/// Typealiasing the node class to increase readability of code
public typealias Node = LinkedListNode<T>
/// The head of the Linked List
private(set) var head: Node?
/// Computed property to iterate through the linked list and return the last node in the list (if any)
public var last: Node? {
guard var node = head else {
return nil
}
while let next = node.next {
node = next
}
return node
}
/// Computed property to check if the linked list is empty
public var isEmpty: Bool {
return head == nil
}
/// Computed property to iterate through the linked list and return the total number of nodes
public var count: Int {
guard var node = head else {
return 0
}
var count = 1
while let next = node.next {
node = next
count += 1
}
return count
}
/// Default initializer
public init() {}
/// Subscript function to return the node at a specific index
///
/// - Parameter index: Integer value of the requested value's index
public subscript(index: Int) -> T {
let node = self.node(at: index)
return node.value
}
/// Function to return the node at a specific index. Crashes if index is out of bounds (0...self.count)
///
/// - Parameter index: Integer value of the node's index to be returned
/// - Returns: LinkedListNode
public func node(at index: Int) -> Node {
assert(head != nil, "List is empty")
assert(index >= 0, "index must be greater or equal to 0")
if index == 0 {
return head!
} else {
var node = head!.next
for _ in 1..<index {
node = node?.next
if node == nil {
break
}
}
assert(node != nil, "index is out of bounds.")
return node!
}
}
/// Append a value to the end of the list
///
/// - Parameter value: The data value to be appended
public func append(_ value: T) {
let newNode = Node(value: value)
append(newNode)
}
/// Append a copy of a LinkedListNode to the end of the list.
///
/// - Parameter node: The node containing the value to be appended
public func append(_ node: Node) {
let newNode = node
if let lastNode = last {
newNode.previous = lastNode
lastNode.next = newNode
} else {
head = newNode
}
}
/// Append a copy of a LinkedList to the end of the list.
///
/// - Parameter list: The list to be copied and appended.
public func append(_ list: LinkedList) {
var nodeToCopy = list.head
while let node = nodeToCopy {
append(node.value)
nodeToCopy = node.next
}
}
/// Insert a value at a specific index. Crashes if index is out of bounds (0...self.count)
///
/// - Parameters:
/// - value: The data value to be inserted
/// - index: Integer value of the index to be insterted at
public func insert(_ value: T, at index: Int) {
let newNode = Node(value: value)
insert(newNode, at: index)
}
/// Insert a copy of a node at a specific index. Crashes if index is out of bounds (0...self.count)
///
/// - Parameters:
/// - node: The node containing the value to be inserted
/// - index: Integer value of the index to be inserted at
public func insert(_ newNode: Node, at index: Int) {
if index == 0 {
newNode.next = head
head?.previous = newNode
head = newNode
} else {
let prev = node(at: index - 1)
let next = prev.next
newNode.previous = prev
newNode.next = next
next?.previous = newNode
prev.next = newNode
}
}
/// Insert a copy of a LinkedList at a specific index. Crashes if index is out of bounds (0...self.count)
///
/// - Parameters:
/// - list: The LinkedList to be copied and inserted
/// - index: Integer value of the index to be inserted at
public func insert(_ list: LinkedList, at index: Int) {
guard !list.isEmpty else { return }
if index == 0 {
list.last?.next = head
head = list.head
} else {
let prev = node(at: index - 1)
let next = prev.next
prev.next = list.head
list.head?.previous = prev
list.last?.next = next
next?.previous = list.last
}
}
/// Function to remove all nodes/value from the list
public func removeAll() {
head = nil
}
/// Function to remove a specific node.
///
/// - Parameter node: The node to be deleted
/// - Returns: The data value contained in the deleted node.
@discardableResult public func remove(node: Node) -> T {
let prev = node.previous
let next = node.next
if let prev = prev {
prev.next = next
} else {
head = next
}
next?.previous = prev
node.previous = nil
node.next = nil
return node.value
}
/// Function to remove the last node/value in the list. Crashes if the list is empty
///
/// - Returns: The data value contained in the deleted node.
@discardableResult public func removeLast() -> T {
assert(!isEmpty)
return remove(node: last!)
}
/// Function to remove a node/value at a specific index. Crashes if index is out of bounds (0...self.count)
///
/// - Parameter index: Integer value of the index of the node to be removed
/// - Returns: The data value contained in the deleted node
@discardableResult public func remove(at index: Int) -> T {
let node = self.node(at: index)
return remove(node: node)
}
}
//: End of the base class declarations & beginning of extensions' declarations:
// MARK: - Extension to enable the standard conversion of a list to String
extension LinkedList: CustomStringConvertible {
public var description: String {
var s = "["
var node = head
while let nd = node {
s += "\(nd.value)"
node = nd.next
if node != nil { s += ", " }
}
return s + "]"
}
}
// MARK: - Extension to add a 'reverse' function to the list
extension LinkedList {
public func reverse() {
var node = head
while let currentNode = node {
node = currentNode.next
swap(¤tNode.next, ¤tNode.previous)
head = currentNode
}
}
}
// MARK: - An extension with an implementation of 'map' & 'filter' functions
extension LinkedList {
public func map<U>(transform: (T) -> U) -> LinkedList<U> {
let result = LinkedList<U>()
var node = head
while let nd = node {
result.append(transform(nd.value))
node = nd.next
}
return result
}
public func filter(predicate: (T) -> Bool) -> LinkedList<T> {
let result = LinkedList<T>()
var node = head
while let nd = node {
if predicate(nd.value) {
result.append(nd.value)
}
node = nd.next
}
return result
}
}
// MARK: - Extension to enable initialization from an Array
extension LinkedList {
convenience init(array: Array<T>) {
self.init()
array.forEach { append($0) }
}
}
// MARK: - Extension to enable initialization from an Array Literal
extension LinkedList: ExpressibleByArrayLiteral {
public convenience init(arrayLiteral elements: T...) {
self.init()
elements.forEach { append($0) }
}
}
// MARK: - Collection
extension LinkedList: Collection {
public typealias Index = LinkedListIndex<T>
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
/// - Complexity: O(1)
public var startIndex: Index {
get {
return LinkedListIndex<T>(node: head, tag: 0)
}
}
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
/// - Complexity: O(n), where n is the number of elements in the list. This can be improved by keeping a reference
/// to the last node in the collection.
public var endIndex: Index {
get {
if let h = self.head {
return LinkedListIndex<T>(node: h, tag: count)
} else {
return LinkedListIndex<T>(node: nil, tag: startIndex.tag)
}
}
}
public subscript(position: Index) -> T {
get {
return position.node!.value
}
}
public func index(after idx: Index) -> Index {
return LinkedListIndex<T>(node: idx.node?.next, tag: idx.tag + 1)
}
}
// MARK: - Collection Index
/// Custom index type that contains a reference to the node at index 'tag'
public struct LinkedListIndex<T>: Comparable {
fileprivate let node: LinkedList<T>.LinkedListNode<T>?
fileprivate let tag: Int
public static func==<T>(lhs: LinkedListIndex<T>, rhs: LinkedListIndex<T>) -> Bool {
return (lhs.tag == rhs.tag)
}
public static func< <T>(lhs: LinkedListIndex<T>, rhs: LinkedListIndex<T>) -> Bool {
return (lhs.tag < rhs.tag)
}
}
| 28.971429 | 118 | 0.569132 |
abb3af8492bccbd44e55461eb4a3ed3c75d934a3 | 1,142 | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "FastaiNotebook_06_cuda",
products: [
.library(name: "FastaiNotebook_06_cuda", targets: ["FastaiNotebook_06_cuda"]),
],
dependencies: [
.package(path: "../FastaiNotebook_00_load_data"),
.package(path: "../FastaiNotebook_01_matmul"),
.package(path: "../FastaiNotebook_01a_fastai_layers"),
.package(path: "../FastaiNotebook_01c_array_differentiable"),
.package(path: "../FastaiNotebook_02_fully_connected"),
.package(path: "../FastaiNotebook_02a_why_sqrt5"),
.package(path: "../FastaiNotebook_03_minibatch_training"),
.package(path: "../FastaiNotebook_04_callbacks"),
.package(path: "../FastaiNotebook_05_anneal"),
.package(path: "../FastaiNotebook_05b_early_stopping"),
.package(url: "https://github.com/mxcl/Path.swift", from: "0.16.1"),
.package(url: "https://github.com/JustHTTP/Just", from: "0.7.1")
],
targets: [
.target(
name: "FastaiNotebook_06_cuda",
dependencies: ["Just", "Path"]),
]
)
| 39.37931 | 86 | 0.637478 |
f72f93796090bf6e7297b6ae107e680f753856dd | 55,555 | /* Copyright 2018 JDCLOUD.COM
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.
Redis Instance Order API
查询缓存Redis订单结果
OpenAPI spec version: v1
Contact:
NOTE: This class is auto generated by the jdcloud code generator program.
*/
import Foundation
import JDCloudSDKCore
import JDCloudSDKCommon
import JDCloudSDKCharge
/// 查询账户的缓存Redis配额信息
public class DescribeUserQuotaResult:NSObject,JdCloudResult
{
/// Quota
var quota:Quota?
public override init(){
super.init()
}
enum DescribeUserQuotaResultCodingKeys: String, CodingKey {
case quota
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeUserQuotaResultCodingKeys.self)
if decoderContainer.contains(.quota)
{
self.quota = try decoderContainer.decode(Quota?.self, forKey: .quota)
}
}
}
public extension DescribeUserQuotaResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeUserQuotaResultCodingKeys.self)
try encoderContainer.encode(quota, forKey: .quota)
}
}
public class DescribeUserQuotaResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:DescribeUserQuotaResult?;
enum DescribeUserQuotaResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeUserQuotaResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(DescribeUserQuotaResult?.self, forKey: .result) ?? nil
}
}
public extension DescribeUserQuotaResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeUserQuotaResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 查询账户的缓存Redis配额信息
public class DescribeUserQuotaRequest:JdCloudRequest
{
}
public class DescribeInstanceConfigResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:DescribeInstanceConfigResult?;
enum DescribeInstanceConfigResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeInstanceConfigResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(DescribeInstanceConfigResult?.self, forKey: .result) ?? nil
}
}
public extension DescribeInstanceConfigResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeInstanceConfigResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 修改缓存Redis实例的配置参数,支持部分参数修改
public class ModifyInstanceConfigRequest:JdCloudRequest
{
/// 要修改的配置参数名和参数值
var instanceConfig:[ConfigItem?]?
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,instanceConfig:[ConfigItem?]?,cacheInstanceId:String){
self.instanceConfig = instanceConfig
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum ModifyInstanceConfigRequestRequestCodingKeys: String, CodingKey {
case instanceConfig
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ModifyInstanceConfigRequestRequestCodingKeys.self)
try encoderContainer.encode(instanceConfig, forKey: .instanceConfig)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
/// 查询缓存Redis实例列表,可分页、可排序、可搜索、可过滤
public class DescribeCacheInstancesResult:NSObject,JdCloudResult
{
/// 分页后的实例列表
var cacheInstances:[CacheInstance?]?
/// 实例总数
var totalCount:Int?
public override init(){
super.init()
}
enum DescribeCacheInstancesResultCodingKeys: String, CodingKey {
case cacheInstances
case totalCount
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeCacheInstancesResultCodingKeys.self)
if decoderContainer.contains(.cacheInstances)
{
self.cacheInstances = try decoderContainer.decode([CacheInstance?]?.self, forKey: .cacheInstances)
}
if decoderContainer.contains(.totalCount)
{
self.totalCount = try decoderContainer.decode(Int?.self, forKey: .totalCount)
}
}
}
public extension DescribeCacheInstancesResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeCacheInstancesResultCodingKeys.self)
try encoderContainer.encode(cacheInstances, forKey: .cacheInstances)
try encoderContainer.encode(totalCount, forKey: .totalCount)
}
}
public class DescribeBackupsResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:DescribeBackupsResult?;
enum DescribeBackupsResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeBackupsResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(DescribeBackupsResult?.self, forKey: .result) ?? nil
}
}
public extension DescribeBackupsResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeBackupsResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 获取缓存Redis实例的备份文件临时下载地址
public class DescribeDownloadUrlResult:NSObject,JdCloudResult
{
/// 备份文件下载信息列表
var downloadUrls:[DownloadUrl?]?
public override init(){
super.init()
}
enum DescribeDownloadUrlResultCodingKeys: String, CodingKey {
case downloadUrls
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeDownloadUrlResultCodingKeys.self)
if decoderContainer.contains(.downloadUrls)
{
self.downloadUrls = try decoderContainer.decode([DownloadUrl?]?.self, forKey: .downloadUrls)
}
}
}
public extension DescribeDownloadUrlResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeDownloadUrlResultCodingKeys.self)
try encoderContainer.encode(downloadUrls, forKey: .downloadUrls)
}
}
/// 重置缓存Redis实例的密码,可为空
public class ResetCacheInstancePasswordResult:NSObject,JdCloudResult
{
}
/// 查询缓存Redis实例的自动备份策略
public class DescribeBackupPolicyRequest:JdCloudRequest
{
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,cacheInstanceId:String){
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum DescribeBackupPolicyRequestRequestCodingKeys: String, CodingKey {
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeBackupPolicyRequestRequestCodingKeys.self)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
public class ResetCacheInstancePasswordResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:ResetCacheInstancePasswordResult?;
enum ResetCacheInstancePasswordResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ResetCacheInstancePasswordResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(ResetCacheInstancePasswordResult?.self, forKey: .result) ?? nil
}
}
public extension ResetCacheInstancePasswordResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ResetCacheInstancePasswordResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
public class ModifyCacheInstanceAttributeResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:ModifyCacheInstanceAttributeResult?;
enum ModifyCacheInstanceAttributeResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ModifyCacheInstanceAttributeResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(ModifyCacheInstanceAttributeResult?.self, forKey: .result) ?? nil
}
}
public extension ModifyCacheInstanceAttributeResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ModifyCacheInstanceAttributeResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 创建并执行缓存Redis实例的备份任务,只能为手动备份,可设置备份文件名称
public class CreateBackupRequest:JdCloudRequest
{
/// 备份文件名称,只支持英文数字和下划线的组合,长度不超过32个字符
var fileName:String
/// 备份类型:手动备份为1,只能为手动备份
var backupType:Int
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,fileName:String,backupType:Int,cacheInstanceId:String){
self.fileName = fileName
self.backupType = backupType
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum CreateBackupRequestRequestCodingKeys: String, CodingKey {
case fileName
case backupType
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: CreateBackupRequestRequestCodingKeys.self)
try encoderContainer.encode(fileName, forKey: .fileName)
try encoderContainer.encode(backupType, forKey: .backupType)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
/// 查看缓存Redis实例的当前配置参数
public class DescribeInstanceConfigResult:NSObject,JdCloudResult
{
/// InstanceConfig
var instanceConfig:[ConfigItem?]?
public override init(){
super.init()
}
enum DescribeInstanceConfigResultCodingKeys: String, CodingKey {
case instanceConfig
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeInstanceConfigResultCodingKeys.self)
if decoderContainer.contains(.instanceConfig)
{
self.instanceConfig = try decoderContainer.decode([ConfigItem?]?.self, forKey: .instanceConfig)
}
}
}
public extension DescribeInstanceConfigResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeInstanceConfigResultCodingKeys.self)
try encoderContainer.encode(instanceConfig, forKey: .instanceConfig)
}
}
/// 创建并执行缓存Redis实例的备份任务,只能为手动备份,可设置备份文件名称
public class CreateBackupResult:NSObject,JdCloudResult
{
/// 本次备份任务ID,可用于查询本次备份任务的结果
var baseId:String?
public override init(){
super.init()
}
enum CreateBackupResultCodingKeys: String, CodingKey {
case baseId
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: CreateBackupResultCodingKeys.self)
if decoderContainer.contains(.baseId)
{
self.baseId = try decoderContainer.decode(String?.self, forKey: .baseId)
}
}
}
public extension CreateBackupResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: CreateBackupResultCodingKeys.self)
try encoderContainer.encode(baseId, forKey: .baseId)
}
}
/// 查询缓存Redis实例的自动备份策略
public class DescribeBackupPolicyResult:NSObject,JdCloudResult
{
/// 备份周期,包括:Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday,多个用逗号分隔
var backupPeriod:String?
/// 备份时间,格式为:HH:mm-HH:mm 时区,例如"01:00-02:00 +0800",表示东八区的1点到2点
var backupTime:String?
/// 下次自动备份时间段,ISO 8601标准的UTC时间,格式为:YYYY-MM-DDTHH:mm:ssZ~YYYY-MM-DDTHH:mm:ssZ
var nextBackupTime:String?
public override init(){
super.init()
}
enum DescribeBackupPolicyResultCodingKeys: String, CodingKey {
case backupPeriod
case backupTime
case nextBackupTime
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeBackupPolicyResultCodingKeys.self)
if decoderContainer.contains(.backupPeriod)
{
self.backupPeriod = try decoderContainer.decode(String?.self, forKey: .backupPeriod)
}
if decoderContainer.contains(.backupTime)
{
self.backupTime = try decoderContainer.decode(String?.self, forKey: .backupTime)
}
if decoderContainer.contains(.nextBackupTime)
{
self.nextBackupTime = try decoderContainer.decode(String?.self, forKey: .nextBackupTime)
}
}
}
public extension DescribeBackupPolicyResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeBackupPolicyResultCodingKeys.self)
try encoderContainer.encode(backupPeriod, forKey: .backupPeriod)
try encoderContainer.encode(backupTime, forKey: .backupTime)
try encoderContainer.encode(nextBackupTime, forKey: .nextBackupTime)
}
}
/// 修改缓存Redis实例的资源名称或描述,二者至少选一
public class ModifyCacheInstanceAttributeResult:NSObject,JdCloudResult
{
}
public class ModifyBackupPolicyResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:ModifyBackupPolicyResult?;
enum ModifyBackupPolicyResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ModifyBackupPolicyResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(ModifyBackupPolicyResult?.self, forKey: .result) ?? nil
}
}
public extension ModifyBackupPolicyResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ModifyBackupPolicyResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 修改缓存Redis实例的资源名称或描述,二者至少选一
public class ModifyCacheInstanceAttributeRequest:JdCloudRequest
{
/// 实例的名称,名称只支持数字、字母、英文下划线、中文,且不少于2字符不超过32字符
var cacheInstanceName:String?
/// 实例的描述,不能超过256个字符
var cacheInstanceDescription:String?
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,cacheInstanceId:String){
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum ModifyCacheInstanceAttributeRequestRequestCodingKeys: String, CodingKey {
case cacheInstanceName
case cacheInstanceDescription
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ModifyCacheInstanceAttributeRequestRequestCodingKeys.self)
try encoderContainer.encode(cacheInstanceName, forKey: .cacheInstanceName)
try encoderContainer.encode(cacheInstanceDescription, forKey: .cacheInstanceDescription)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
public class DescribeDownloadUrlResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:DescribeDownloadUrlResult?;
enum DescribeDownloadUrlResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeDownloadUrlResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(DescribeDownloadUrlResult?.self, forKey: .result) ?? nil
}
}
public extension DescribeDownloadUrlResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeDownloadUrlResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
public class RestoreInstanceResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:RestoreInstanceResult?;
enum RestoreInstanceResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: RestoreInstanceResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(RestoreInstanceResult?.self, forKey: .result) ?? nil
}
}
public extension RestoreInstanceResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: RestoreInstanceResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
public class DescribeClusterInfoResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:DescribeClusterInfoResult?;
enum DescribeClusterInfoResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeClusterInfoResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(DescribeClusterInfoResult?.self, forKey: .result) ?? nil
}
}
public extension DescribeClusterInfoResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeClusterInfoResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 获取缓存Redis实例的慢查询日志
public class DescribeSlowLogRequest:JdCloudRequest
{
/// 页码;默认为1
var pageNumber:Int?
/// 分页大小;默认为10;取值范围[10, 100]
var pageSize:Int?
/// 开始时间
var startTime:String?
/// 结束时间
var endTime:String?
/// 分片id
var shardId:String?
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,cacheInstanceId:String){
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum DescribeSlowLogRequestRequestCodingKeys: String, CodingKey {
case pageNumber
case pageSize
case startTime
case endTime
case shardId
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeSlowLogRequestRequestCodingKeys.self)
try encoderContainer.encode(pageNumber, forKey: .pageNumber)
try encoderContainer.encode(pageSize, forKey: .pageSize)
try encoderContainer.encode(startTime, forKey: .startTime)
try encoderContainer.encode(endTime, forKey: .endTime)
try encoderContainer.encode(shardId, forKey: .shardId)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
/// 重置缓存Redis实例的密码,可为空
public class ResetCacheInstancePasswordRequest:JdCloudRequest
{
/// 密码,为空即为免密,不少于8字符不超过16字符
var password:String?
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,cacheInstanceId:String){
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum ResetCacheInstancePasswordRequestRequestCodingKeys: String, CodingKey {
case password
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ResetCacheInstancePasswordRequestRequestCodingKeys.self)
try encoderContainer.encode(password, forKey: .password)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
/// 查询缓存Redis实例的备份结果(备份文件列表),可分页、可指定起止时间或备份任务ID
public class DescribeBackupsRequest:JdCloudRequest
{
/// 页码;默认为1
var pageNumber:Int?
/// 分页大小;默认为10;取值范围[10, 100]
var pageSize:Int?
/// 开始时间
var startTime:String?
/// 结束时间
var endTime:String?
/// 备份任务ID
var baseId:String?
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,cacheInstanceId:String){
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum DescribeBackupsRequestRequestCodingKeys: String, CodingKey {
case pageNumber
case pageSize
case startTime
case endTime
case baseId
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeBackupsRequestRequestCodingKeys.self)
try encoderContainer.encode(pageNumber, forKey: .pageNumber)
try encoderContainer.encode(pageSize, forKey: .pageSize)
try encoderContainer.encode(startTime, forKey: .startTime)
try encoderContainer.encode(endTime, forKey: .endTime)
try encoderContainer.encode(baseId, forKey: .baseId)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
/// 删除按配置计费、或包年包月已到期的缓存Redis实例,包年包月未到期不可删除。
/// /// 只有处于运行running或者错误error状态才可以删除,其余状态不可以删除。
/// /// 白名单用户不能删除包年包月已到期的缓存Redis实例。
/// ///
public class DeleteCacheInstanceRequest:JdCloudRequest
{
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,cacheInstanceId:String){
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum DeleteCacheInstanceRequestRequestCodingKeys: String, CodingKey {
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DeleteCacheInstanceRequestRequestCodingKeys.self)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
public class DescribeCacheInstancesResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:DescribeCacheInstancesResult?;
enum DescribeCacheInstancesResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeCacheInstancesResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(DescribeCacheInstancesResult?.self, forKey: .result) ?? nil
}
}
public extension DescribeCacheInstancesResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeCacheInstancesResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
public class CreateBackupResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:CreateBackupResult?;
enum CreateBackupResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: CreateBackupResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(CreateBackupResult?.self, forKey: .result) ?? nil
}
}
public extension CreateBackupResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: CreateBackupResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 查询Redis实例的集群内部信息
public class DescribeClusterInfoRequest:JdCloudRequest
{
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,cacheInstanceId:String){
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum DescribeClusterInfoRequestRequestCodingKeys: String, CodingKey {
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeClusterInfoRequestRequestCodingKeys.self)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
/// 修改缓存Redis实例的自动备份策略,可修改备份周期和备份时间
public class ModifyBackupPolicyRequest:JdCloudRequest
{
/// 备份时间,格式为:HH:mm-HH:mm 时区,例如"01:00-02:00 +0800",表示东八区的1点到2点
var backupTime:String
/// 备份周期,包括:Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday,多个用逗号分隔
var backupPeriod:String
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,backupTime:String,backupPeriod:String,cacheInstanceId:String){
self.backupTime = backupTime
self.backupPeriod = backupPeriod
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum ModifyBackupPolicyRequestRequestCodingKeys: String, CodingKey {
case backupTime
case backupPeriod
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ModifyBackupPolicyRequestRequestCodingKeys.self)
try encoderContainer.encode(backupTime, forKey: .backupTime)
try encoderContainer.encode(backupPeriod, forKey: .backupPeriod)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
public class CreateCacheInstanceResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:CreateCacheInstanceResult?;
enum CreateCacheInstanceResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: CreateCacheInstanceResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(CreateCacheInstanceResult?.self, forKey: .result) ?? nil
}
}
public extension CreateCacheInstanceResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: CreateCacheInstanceResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
public class ModifyCacheInstanceClassResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:ModifyCacheInstanceClassResult?;
enum ModifyCacheInstanceClassResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ModifyCacheInstanceClassResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(ModifyCacheInstanceClassResult?.self, forKey: .result) ?? nil
}
}
public extension ModifyCacheInstanceClassResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ModifyCacheInstanceClassResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 创建一个指定配置的缓存Redis实例:可选择主从版或集群版,每种类型又分为多种规格(按CPU核数、内存容量、磁盘容量、带宽等划分),具体可参考产品规格代码,https://docs.jdcloud.com/cn/jcs-for-redis/specifications
/// ///
public class CreateCacheInstanceResult:NSObject,JdCloudResult
{
/// 实例ID
var cacheInstanceId:String?
/// 订单编号
var orderNum:String?
public override init(){
super.init()
}
enum CreateCacheInstanceResultCodingKeys: String, CodingKey {
case cacheInstanceId
case orderNum
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: CreateCacheInstanceResultCodingKeys.self)
if decoderContainer.contains(.cacheInstanceId)
{
self.cacheInstanceId = try decoderContainer.decode(String?.self, forKey: .cacheInstanceId)
}
if decoderContainer.contains(.orderNum)
{
self.orderNum = try decoderContainer.decode(String?.self, forKey: .orderNum)
}
}
}
public extension CreateCacheInstanceResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: CreateCacheInstanceResultCodingKeys.self)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
try encoderContainer.encode(orderNum, forKey: .orderNum)
}
}
/// 恢复缓存Redis实例的某次备份
public class RestoreInstanceResult:NSObject,JdCloudResult
{
}
/// 创建一个指定配置的缓存Redis实例:可选择主从版或集群版,每种类型又分为多种规格(按CPU核数、内存容量、磁盘容量、带宽等划分),具体可参考产品规格代码,https://docs.jdcloud.com/cn/jcs-for-redis/specifications
/// ///
public class CreateCacheInstanceRequest:JdCloudRequest
{
/// 创建实例时指定的信息
var cacheInstance:CacheInstanceSpec
/// 实例的计费类型
var charge:ChargeSpec?
public init(regionId: String,cacheInstance:CacheInstanceSpec){
self.cacheInstance = cacheInstance
super.init(regionId: regionId)
}
enum CreateCacheInstanceRequestRequestCodingKeys: String, CodingKey {
case cacheInstance
case charge
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: CreateCacheInstanceRequestRequestCodingKeys.self)
try encoderContainer.encode(cacheInstance, forKey: .cacheInstance)
try encoderContainer.encode(charge, forKey: .charge)
}
}
/// 变更缓存Redis实例规格(变配),只能变更运行状态的实例规格,变更的规格不能与之前的相同。
/// /// 预付费用户,从集群版变配到主从版,新规格的内存大小要大于老规格的内存大小,从主从版到集群版,新规格的内存大小要不小于老规格的内存大小。
/// ///
public class ModifyCacheInstanceClassRequest:JdCloudRequest
{
/// 变更后的实例规格
var cacheInstanceClass:String
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,cacheInstanceClass:String,cacheInstanceId:String){
self.cacheInstanceClass = cacheInstanceClass
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum ModifyCacheInstanceClassRequestRequestCodingKeys: String, CodingKey {
case cacheInstanceClass
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ModifyCacheInstanceClassRequestRequestCodingKeys.self)
try encoderContainer.encode(cacheInstanceClass, forKey: .cacheInstanceClass)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
/// 查询缓存Redis实例列表,可分页、可排序、可搜索、可过滤
public class DescribeCacheInstancesRequest:JdCloudRequest
{
/// 页码:取值范围[1,∞),默认为1
var pageNumber:Int?
/// 分页大小:取值范围[10, 100],默认为10
var pageSize:Int?
/// 过滤属性:
/// cacheInstanceId - 实例Id,精确匹配,可选择多个
/// cacheInstanceName - 实例名称,模糊匹配
/// cacheInstanceStatus - 实例状态,精确匹配,可选择多个(running:运行中,error:错误,creating:创建中,changing:变配中,configuring:参数修改中,restoring:备份恢复中,deleting:删除中)
/// redisVersion - redis引擎版本,精确匹配,可选择2.8和4.0
/// instanceType - 实例类型,精确匹配(redis表示主从版,redis_cluster表示集群版)
/// chargeMode - 计费类型,精确匹配(prepaid_by_duration表示包年包月预付费,postpaid_by_duration表示按配置后付费)
///
var filters:[Filter?]?
/// 排序属性:
/// createTime - 按创建时间排序(asc表示按时间正序,desc表示按时间倒序)
///
var sorts:[Sort?]?
/// 标签的过滤条件
var tagFilters:[TagFilter?]?
enum DescribeCacheInstancesRequestRequestCodingKeys: String, CodingKey {
case pageNumber
case pageSize
case filters
case sorts
case tagFilters
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeCacheInstancesRequestRequestCodingKeys.self)
try encoderContainer.encode(pageNumber, forKey: .pageNumber)
try encoderContainer.encode(pageSize, forKey: .pageSize)
try encoderContainer.encode(filters, forKey: .filters)
try encoderContainer.encode(sorts, forKey: .sorts)
try encoderContainer.encode(tagFilters, forKey: .tagFilters)
}
}
/// 修改缓存Redis实例的自动备份策略,可修改备份周期和备份时间
public class ModifyBackupPolicyResult:NSObject,JdCloudResult
{
}
public class DescribeSlowLogResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:DescribeSlowLogResult?;
enum DescribeSlowLogResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeSlowLogResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(DescribeSlowLogResult?.self, forKey: .result) ?? nil
}
}
public extension DescribeSlowLogResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeSlowLogResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
public class DeleteCacheInstanceResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:DeleteCacheInstanceResult?;
enum DeleteCacheInstanceResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DeleteCacheInstanceResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(DeleteCacheInstanceResult?.self, forKey: .result) ?? nil
}
}
public extension DeleteCacheInstanceResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DeleteCacheInstanceResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 查看缓存Redis实例的当前配置参数
public class DescribeInstanceConfigRequest:JdCloudRequest
{
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,cacheInstanceId:String){
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum DescribeInstanceConfigRequestRequestCodingKeys: String, CodingKey {
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeInstanceConfigRequestRequestCodingKeys.self)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
/// 查询缓存Redis实例的备份结果(备份文件列表),可分页、可指定起止时间或备份任务ID
public class DescribeBackupsResult:NSObject,JdCloudResult
{
/// 备份结果(备份文件)列表
var backups:[Backup?]?
/// 备份结果总数
var totalCount:Int?
public override init(){
super.init()
}
enum DescribeBackupsResultCodingKeys: String, CodingKey {
case backups
case totalCount
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeBackupsResultCodingKeys.self)
if decoderContainer.contains(.backups)
{
self.backups = try decoderContainer.decode([Backup?]?.self, forKey: .backups)
}
if decoderContainer.contains(.totalCount)
{
self.totalCount = try decoderContainer.decode(Int?.self, forKey: .totalCount)
}
}
}
public extension DescribeBackupsResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeBackupsResultCodingKeys.self)
try encoderContainer.encode(backups, forKey: .backups)
try encoderContainer.encode(totalCount, forKey: .totalCount)
}
}
public class DescribeBackupPolicyResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:DescribeBackupPolicyResult?;
enum DescribeBackupPolicyResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeBackupPolicyResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(DescribeBackupPolicyResult?.self, forKey: .result) ?? nil
}
}
public extension DescribeBackupPolicyResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeBackupPolicyResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
public class DescribeCacheInstanceResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:DescribeCacheInstanceResult?;
enum DescribeCacheInstanceResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeCacheInstanceResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(DescribeCacheInstanceResult?.self, forKey: .result) ?? nil
}
}
public extension DescribeCacheInstanceResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeCacheInstanceResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 删除按配置计费、或包年包月已到期的缓存Redis实例,包年包月未到期不可删除。
/// /// 只有处于运行running或者错误error状态才可以删除,其余状态不可以删除。
/// /// 白名单用户不能删除包年包月已到期的缓存Redis实例。
/// ///
public class DeleteCacheInstanceResult:NSObject,JdCloudResult
{
}
/// 修改缓存Redis实例的配置参数,支持部分参数修改
public class ModifyInstanceConfigResult:NSObject,JdCloudResult
{
}
public class ModifyInstanceConfigResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:ModifyInstanceConfigResult?;
enum ModifyInstanceConfigResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ModifyInstanceConfigResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(ModifyInstanceConfigResult?.self, forKey: .result) ?? nil
}
}
public extension ModifyInstanceConfigResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ModifyInstanceConfigResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 获取缓存Redis实例的慢查询日志
public class DescribeSlowLogResult:NSObject,JdCloudResult
{
/// 该页的慢查询日志列表
var slowLogs:[SlowLog?]?
/// 慢查询日志总条数
var totalCount:Int?
public override init(){
super.init()
}
enum DescribeSlowLogResultCodingKeys: String, CodingKey {
case slowLogs
case totalCount
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeSlowLogResultCodingKeys.self)
if decoderContainer.contains(.slowLogs)
{
self.slowLogs = try decoderContainer.decode([SlowLog?]?.self, forKey: .slowLogs)
}
if decoderContainer.contains(.totalCount)
{
self.totalCount = try decoderContainer.decode(Int?.self, forKey: .totalCount)
}
}
}
public extension DescribeSlowLogResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeSlowLogResultCodingKeys.self)
try encoderContainer.encode(slowLogs, forKey: .slowLogs)
try encoderContainer.encode(totalCount, forKey: .totalCount)
}
}
/// 获取缓存Redis实例的备份文件临时下载地址
public class DescribeDownloadUrlRequest:JdCloudRequest
{
/// 备份任务ID
var baseId:String
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,baseId:String,cacheInstanceId:String){
self.baseId = baseId
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum DescribeDownloadUrlRequestRequestCodingKeys: String, CodingKey {
case baseId
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeDownloadUrlRequestRequestCodingKeys.self)
try encoderContainer.encode(baseId, forKey: .baseId)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
/// 变更缓存Redis实例规格(变配),只能变更运行状态的实例规格,变更的规格不能与之前的相同。
/// /// 预付费用户,从集群版变配到主从版,新规格的内存大小要大于老规格的内存大小,从主从版到集群版,新规格的内存大小要不小于老规格的内存大小。
/// ///
public class ModifyCacheInstanceClassResult:NSObject,JdCloudResult
{
/// 本次变更请求的订单编号
var orderNum:String?
public override init(){
super.init()
}
enum ModifyCacheInstanceClassResultCodingKeys: String, CodingKey {
case orderNum
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ModifyCacheInstanceClassResultCodingKeys.self)
if decoderContainer.contains(.orderNum)
{
self.orderNum = try decoderContainer.decode(String?.self, forKey: .orderNum)
}
}
}
public extension ModifyCacheInstanceClassResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ModifyCacheInstanceClassResultCodingKeys.self)
try encoderContainer.encode(orderNum, forKey: .orderNum)
}
}
/// 查询缓存Redis实例的详细信息
public class DescribeCacheInstanceResult:NSObject,JdCloudResult
{
/// 该实例的详细信息
var cacheInstance:CacheInstance?
public override init(){
super.init()
}
enum DescribeCacheInstanceResultCodingKeys: String, CodingKey {
case cacheInstance
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeCacheInstanceResultCodingKeys.self)
if decoderContainer.contains(.cacheInstance)
{
self.cacheInstance = try decoderContainer.decode(CacheInstance?.self, forKey: .cacheInstance)
}
}
}
public extension DescribeCacheInstanceResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeCacheInstanceResultCodingKeys.self)
try encoderContainer.encode(cacheInstance, forKey: .cacheInstance)
}
}
/// 恢复缓存Redis实例的某次备份
public class RestoreInstanceRequest:JdCloudRequest
{
/// 备份任务ID
var baseId:String
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,baseId:String,cacheInstanceId:String){
self.baseId = baseId
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum RestoreInstanceRequestRequestCodingKeys: String, CodingKey {
case baseId
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: RestoreInstanceRequestRequestCodingKeys.self)
try encoderContainer.encode(baseId, forKey: .baseId)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
/// 查询Redis实例的集群内部信息
public class DescribeClusterInfoResult:NSObject,JdCloudResult
{
/// 集群内部信息
var info:ClusterInfo?
public override init(){
super.init()
}
enum DescribeClusterInfoResultCodingKeys: String, CodingKey {
case info
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeClusterInfoResultCodingKeys.self)
if decoderContainer.contains(.info)
{
self.info = try decoderContainer.decode(ClusterInfo?.self, forKey: .info)
}
}
}
public extension DescribeClusterInfoResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeClusterInfoResultCodingKeys.self)
try encoderContainer.encode(info, forKey: .info)
}
}
/// 查询缓存Redis实例的详细信息
public class DescribeCacheInstanceRequest:JdCloudRequest
{
/// 缓存Redis实例ID,是访问实例的唯一标识
var cacheInstanceId:String
public init(regionId: String,cacheInstanceId:String){
self.cacheInstanceId = cacheInstanceId
super.init(regionId: regionId)
}
enum DescribeCacheInstanceRequestRequestCodingKeys: String, CodingKey {
case cacheInstanceId
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeCacheInstanceRequestRequestCodingKeys.self)
try encoderContainer.encode(cacheInstanceId, forKey: .cacheInstanceId)
}
}
/// 查询某区域下的缓存Redis实例规格列表
public class DescribeInstanceClassResult:NSObject,JdCloudResult
{
/// InstanceClasses
var instanceClasses:[InstanceClass?]?
/// TotalCount
var totalCount:Int?
public override init(){
super.init()
}
enum DescribeInstanceClassResultCodingKeys: String, CodingKey {
case instanceClasses
case totalCount
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeInstanceClassResultCodingKeys.self)
if decoderContainer.contains(.instanceClasses)
{
self.instanceClasses = try decoderContainer.decode([InstanceClass?]?.self, forKey: .instanceClasses)
}
if decoderContainer.contains(.totalCount)
{
self.totalCount = try decoderContainer.decode(Int?.self, forKey: .totalCount)
}
}
}
public extension DescribeInstanceClassResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeInstanceClassResultCodingKeys.self)
try encoderContainer.encode(instanceClasses, forKey: .instanceClasses)
try encoderContainer.encode(totalCount, forKey: .totalCount)
}
}
public class DescribeInstanceClassResponse:NSObject,Codable
{
var requestId:String?;
var error:ServiceError?;
var result:DescribeInstanceClassResult?;
enum DescribeInstanceClassResponseCodingKeys: String, CodingKey {
case requestId
case error
case result
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: DescribeInstanceClassResponseCodingKeys.self)
self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil
self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil
self.result = try decoderContainer.decodeIfPresent(DescribeInstanceClassResult?.self, forKey: .result) ?? nil
}
}
public extension DescribeInstanceClassResponse{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeInstanceClassResponseCodingKeys.self)
try encoderContainer.encode(requestId, forKey: .requestId)
try encoderContainer.encode(error, forKey: .error)
try encoderContainer.encode(result, forKey: .result)
}
}
/// 查询某区域下的缓存Redis实例规格列表
public class DescribeInstanceClassRequest:JdCloudRequest
{
/// 缓存Redis的版本号:目前有2.8和4.0,默认为2.8
var redisVersion:String?
enum DescribeInstanceClassRequestRequestCodingKeys: String, CodingKey {
case redisVersion
}
public override func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: DescribeInstanceClassRequestRequestCodingKeys.self)
try encoderContainer.encode(redisVersion, forKey: .redisVersion)
}
}
| 32.989905 | 142 | 0.720673 |
bf4f6bd8649e2da951c4bcf48947d77a13bc07b7 | 1,425 | //
// ViewController.swift
// XML
//
// Created by Craig Grummitt on 24/08/2016.
// Copyright © 2016 interactivecoconut. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Import an XML document
guard let url = Bundle.main.url(forResource: "books", withExtension: "xml") else { return }
guard let xml = XML(contentsOf: url) else { return }
//Create an XML Node
let bookNode = XMLNode(name:"book")
//Add child node with name and value
bookNode.addChild(name: "title", value: "Robinson Crusoe")
bookNode.addChild(name: "author", value: "Daniel Defoe")
//Add attributes to node
bookNode.attributes["isbn"] = "9789835004100"
//Add child node with node
xml[0].addChild(bookNode)
//Remove child from XML
xml[0].removeChild(at: 1)
//Set with subscripts
xml[0][0]["title"]?.text = "Great Expectations"
xml[0][0].attributes["isbn"] = "38"
//Get title node and isbn attribute of first book node:
guard let title = xml[0][0]["title"]?.text,
let isbn = xml[0][0].attributes["isbn"] else {return}
print("\(title) with isbn of \(isbn)")
//Print XML structure
print(xml)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 29.081633 | 96 | 0.645614 |
9c5e3f945f1362104ddffcb9ecee720b8ddbbded | 1,488 | // Copyright 2020 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.
import Foundation
/// Runs basic tokenization such as punctuation spliting, lower casing.
///
/// Name of functions and variables are from
/// [google-research/bert]( https://github.com/google-research/bert/blob/d66a146741588fb208450bde15aa7db143baaa69/tokenization.py#L185).
struct BasicTokenizer {
let isCaseInsensitive: Bool
/// Constructs a BasicTokenizer.
///
/// - Parameter isCaseInsensitive: Whether to lower case the input.
init(isCaseInsensitive: Bool) {
self.isCaseInsensitive = isCaseInsensitive
}
/// Tokenizes a piece of text.
///
/// - Parameter text: Text to be tokenized.
func tokenize(_ text: String) -> [String] {
var cleanedText = text.cleaned()
if isCaseInsensitive {
cleanedText = cleanedText.lowercased()
}
return cleanedText.splitByWhitespace().flatMap { $0.tokenizedWithPunctuation() }
}
}
| 34.604651 | 136 | 0.733199 |
2f2771199e4a7bee5c37d136b1c83206cb17237a | 907 | // MIT license. Copyright (c) 2020 Simon Strandgaard. All rights reserved.
import Foundation
public class MeasureAreaSize {
public class func compute(positionArray: [IntVec2], startPosition: IntVec2) -> UInt {
return compute(
positionSet: Set<IntVec2>(positionArray),
startPosition: startPosition
)
}
public class func compute(positionSet: Set<IntVec2>, startPosition: IntVec2) -> UInt {
var unvisited: Set<IntVec2> = positionSet
var fillCount: UInt = 0
func compute(position: IntVec2) {
guard unvisited.contains(position) else {
return
}
unvisited.remove(position)
fillCount += 1
compute(position: position.offsetBy(dx: -1, dy: 0))
compute(position: position.offsetBy(dx: 1, dy: 0))
compute(position: position.offsetBy(dx: 0, dy: -1))
compute(position: position.offsetBy(dx: 0, dy: 1))
}
compute(position: startPosition)
return UInt(fillCount)
}
}
| 28.34375 | 87 | 0.715546 |
1697a139844c185d1f1b0b6168cfe6b5abb695a5 | 9,047 | import UIKit
import MetalKit
import PHAssetPicker
import SnapKit
import MetalView
import Alloy
import Photos
import MetalPerformanceShaders
class ViewController: UIViewController {
private var metalView: MetalView!
private var context: MTLContext!
private var textureFlip: TextureFlip!
private var textureCopy: TextureCopy!
private var chooseImageButton: UIButton!
private var flipTextureButton: UIButton!
private var shareImageButton: UIButton!
private var assetPickerController: PHAssetPickerController!
private var imageManager: PHImageManager!
private var imageRequestOptions: PHImageRequestOptions!
private var texture: MTLTexture!
init() {
super.init(nibName: nil,
bundle: nil)
self.setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.redraw()
}
// MARK: - Setup
private func setup() {
do {
self.context = try .init()
self.metalView = try .init(context: self.context)
self.textureFlip = try .init(library: self.context
.library(for: TextureFlip.self))
self.textureCopy = try .init(context: self.context)
self.chooseImageButton = .init(type: .roundedRect)
self.flipTextureButton = .init(type: .roundedRect)
self.flipTextureButton.accessibilityIdentifier = "FlipTextureButton"
self.shareImageButton = .init(type: .roundedRect)
self.assetPickerController = .init()
self.assetPickerController
.configuration
.selection
.max = 1
self.imageManager = .init()
self.imageRequestOptions = .init()
self.imageRequestOptions
.isNetworkAccessAllowed = true
self.imageRequestOptions
.deliveryMode = .highQualityFormat
self.imageRequestOptions
.resizeMode = .exact
self.imageRequestOptions
.version = .current
self.draw(image: Asset.image.image)
self.setupUI()
} catch {
fatalError(error.localizedDescription)
}
}
private func setupUI() {
self.view
.backgroundColor = .systemBackground
// MetalView
self.view
.addSubview(self.metalView)
self.metalView
.layer
.cornerRadius = 10
self.metalView
.layer
.masksToBounds = true
self.metalView
.snp
.makeConstraints { constraintMaker in
constraintMaker.top
.equalToSuperview()
.inset(40)
constraintMaker.bottom
.equalToSuperview()
.inset(120)
constraintMaker.trailing
.leading
.equalToSuperview()
}
// chooseImageButton
self.view
.addSubview(self.chooseImageButton)
self.chooseImageButton
.setImage(Asset.gallery.image,
for: .normal)
self.chooseImageButton
.tintColor = .label
self.chooseImageButton
.addTarget(self,
action: #selector(self.chooseImage),
for: .touchUpInside)
self.chooseImageButton
.snp
.makeConstraints { constraintMaker in
constraintMaker.width
.equalTo(54)
constraintMaker.height
.equalTo(40)
constraintMaker.bottom
.equalToSuperview()
.inset(60)
constraintMaker.leading
.equalToSuperview()
.inset(20)
}
// flipTextureButton
self.view
.addSubview(self.flipTextureButton)
self.flipTextureButton
.setImage(Asset.flip.image,
for: .normal)
self.flipTextureButton
.tintColor = .label
self.flipTextureButton
.addTarget(self,
action: #selector(self.flipTexture),
for: .touchUpInside)
self.flipTextureButton
.snp
.makeConstraints { constraintMaker in
constraintMaker.width
.height
.equalTo(40)
constraintMaker.bottom
.equalToSuperview()
.inset(60)
constraintMaker.centerX
.equalToSuperview()
}
// shareImageButton
self.view
.addSubview(self.shareImageButton)
self.shareImageButton
.setImage(Asset.share.image,
for: .normal)
self.shareImageButton
.tintColor = .label
self.shareImageButton
.addTarget(self,
action: #selector(self.shareImage),
for: .touchUpInside)
self.shareImageButton
.snp
.makeConstraints { constraintMaker in
constraintMaker.width
.equalTo(30)
constraintMaker.height
.equalTo(40)
constraintMaker.bottom
.equalToSuperview()
.inset(60)
constraintMaker.trailing
.greaterThanOrEqualToSuperview()
.inset(20)
}
}
// MARK: - Redraw
private func draw(image: UIImage?) {
guard let image = image,
let cgImage = image.cgImage,
let texture = try? self.context
.texture(from: cgImage,
srgb: false,
usage: [.shaderWrite, .shaderRead])
else { return }
self.texture = texture
#if targetEnvironment(macCatalyst)
try? self.context.scheduleAndWait { commandBuffer in
commandBuffer.blit { blitEncoder in
blitEncoder.synchronize(resource: self.texture)
}
}
#endif
self.redraw()
}
private func redraw() {
self.metalView.setNeedsAdaptToTextureInput()
DispatchQueue.main.async {
try? self.context.schedule { commandBuffer in
self.metalView.draw(texture: self.texture,
in: commandBuffer)
}
}
}
// MARK: - Button Actions
@objc
func chooseImage() {
presentPHAssetPicker(self.assetPickerController,
select: { _ in },
deselect: { _ in },
cancel: { _ in },
finish: { assets in
guard let asset = assets.first
else { return }
self.imageManager
.requestImage(for: asset,
targetSize: PHImageManagerMaximumSize,
contentMode: .default,
options: self.imageRequestOptions) { image, info in
self.draw(image: image)
}
})
}
@objc
func flipTexture() {
guard let temporaryTexture = try? self.texture.matchingTexture()
else { return }
self.metalView.setNeedsAdaptToTextureInput()
DispatchQueue.main.async {
try? self.context.scheduleAndWait { commandBuffer in
self.textureFlip(source: self.texture,
destination: temporaryTexture,
in: commandBuffer)
self.textureCopy(sourceTexture: temporaryTexture,
destinationTexture: self.texture,
in: commandBuffer)
self.metalView.draw(texture: self.texture,
in: commandBuffer)
}
}
}
@objc
func shareImage() {
guard let image = try? self.texture
.image()
else { return }
let activityViewController = UIActivityViewController(activityItems: [image],
applicationActivities: nil)
present(activityViewController,
animated: true)
}
}
| 32.08156 | 89 | 0.495302 |
1eb11affd854da74264bb65a5b16b30fd060cb2b | 343 | //
// Street.swift
// GojekTinder
//
// Created by Tien Pham on 8/30/20.
// Copyright © 2020 Tien Pham. All rights reserved.
//
import Foundation
struct Street: Codable {
// MARK: - Properties
let name: String?
let number: Int?
private enum CodingKeys: String, CodingKey {
case name
case number
}
}
| 15.590909 | 52 | 0.618076 |
624ffdb1512907dbe201308f647a8d610ed2b56b | 2,364 | //
// GCDWorkItemTestVC.swift
// Neves
//
// Created by aa on 2020/11/5.
//
class GCDWorkItemTestVC: TestBaseViewController {
var workItem: DispatchWorkItem? = nil
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
JPrint("开始了~")
// var abc = 1
// workItem = Asyncs.asyncDelay(5) {
// // 不想这个 workItem 会被再次调用,就调用 cancel,workItem 就会废掉。
// self.workItem?.cancel()
// abc += 1
// JPrint("执行了~ \(abc)")
// } mainTask: {
// JPrint("执行完?\(abc)")
// }
workItem = Asyncs.asyncDelay(5) {
JPrint("执行了~")
} mainTask: { (isCanceled) in
// self?.workItem = nil
JPrint("执行完?\(isCanceled)")
}
// workItem = Asyncs.mainDelay(5) {
// // 不想这个 workItem 会被再次调用,就调用 cancel,workItem 就会废掉。
//// self.workItem?.cancel()
// JPrint("执行了~")
// }
// workItem?.notify(queue: DispatchQueue.main, execute: {
// JPrint("执行完?")
// })
}
deinit {
JPrint("我死了")
}
// 只要执行过 cancel 或 perform,都会执行 notify,并且一个 workItem 只会执行【一次】notify
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
JPrint("点了屏幕")
if workItem?.isCancelled ?? true {
// 只要调用了 perform,就会【立即】接着执行 notify
// 即便在此之前已经调用了 cancel,那也只是不会执行 perform 里面的代码,但 notify 还是会执行
workItem?.perform()
} else {
// 延时来到前【只】调用 cancel(不管调用几次)都【不会】接着执行 notify,会等到延时到了才会执行 notify
workItem?.cancel()
workItem?.cancel()
workItem?.cancel()
}
// 只要不调用 cancel,perform 就可以执行多次(即便 notify 已经执行了)
// workItem?.perform()
// workItem?.perform()
// workItem?.perform()
// 只要【执行过】cancel,就不可以再执行 perform(废掉 workItem)
// workItem?.cancel()
// workItem?.perform()
// workItem?.perform()
// workItem?.perform()
// 所以,如果想 perform 只执行一次,那么就在 perform 的函数体内对 workItem 执行 cancel,那么这个 workItem 就会废掉了。
// 想【提前】完整地执行整个任务,即 perform + notify 都会调用,并且只会调用一次,最好的做法就是在外部 perform + cancel
// workItem?.perform()
// workItem?.cancel()
}
}
| 27.811765 | 91 | 0.520305 |
d5677d42cc5f15e2a21a3d04f3def807b0eb51c8 | 3,342 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Distributed Actors open source project
//
// Copyright (c) 2018-2022 Apple Inc. and the Swift Distributed Actors project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of Swift Distributed Actors project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#else
import Glibc
#endif
import NIO
/// Not intended for general use.
public final class _Condition {
@usableFromInline
var condition: pthread_cond_t = .init()
public init() {
let error = pthread_cond_init(&self.condition, nil)
switch error {
case 0:
return
default:
fatalError("Condition could not be created: \(error)")
}
}
deinit {
pthread_cond_destroy(&condition)
}
@inlinable
public func wait(_ mutex: _Mutex) {
let error = pthread_cond_wait(&self.condition, &mutex.mutex)
switch error {
case 0:
return
case EPERM:
fatalError("Wait failed, mutex is not owned by this thread")
case EINVAL:
fatalError("Wait failed, condition is not valid")
default:
fatalError("Wait failed with unspecified error: \(error)")
}
}
@inlinable
public func wait(_ mutex: _Mutex, atMost duration: Duration) -> Bool {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let time = TimeSpec.from(duration: duration)
#else
var now = timespec()
clock_gettime(CLOCK_REALTIME, &now)
let time = now + TimeSpec.from(duration: duration)
#endif
let error = withUnsafePointer(to: time) { p -> Int32 in
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
return pthread_cond_timedwait_relative_np(&condition, &mutex.mutex, p)
#else
return pthread_cond_timedwait(&condition, &mutex.mutex, p)
#endif
}
switch error {
case 0:
return true
case ETIMEDOUT:
return false
case EPERM:
fatalError("Wait failed, mutex is not owned by this thread")
case EINVAL:
fatalError("Wait failed, condition is not valid")
default:
fatalError("Wait failed with unspecified error: \(error)")
}
}
@inlinable
public func signal() {
let error = pthread_cond_signal(&self.condition)
switch error {
case 0:
return
case EINVAL:
fatalError("Signal failed, condition is not valid")
default:
fatalError("Signal failed with unspecified error: \(error)")
}
}
@inlinable
public func signalAll() {
let error = pthread_cond_broadcast(&self.condition)
switch error {
case 0:
return
case EINVAL:
fatalError("Signal failed, condition is not valid")
default:
fatalError("Signal failed with unspecified error: \(error)")
}
}
}
| 28.322034 | 86 | 0.559844 |
61de9c0722b1ead428f569b2259c2f735a268342 | 2,639 | //
// FunctionVC1.swift
// 函数的灵活性
//
// Created by 姜守栋 on 2018/8/31.
// Copyright © 2018年 Munger. All rights reserved.
//
import UIKit
class FunctionVC1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// let myArray = [1,4,0, 3, 9]
// print(myArray.sorted())
// print(myArray.sorted(by: >))
// var numberStrings = [(2, "Two"), (1, "One"),(3, "Three")]
// print(numberStrings.sorted(by: >))
let people = [
Person(first: "Emily", last: "Young", yearOfBirth: 2002),
Person(first: "David", last: "Gray", yearOfBirth: 1991),
Person(first: "Robert", last: "Barnes", yearOfBirth: 1985),
Person(first: "Ava", last: "Barnes", yearOfBirth: 2000),
Person(first: "Joanne", last: "Miller", yearOfBirth: 1994),
Person(first: "Ava", last: "Barnes", yearOfBirth: 1998),
]
// sortedArray(using: descriptors) :这个方法为了确定两个元素之间的顺序,他会先使用第一个描述符,并检查其结果。如果两个元素在第一个描述符下相同,那么他将使用第二个描述,以此类推。
// 排序描述符用到了两个OC运行时特性,首先,key是oc的键路径,他其实是一个包含属性名字的链表。第二个是oc运行时的键值编程,它可以在运行时通过键查找一个对象上对应的值。
// let lastDescriptor = NSSortDescriptor(key: #keyPath(Person.last), ascending: true,
// selector: #selector(NSString.localizedStandardCompare(_:)))
// let firstDescriptor = NSSortDescriptor(key: #keyPath(Person.first), ascending: true,
// selector: #selector(NSString.localizedStandardCompare(_:)))
// let yearDescriptor = NSSortDescriptor(key: #keyPath(Person.yearOfBirth),
// ascending: true)
// let descriptors = [lastDescriptor, firstDescriptor, yearDescriptor]
// let sorted = (people as NSArray).sortedArray(using: descriptors) as! [Person]
// sorted.map { print($0.first)}
print(people.sorted { $0.yearOfBirth < $1.yearOfBirth } )
typealias SortDescriptor<Value> = (Value, Value) -> Bool
// let sortedByYear: SortDescriptor<Person> = { $0. yearOfBirth < $1.yearOfBirth }
// let sortedByLastName: SortDescriptor<Person> = {
// $0.last.localizedStandardCompare($1.last) == .orderedAscending
// }
}
}
@objcMembers // 此标记的作用是被标记的类的所有成员都将在Objective-C中可见
final class Person: NSObject {
let first: String
let last: String
let yearOfBirth: Int
init(first: String, last: String, yearOfBirth: Int) {
self.first = first
self.last = last
self.yearOfBirth = yearOfBirth
}
}
| 37.7 | 112 | 0.593786 |
bf7057d7f32c840bef7ac0b87fe8707304597290 | 932 | // RUN: %target-swift-frontend %s -g -emit-ir -o - | %FileCheck %s
class X {
init (i : Int64) { x = i }
var x : Int64
}
// CHECK: define {{.*}}ifelseexpr
public func ifelseexpr() -> Int64 {
var x = X(i:0)
// CHECK: [[META:%.*]] = call %swift.type* @_T06return1XCMa()
// CHECK: [[X:%.*]] = call {{.*}}%T6return1XC* @_T06return1XCACs5Int64V1i_tcfC(
// CHECK-SAME: i64 0, %swift.type* swiftself [[META]])
// CHECK: @swift_rt_swift_release to void (%T6return1XC*)*)(%T6return1XC* [[X]])
if true {
x.x += 1
} else {
x.x -= 1
}
// CHECK: @swift_rt_swift_release to void (%T6return1XC*)*)(%T6return1XC* [[X]])
// CHECK-SAME: , !dbg ![[RELEASE:.*]]
// The ret instruction should be in the same scope as the return expression.
// CHECK: ret{{.*}}, !dbg ![[RELEASE]]
return x.x // CHECK: ![[RELEASE]] = !DILocation(line: [[@LINE]], column: 3
}
| 33.285714 | 89 | 0.551502 |
cce45e356ca2f02d2c829a2e1c5b9201428bda2a | 455 | //
// StyleGuide.swift
// TipCalc35
//
// Created by Ian Becker on 8/24/20.
// Copyright © 2020 Colton Swapp. All rights reserved.
//
import UIKit
extension UIView {
func addCornerRadius(_ radius: CGFloat = 4) {
self.layer.cornerRadius = radius
}
}
extension UIColor {
static let darkBlue = UIColor(named: "darkBlue")
static let customGreen = UIColor(named: "green")
static let headerGray = UIColor(named: "headerGray")
}
| 18.958333 | 56 | 0.676923 |
879c96bcf5e7b4336b1be4ab0c39dd04b46cc2e1 | 236 | //
// AppDelegate.swift
// InkExampleOSX
//
// Created by Shaps Benkau on 30/09/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
}
| 14.75 | 52 | 0.724576 |
ef67efe3e6bbe503daa2582dc6a9f1d3e70c166f | 34 | let a: Int? = nil
if let aa = a {} | 17 | 17 | 0.529412 |
56041d4aa5d5f6923149ba3c505f7d88b4a6e2f3 | 336 | //
// Coordinator.swift
// PhotoBin
//
// Created by Vipin Aggarwal on 10/05/20.
// Copyright © 2020 Vipin Aggarwal. All rights reserved.
//
import UIKit
protocol Coordinator: AnyObject {
var childCoordinators: [Coordinator] { get set }
var navigationController: UINavigationController { get set }
func start()
}
| 19.764706 | 64 | 0.693452 |
89c4bdc45f3a50c13a467f0ccb907602483c56ff | 2,735 | //
// LocationSimulationSession.swift
// Teleport
//
// Created by Cameron Deardorff on 7/4/20.
//
import Foundation
import CoreLocation
import SwiftUI
import Combine
class PathSimulationPlayer: ObservableObject {
private var locationIndex: Int? = nil
private var timer: RepeatingTimer? = nil
@Published var loop: PlayLoop = .notLooped
@Published var speed: PlaySpeed = .fast {
didSet {
timer?.timeInterval = speed.rawValue
}
}
@Published var state: PlayState = .stopped {
didSet {
if oldValue == .stopped && state == .playing {
timer = RepeatingTimer(timeInterval: speed.rawValue)
timer?.eventHandler = { [weak self] in
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
if self.loop == .loop, let index = self.locationIndex, index >= self.path.count {
self.locationIndex = 0
}
let index = self.locationIndex ?? 0
guard (0..<self.path.count).contains(index) else {
self.timer = nil
self.state = .stopped
return
}
self.currentLocation = self.path[index]
self.locationIndex = index + 1
}
}
timer?.resume()
return
}
if oldValue == .playing && state == .paused {
timer?.suspend()
}
if oldValue == .paused && state == .playing {
timer?.resume()
}
if state == .stopped {
timer = nil
currentLocation = nil
locationIndex = nil
}
}
}
@Published var currentLocation: CLLocation? = nil {
didSet {
guard currentLocation != nil else { return }
let sims = simulators.map { $0.udid.uuidString }
SystemNotification().simulate(coordinates: currentLocation!.coordinate, to: sims)
}
}
var provider: PathSimulationProvider
var path: [CLLocation] { return provider.path }
private var simulators: [Simulator] = []
private weak var cancellable: AnyCancellable? = nil
init(provider: PathSimulationProvider) {
self.provider = provider
self.cancellable = SimulatorController.shared.publisher
.sink { (simulators) in
self.simulators = simulators
}
}
}
| 31.079545 | 105 | 0.500548 |
39befbcec97beada8947d0c0205a76a932682abb | 1,463 | //
// KeyedEncodingContainer+Utils.swift
// Codable-Utils
//
// Created by Jaime Andres Laino Guerra on 8/5/19.
// Copyright © 2019 jaime Laino Guerra. All rights reserved.
//
import Foundation
public extension KeyedEncodingContainer {
/// Encodes a Dictionary where the key conform to `CodingKey`
///
/// struct Photo: Codable {
/// enum URLKind: String, CodingKey {
/// case raw, full, regular, small, thumb
/// }
///
/// enum CodingKeys: String, CodingKey {
/// case urls
/// }
///
/// let urls: [URLKind: URL]
///
/// public func encode(to encoder: Encoder) throws {
/// var container = encoder.container(keyedBy: CodingKeys.self)
/// try container.encodeDictionary(urls, forKey: .urls)
/// }
/// }
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid
mutating func encodeDictionary<K, V>(_ value: Dictionary<K, V>,
forKey codingKey: Key) throws where K: CodingKey, V: Encodable {
let dictionary = value.reduce(into: [String: V]()) { (result, dict) in
result[dict.key.stringValue] = dict.value
}
try encode(dictionary, forKey: codingKey)
}
}
| 34.833333 | 105 | 0.559809 |
8a4215dfcfec124a387779cbb2b869ba9abc9c28 | 1,465 | //
// ContentView.swift
// macplot
//
// Created by SATOSHI NAKAJIMA on 3/20/21.
//
import SwiftUI
struct Sample: Identifiable {
let id: String
let title: String
}
let samples = [
Sample(id: "sample", title: "Decaying Sin Wave"),
Sample(id: "sample2", title: "Decaying Sin Wave with another Sin Wave"),
Sample(id: "sample3", title: "Normal Distribution"),
Sample(id: "circle", title: "Circle"),
Sample(id: "flower", title: "Flower"),
Sample(id: "piechart", title: "Pie Chart"),
Sample(id: "salaries", title: "Median Salary (USD) by Age"),
Sample(id: "stock", title: "Historical Stock Price: TSLA"),
Sample(id: "stocks", title: "Compare Historical Stock Price"),
Sample(id: "stocka", title: "Stock Price Moving Average"),
Sample(id: "poisson", title: "Poisson Distribution"),
Sample(id: "b-spline", title: "B-Spline"),
Sample(id: "julia", title: "Julia Fractal"), // NOTE: Does not look good
Sample(id: "mandelbrot", title: "Mandelbrot Fractal"),
Sample(id: "random", title: "Random Walk"),
Sample(id: "fern", title: "Barnsley Fern"),
]
struct ContentView: View {
@EnvironmentObject var settings: Settings
var body: some View {
NavigationView {
List {
ForEach(samples) {
NavigationLink($0.title, destination: ScriptView(name: $0.id))
}
}
}
.environmentObject(settings)
}
}
| 30.520833 | 82 | 0.608191 |
71fac0e26c722b776d9ad087a4715011d3e6084c | 1,404 | //
// PasswordRouter.swift
// iOSApp
//
// Created by igork on 2/4/20.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import UIKit
import Swinject
class PasswordRouter {
let resolver: Resolver
weak var view: PasswordViewController!
init(withResolver resolver: Swinject.Resolver) {
self.resolver = resolver
}
func close(completion: (() -> Void)? = nil) {
view.dismiss(animated: true, completion: completion)
}
func presentError(_ title: String?, message: String?) {
if let errorView = resolver.resolve(ErrorViewInput.self, arguments: title, message),
let popupView = resolver.resolve(PopupViewInput.self) {
let presentedViewController = errorView.getViewController()
popupView.setContentViewController(presentedViewController)
popupView.getViewController().modalTransitionStyle = .crossDissolve
popupView.getViewController().modalPresentationStyle = .overFullScreen
view
.present(popupView.getViewController(), animated: true, completion: nil)
}
}
func presentProcessingView() {
if let processingView = resolver.resolve(ProcessingViewInput.self),
let popupViewController = view.popupViewController {
popupViewController.setContentViewController(processingView.getViewController())
}
}
}
| 32.651163 | 92 | 0.680199 |
035f298aa9c9af7e8d406a2f37f5012b2fe38db3 | 7,572 | /*
* Confess It
*
* This app is provided as-is with no warranty or guarantee
* See the license file under "Confess It" -> "License" ->
* "License.txt"
*
* Copyright © 2019 Brick Water Studios
*
*/
import Foundation
import Firebase
public class CIServer {
public weak var delegate: CIServerDelegate?
public weak var postDelegate: CIPostDelegate?
private let db = Firestore.firestore()
/// CODES: 1-- Share
/// 2-- Firebase
/// 3-- Recoverable Unknown
private func error(code: Int, desciption: String) -> Error {
return NSError(domain: "bws.confess.app", code: code, userInfo: [NSLocalizedDescriptionKey: desciption]) as Error
}
// MARK: - Share -
public func share(_ items: [UIImage]) {
let shareSheet = UIActivityViewController(activityItems: items, applicationActivities: nil)
if let root = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {
if let top = root.topViewController {
top.present(shareSheet, animated: true, completion: nil)
} else {
delegate?.didFailShare(error(code: 101, desciption: "Could not find top controller"))
}
} else {
delegate?.didFailShare(error(code: 100, desciption: "Could not find navigation controller"))
}
}
// MARK: - Post -
public func post(author: String, story: String, color: UIColor) {
db.collection("confessions").document().setData([
"author": author,
"story": story,
"background": color.stringValue ?? UIColor(red: 33/255, green: 33/255, blue: 33/255, alpha: 1).stringValue!,
"published": Timestamp(date: Date())
]) { error in
if let error = error {
self.postDelegate?.postDidFail(error: error)
} else {
self.postDelegate?.postDidSucceed()
}
}
}
// MARK: - Subscribe -
public func subscribe() {
db.collection("confessions").addSnapshotListener { docSnap, error in
if let error = error {
self.delegate?.confessionUpdateError(error)
return
}
guard let doc = docSnap else {
self.delegate?.confessionUpdateError(self.error(code: 200, desciption: "No server data found"))
return
}
for d in doc.documentChanges {
let dat = d.document.data()
if let story = dat["story"] as? String {
var time: Date
if let t = dat["published"] as? Timestamp {
time = t.dateValue()
} else { time = Date() }
var author: String
if let a = dat["author"] as? String {
author = a
} else { author = "Anonymous" }
var color: UIColor
if let c = dat["background"] as? String {
color = UIColor(from: c)
} else {
color = UIColor(red: 33/255, green: 33/255, blue: 33/255, alpha: 1)
}
var reports = 0
if let r = dat["reports"] as? Int {
reports = r
}
let conf = Confession(referance: d.document.reference, author: author, story: story, pubished: time, background: color, reports: reports)
if reports >= 5 {
CIServer().moveAndRemove(conf)
continue
}
confessions.append(conf)
} else { continue }
confessions.sort(by: { $0.published > $1.published })
self.delegate?.confessionDidUpdate()
}
}
}
// MARK: - Update -
public func update(completion: @escaping (Bool) -> Void) {
db.collection("confessions").getDocuments { snap, error in
if let error = error {
self.delegate?.confessionUpdateError(error)
completion(false)
}
guard let snap = snap else {
self.delegate?.confessionUpdateError(self.error(code: 200, desciption: "No server data found"))
completion(false)
return
}
var temp = [Confession]()
for d in snap.documentChanges {
let dat = d.document.data()
if let story = dat["story"] as? String {
var time: Date
if let t = dat["published"] as? Timestamp {
time = t.dateValue()
} else { time = Date() }
var author: String
if let a = dat["author"] as? String {
author = a
} else { author = "Anonymous" }
var color: UIColor
if let c = dat["background"] as? String {
color = UIColor(from: c)
} else {
color = UIColor(red: 33/255, green: 33/255, blue: 33/255, alpha: 1)
}
var reports = 0
if let r = dat["reports"] as? Int {
reports = r
}
let conf = Confession(referance: d.document.reference, author: author, story: story, pubished: time, background: color, reports: reports)
if reports >= 5 {
CIServer().moveAndRemove(conf)
continue
}
temp.append(conf)
} else { continue }
}
confessions = temp
completion(true)
}
}
// MARK: - Report -
public func report(_ confession: Confession) {
if let ref = confession.referance {
print(confession.diagString)
let rep = confession.reports + 1
ref.updateData(["reports":rep]) { error in
if let error = error {
self.delegate?.reportDidFail(error)
} else {
self.delegate?.reportDidSucceed()
}
}
} else {
let refError = error(code: 300, desciption: "Could not find confession database referance")
delegate?.reportDidFail(refError)
}
}
private func moveAndRemove(_ confession: Confession) {
guard let ref = confession.referance else { abortRaM(confession); return }
ref.getDocument { snap, error in
guard error == nil else { self.abortRaM(confession); return }
guard let snap = snap, let data = snap.data() else { self.abortRaM(confession); return }
self.db.collection("reported").addDocument(data: data) { error in
guard error == nil else { self.abortRaM(confession); return }
}
}
}
private func remove(_ confession: Confession) {
guard let ref = confession.referance else { abortRaM(confession); return }
ref.delete { error in
guard error == nil else { self.abortRaM(confession); return }
self.delegate?.confessionDidUpdate()
}
}
private func abortRaM(_ confession: Confession) {
confessions.append(confession)
}
}
| 39.4375 | 157 | 0.50383 |
efd3388158c3258cdd25fd9592a42ca2799b2e2a | 2,157 | //
// AppDelegate.swift
// dyzb
//
// Created by apple on 2019/9/5.
// Copyright © 2019 jodie. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.893617 | 285 | 0.753825 |
e98752b69951d68ae7e724bb252eafc45416f038 | 171 | /// Encapsulates shared behavior within Show types
protocol Showable {
var artworks: [Artworkable] { get }
var id: String { get }
var name: String { get }
}
| 19 | 50 | 0.654971 |
e2719994def3f513244409f35b08f7780e6b0f33 | 672 | // swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "VerificationSuite",
dependencies: [
.package(url: "https://github.com/apple/swift-package-manager.git", from: "0.1.0"),
.package(url: "https://github.com/JohnSundell/ShellOut.git", from: "2.1.0")
],
targets: [
.target(
name: "VerificationSuite",
dependencies: ["Utility", "ShellOut"]
),
.testTarget(
name: "VerificationSuiteTests",
dependencies: ["VerificationSuite"]
)
]
)
| 29.217391 | 96 | 0.607143 |
fe6206fbd23a71ed1a174d657510750c3104c03f | 2,972 | //
// ___COPYRIGHT___
//
import UIKit
/// Provides methods and properties for all navigation operations.
/// Instantiate, and use the object of this class in coordinators.
class MainRouter: Router {
private var window: UIWindow? {
return (UIApplication.shared.delegate as? AppDelegate)?.window
}
private var navigationController: UINavigationController? {
if let tabBar = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController {
return tabBar.selectedViewController as? UINavigationController
}
return UIApplication.shared.keyWindow?.rootViewController as? UINavigationController
}
private var tabBarController: UITabBarController? {
return UIApplication.shared.keyWindow?.rootViewController as? UITabBarController
}
private var topViewController: UIViewController? {
return UIApplication.topViewController()
}
func present(_ module: Presentable?) {
self.present(module, animated: true, completion: nil)
}
func present(_ module: Presentable?, animated: Bool, completion: (() -> Void)?) {
if let controller = module?.toPresent() {
self.topViewController?.present(controller, animated: animated, completion: completion)
}
}
func push(_ module: Presentable?) {
self.push(module, animated: true)
}
func push(_ module: Presentable?, animated: Bool) {
if let controller = module?.toPresent() {
self.topViewController?.navigationController?.pushViewController(controller, animated: animated)
}
}
func popModule() {
self.popModule(animated: true)
}
func popModule(animated: Bool) {
self.navigationController?.popViewController(animated: animated)
}
func popPreviousView() {
let navigationController = self.topViewController?.navigationController
guard
var controllers = navigationController?.viewControllers,
controllers.count >= 3 else {
return
}
controllers.remove(at: controllers.count - 2)
navigationController?.viewControllers = controllers
}
func dismissModule() {
self.dismissModule(animated: true, completion: nil)
}
func dismissModule(animated: Bool, completion: (() -> Void)?) {
topViewController?.dismiss(animated: animated, completion: completion)
}
func setNavigationControllerRootModule(_ module: Presentable?, animated: Bool = false, hideBar: Bool = false) {
if let controller = module?.toPresent() {
navigationController?.isNavigationBarHidden = hideBar
navigationController?.setViewControllers([controller], animated: false)
}
}
func setRootModule(_ module: Presentable?) {
window?.rootViewController = module?.toPresent()
}
func setTab(_ index: Int) {
tabBarController?.selectedIndex = index
}
}
| 32.304348 | 115 | 0.673957 |
f7d66c63b9a8ddc06e835e4b8116b6c7ccdc0375 | 35,739 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basics
import PackageModel
import PackageLoading
import SPMTestSupport
import TSCBasic
import TSCUtility
import XCTest
class PackageDescription4_2LoadingTests: PackageDescriptionLoadingTests {
override var toolsVersion: ToolsVersion {
.v4_2
}
func testBasics() {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Trivial",
products: [
.executable(name: "tool", targets: ["tool"]),
.library(name: "Foo", targets: ["foo"]),
],
dependencies: [
.package(url: "/foo1", from: "1.0.0"),
],
targets: [
.target(
name: "foo",
dependencies: ["dep1", .product(name: "product"), .target(name: "target")]),
.target(
name: "tool"),
.testTarget(
name: "bar",
dependencies: ["foo"]),
]
)
"""
loadManifest(stream.bytes) { manifest in
XCTAssertEqual(manifest.name, "Trivial")
// Check targets.
let foo = manifest.targetMap["foo"]!
XCTAssertEqual(foo.name, "foo")
XCTAssertFalse(foo.isTest)
XCTAssertEqual(foo.dependencies, ["dep1", .product(name: "product"), .target(name: "target")])
let bar = manifest.targetMap["bar"]!
XCTAssertEqual(bar.name, "bar")
XCTAssertTrue(bar.isTest)
XCTAssertEqual(bar.dependencies, ["foo"])
// Check dependencies.
let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })
XCTAssertEqual(deps["foo1"], .scm(location: "/foo1", requirement: .upToNextMajor(from: "1.0.0")))
// Check products.
let products = Dictionary(uniqueKeysWithValues: manifest.products.map{ ($0.name, $0) })
let tool = products["tool"]!
XCTAssertEqual(tool.name, "tool")
XCTAssertEqual(tool.targets, ["tool"])
XCTAssertEqual(tool.type, .executable)
let fooProduct = products["Foo"]!
XCTAssertEqual(fooProduct.name, "Foo")
XCTAssertEqual(fooProduct.type, .library(.automatic))
XCTAssertEqual(fooProduct.targets, ["foo"])
}
}
func testSwiftLanguageVersions() throws {
// Ensure integer values are not accepted.
var stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
swiftLanguageVersions: [3, 4]
)
"""
do {
try loadManifestThrowing(stream.bytes) { _ in }
XCTFail()
} catch {
guard case let ManifestParseError.invalidManifestFormat(output, _) = error else {
return XCTFail()
}
XCTAssertMatch(output, .and(.contains("'init(name:pkgConfig:providers:products:dependencies:targets:swiftLanguageVersions:cLanguageStandard:cxxLanguageStandard:)' is unavailable"), .contains("was obsoleted in PackageDescription 4.2")))
}
// Check when Swift language versions is empty.
stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
swiftLanguageVersions: []
)
"""
loadManifest(stream.bytes) { manifest in
XCTAssertEqual(manifest.swiftLanguageVersions, [])
}
stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
swiftLanguageVersions: [.v3, .v4, .v4_2, .version("5")]
)
"""
loadManifest(stream.bytes) { manifest in
XCTAssertEqual(
manifest.swiftLanguageVersions,
[.v3, .v4, .v4_2, SwiftLanguageVersion(string: "5")!]
)
}
stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
swiftLanguageVersions: [.v5]
)
"""
do {
try loadManifestThrowing(stream.bytes) { _ in }
XCTFail()
} catch {
guard case let ManifestParseError.invalidManifestFormat(message, _) = error else {
return XCTFail("\(error)")
}
XCTAssertMatch(message, .contains("is unavailable"))
XCTAssertMatch(message, .contains("was introduced in PackageDescription 5"))
}
}
func testPlatforms() throws {
var stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
platforms: nil
)
"""
do {
try loadManifestThrowing(stream.bytes) { _ in }
XCTFail()
} catch {
guard case let ManifestParseError.invalidManifestFormat(message, _) = error else {
return XCTFail("\(error)")
}
XCTAssertMatch(message, .contains("is unavailable"))
XCTAssertMatch(message, .contains("was introduced in PackageDescription 5"))
}
stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
platforms: [.macOS(.v10_10)]
)
"""
do {
try loadManifestThrowing(stream.bytes) { _ in }
XCTFail()
} catch {
guard case let ManifestParseError.invalidManifestFormat(message, _) = error else {
return XCTFail("\(error)")
}
XCTAssertMatch(message, .contains("is unavailable"))
XCTAssertMatch(message, .contains("was introduced in PackageDescription 5"))
}
}
func testBuildSettings() throws {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
targets: [
.target(
name: "Foo",
swiftSettings: [
.define("SWIFT", .when(configuration: .release)),
],
linkerSettings: [
.linkedLibrary("libz"),
]
),
]
)
"""
do {
try loadManifestThrowing(stream.bytes) { _ in }
XCTFail()
} catch {
guard case let ManifestParseError.invalidManifestFormat(message, _) = error else {
return XCTFail("\(error)")
}
XCTAssertMatch(message, .contains("is unavailable"))
XCTAssertMatch(message, .contains("was introduced in PackageDescription 5"))
}
}
func testPackageDependencies() throws {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
dependencies: [
.package(url: "/foo1", from: "1.0.0"),
.package(url: "/foo2", .revision("58e9de4e7b79e67c72a46e164158e3542e570ab6")),
.package(path: "../foo3"),
.package(path: "/path/to/foo4"),
.package(url: "/foo5", .exact("1.2.3")),
.package(url: "/foo6", "1.2.3"..<"2.0.0"),
.package(url: "/foo7", .branch("master")),
.package(url: "/foo8", .upToNextMinor(from: "1.3.4")),
.package(url: "/foo9", .upToNextMajor(from: "1.3.4")),
.package(path: "~/path/to/foo10"),
.package(path: "~foo11"),
.package(path: "~/path/to/~/foo12"),
.package(path: "~"),
.package(path: "file:///path/to/foo13"),
]
)
"""
loadManifest(stream.bytes) { manifest in
let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })
XCTAssertEqual(deps["foo1"], .scm(location: "/foo1", requirement: .upToNextMajor(from: "1.0.0")))
XCTAssertEqual(deps["foo2"], .scm(location: "/foo2", requirement: .revision("58e9de4e7b79e67c72a46e164158e3542e570ab6")))
if case .local(let dep) = deps["foo3"] {
XCTAssertEqual(dep.path.pathString, "/foo3")
} else {
XCTFail("expected to be local dependency")
}
if case .local(let dep) = deps["foo4"] {
XCTAssertEqual(dep.path.pathString, "/path/to/foo4")
} else {
XCTFail("expected to be local dependency")
}
XCTAssertEqual(deps["foo5"], .scm(location: "/foo5", requirement: .exact("1.2.3")))
XCTAssertEqual(deps["foo6"], .scm(location: "/foo6", requirement: .range("1.2.3"..<"2.0.0")))
XCTAssertEqual(deps["foo7"], .scm(location: "/foo7", requirement: .branch("master")))
XCTAssertEqual(deps["foo8"], .scm(location: "/foo8", requirement: .upToNextMinor(from: "1.3.4")))
XCTAssertEqual(deps["foo9"], .scm(location: "/foo9", requirement: .upToNextMajor(from: "1.3.4")))
let homeDir = "/home/user"
if case .local(let dep) = deps["foo10"] {
XCTAssertEqual(dep.path.pathString, "\(homeDir)/path/to/foo10")
} else {
XCTFail("expected to be local dependency")
}
if case .local(let dep) = deps["~foo11"] {
XCTAssertEqual(dep.path.pathString, "/foo/~foo11")
} else {
XCTFail("expected to be local dependency")
}
if case .local(let dep) = deps["foo12"] {
XCTAssertEqual(dep.path.pathString, "\(homeDir)/path/to/~/foo12")
} else {
XCTFail("expected to be local dependency")
}
if case .local(let dep) = deps["~"] {
XCTAssertEqual(dep.path.pathString, "/foo/~")
} else {
XCTFail("expected to be local dependency")
}
if case .local(let dep) = deps["foo13"] {
XCTAssertEqual(dep.path.pathString, "/path/to/foo13")
} else {
XCTFail("expected to be local dependency")
}
}
}
func testSystemLibraryTargets() throws {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
targets: [
.target(
name: "foo",
dependencies: ["bar"]),
.systemLibrary(
name: "bar",
pkgConfig: "libbar",
providers: [
.brew(["libgit"]),
.apt(["a", "b"]),
]),
]
)
"""
loadManifest(stream.bytes) { manifest in
let foo = manifest.targetMap["foo"]!
XCTAssertEqual(foo.name, "foo")
XCTAssertFalse(foo.isTest)
XCTAssertEqual(foo.type, .regular)
XCTAssertEqual(foo.dependencies, ["bar"])
let bar = manifest.targetMap["bar"]!
XCTAssertEqual(bar.name, "bar")
XCTAssertEqual(bar.type, .system)
XCTAssertEqual(bar.pkgConfig, "libbar")
XCTAssertEqual(bar.providers, [.brew(["libgit"]), .apt(["a", "b"])])
}
}
/// Check that we load the manifest appropriate for the current version, if
/// version specific customization is used.
func testVersionSpecificLoading() throws {
let bogusManifest: ByteString = "THIS WILL NOT PARSE"
let trivialManifest = ByteString(encodingAsUTF8: (
"import PackageDescription\n" +
"let package = Package(name: \"Trivial\")"))
// Check at each possible spelling.
let currentVersion = SwiftVersion.currentVersion
let possibleSuffixes = [
"\(currentVersion.major).\(currentVersion.minor).\(currentVersion.patch)",
"\(currentVersion.major).\(currentVersion.minor)",
"\(currentVersion.major)"
]
for (i, key) in possibleSuffixes.enumerated() {
let root = AbsolutePath.root
// Create a temporary FS with the version we want to test, and everything else as bogus.
let fs = InMemoryFileSystem()
// Write the good manifests.
try fs.writeFileContents(
root.appending(component: Manifest.basename + "@swift-\(key).swift"),
bytes: trivialManifest)
// Write the bad manifests.
let badManifests = [Manifest.filename] + possibleSuffixes[i+1 ..< possibleSuffixes.count].map{
Manifest.basename + "@swift-\($0).swift"
}
try badManifests.forEach {
try fs.writeFileContents(
root.appending(component: $0),
bytes: bogusManifest)
}
// Check we can load the repository.
let manifest = try manifestLoader.load(at: root, packageKind: .root, packageLocation: "/foo", toolsVersion: .v4_2, fileSystem: fs)
XCTAssertEqual(manifest.name, "Trivial")
}
}
// Check that ancient `[email protected]` manifests are properly treated as 3.1 even without a tools-version comment.
func testVersionSpecificLoadingOfVersion3Manifest() throws {
// Create a temporary FS to hold the package manifests.
let fs = InMemoryFileSystem()
// Write a regular manifest with a tools version comment, and a `[email protected]` manifest without one.
let packageDir = AbsolutePath.root
let manifestContents = "import PackageDescription\nlet package = Package(name: \"Trivial\")"
try fs.writeFileContents(
packageDir.appending(component: Manifest.basename + ".swift"),
bytes: ByteString(encodingAsUTF8: "// swift-tools-version:4.0\n" + manifestContents))
try fs.writeFileContents(
packageDir.appending(component: Manifest.basename + "@swift-3.swift"),
bytes: ByteString(encodingAsUTF8: manifestContents))
// Check we can load the manifest.
let manifest = try manifestLoader.load(at: packageDir, packageKind: .root, packageLocation: "/foo", toolsVersion: .v4_2, fileSystem: fs)
XCTAssertEqual(manifest.name, "Trivial")
// Switch it around so that the main manifest is now the one that doesn't have a comment.
try fs.writeFileContents(
packageDir.appending(component: Manifest.basename + ".swift"),
bytes: ByteString(encodingAsUTF8: manifestContents))
try fs.writeFileContents(
packageDir.appending(component: Manifest.basename + "@swift-4.swift"),
bytes: ByteString(encodingAsUTF8: "// swift-tools-version:4.0\n" + manifestContents))
// Check we can load the manifest.
let manifest2 = try manifestLoader.load(at: packageDir, packageKind: .root, packageLocation: "/foo", toolsVersion: .v4_2, fileSystem: fs)
XCTAssertEqual(manifest2.name, "Trivial")
}
func testRuntimeManifestErrors() throws {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Trivial",
products: [
.executable(name: "tool", targets: ["tool"]),
.library(name: "Foo", targets: ["Foo"]),
],
dependencies: [
.package(url: "/foo1", from: "1.0,0"),
],
targets: [
.target(
name: "foo",
dependencies: ["dep1", .product(name: "product"), .target(name: "target")]),
.testTarget(
name: "bar",
dependencies: ["foo"]),
]
)
"""
do {
try loadManifestThrowing(stream.bytes) { _ in }
XCTFail("Unexpected success")
} catch ManifestParseError.runtimeManifestErrors(let errors) {
XCTAssertEqual(errors, ["Invalid semantic version string '1.0,0'"])
}
}
func testDuplicateDependencyDecl() throws {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Trivial",
dependencies: [
.package(path: "../foo1"),
.package(url: "/foo1.git", from: "1.0.1"),
.package(url: "path/to/foo1", from: "3.0.0"),
.package(url: "/foo2.git", from: "1.0.1"),
.package(url: "/foo2.git", from: "1.1.1"),
.package(url: "/foo3.git", from: "1.0.1"),
],
targets: [
.target(
name: "foo",
dependencies: ["dep1", .target(name: "target")]),
]
)
"""
XCTAssertManifestLoadThrows(stream.bytes) { _, diagnostics in
diagnostics.check(diagnostic: .regex("duplicate dependency 'foo(1|2)'"), behavior: .error)
diagnostics.check(diagnostic: .regex("duplicate dependency 'foo(1|2)'"), behavior: .error)
}
}
func testNotAbsoluteDependencyPath() throws {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Trivial",
dependencies: [
.package(path: "https://someurl.com"),
],
targets: [
.target(
name: "foo",
dependencies: []),
]
)
"""
do {
try loadManifestThrowing(stream.bytes) { _ in }
XCTFail("Unexpected success")
} catch ManifestParseError.invalidManifestFormat(let message, let diagnosticFile) {
XCTAssertNil(diagnosticFile)
XCTAssertEqual(message, "'https://someurl.com' is not a valid path for path-based dependencies; use relative or absolute path instead.")
}
}
func testCacheInvalidationOnEnv() throws {
try testWithTemporaryDirectory { path in
let fs = localFileSystem
let manifestPath = path.appending(components: "pkg", "Package.swift")
try fs.writeFileContents(manifestPath) { stream in
stream <<< """
import PackageDescription
let package = Package(
name: "Trivial",
targets: [
.target(
name: "foo",
dependencies: []),
]
)
"""
}
let delegate = ManifestTestDelegate()
let manifestLoader = ManifestLoader(manifestResources: Resources.default, cacheDir: path, delegate: delegate)
func check(loader: ManifestLoader, expectCached: Bool) {
delegate.clear()
let manifest = try! loader.load(
at: manifestPath.parentDirectory,
packageKind: .local,
packageLocation: manifestPath.pathString,
toolsVersion: .v4_2,
fileSystem: fs
)
XCTAssertEqual(delegate.loaded, [manifestPath])
XCTAssertEqual(delegate.parsed, expectCached ? [] : [manifestPath])
XCTAssertEqual(manifest.name, "Trivial")
XCTAssertEqual(manifest.targets[0].name, "foo")
}
check(loader: manifestLoader, expectCached: false)
check(loader: manifestLoader, expectCached: true)
try withCustomEnv(["SWIFTPM_MANIFEST_CACHE_TEST": "1"]) {
check(loader: manifestLoader, expectCached: false)
check(loader: manifestLoader, expectCached: true)
}
try withCustomEnv(["SWIFTPM_MANIFEST_CACHE_TEST": "2"]) {
check(loader: manifestLoader, expectCached: false)
check(loader: manifestLoader, expectCached: true)
}
check(loader: manifestLoader, expectCached: true)
}
}
func testCaching() throws {
try testWithTemporaryDirectory { path in
let fs = localFileSystem
let manifestPath = path.appending(components: "pkg", "Package.swift")
try fs.writeFileContents(manifestPath) { stream in
stream <<< """
import PackageDescription
let package = Package(
name: "Trivial",
targets: [
.target(
name: "foo",
dependencies: []),
]
)
"""
}
let delegate = ManifestTestDelegate()
let manifestLoader = ManifestLoader(manifestResources: Resources.default, cacheDir: path, delegate: delegate)
func check(loader: ManifestLoader, expectCached: Bool) {
delegate.clear()
let manifest = try! loader.load(
at: manifestPath.parentDirectory,
packageKind: .local,
packageLocation: manifestPath.pathString,
toolsVersion: .v4_2,
fileSystem: fs
)
XCTAssertEqual(delegate.loaded, [manifestPath])
XCTAssertEqual(delegate.parsed, expectCached ? [] : [manifestPath])
XCTAssertEqual(manifest.name, "Trivial")
XCTAssertEqual(manifest.targets[0].name, "foo")
}
check(loader: manifestLoader, expectCached: false)
for _ in 0..<2 {
check(loader: manifestLoader, expectCached: true)
}
try fs.writeFileContents(manifestPath) { stream in
stream <<< """
import PackageDescription
let package = Package(
name: "Trivial",
targets: [
.target(
name: "foo",
dependencies: [ ]),
]
)
"""
}
check(loader: manifestLoader, expectCached: false)
for _ in 0..<2 {
check(loader: manifestLoader, expectCached: true)
}
let noCacheLoader = ManifestLoader(manifestResources: Resources.default, delegate: delegate)
for _ in 0..<2 {
check(loader: noCacheLoader, expectCached: false)
}
// Resetting the cache should allow us to remove the cache
// directory without triggering assertions in sqlite.
try manifestLoader.purgeCache()
try localFileSystem.removeFileTree(path)
}
}
func testContentBasedCaching() throws {
try testWithTemporaryDirectory { path in
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Trivial",
targets: [
.target(name: "foo"),
]
)
"""
let delegate = ManifestTestDelegate()
let manifestLoader = ManifestLoader(manifestResources: Resources.default, cacheDir: path, delegate: delegate)
func check(loader: ManifestLoader) throws {
let fs = InMemoryFileSystem()
let manifestPath = AbsolutePath.root.appending(component: Manifest.filename)
try fs.writeFileContents(manifestPath, bytes: stream.bytes)
let m = try manifestLoader.load(
at: AbsolutePath.root,
packageKind: .root,
packageLocation: "/foo",
toolsVersion: .v4_2,
fileSystem: fs)
XCTAssertEqual(m.name, "Trivial")
}
try check(loader: manifestLoader)
XCTAssertEqual(delegate.loaded.count, 1)
XCTAssertEqual(delegate.parsed.count, 1)
try check(loader: manifestLoader)
XCTAssertEqual(delegate.loaded.count, 2)
XCTAssertEqual(delegate.parsed.count, 1)
stream <<< "\n\n"
try check(loader: manifestLoader)
XCTAssertEqual(delegate.loaded.count, 3)
XCTAssertEqual(delegate.parsed.count, 2)
}
}
func testProductTargetNotFound() throws {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.library(name: "Product", targets: ["B"]),
],
targets: [
.target(name: "A"),
.target(name: "b"),
.target(name: "C"),
]
)
"""
XCTAssertManifestLoadThrows(stream.bytes) { _, diagnostics in
diagnostics.check(diagnostic: "target 'B' referenced in product 'Product' could not be found; valid targets are: 'A', 'C', 'b'", behavior: .error)
}
}
func testLoadingWithoutDiagnostics() throws {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.library(name: "Product", targets: ["B"]),
],
targets: [
.target(name: "A"),
]
)
"""
do {
_ = try loadManifest(
stream.bytes,
toolsVersion: toolsVersion,
packageKind: .remote,
diagnostics: nil
)
XCTFail("Unexpected success")
} catch let error as StringError {
XCTAssertMatch(error.description, "target 'B' referenced in product 'Product' could not be found; valid targets are: 'A'")
}
}
// run this with TSAN/ASAN to detect concurrency issues
func testConcurrencyWithWarmup() throws {
let total = 1000
try testWithTemporaryDirectory { path in
let manifestPath = path.appending(components: "pkg", "Package.swift")
try localFileSystem.writeFileContents(manifestPath) { stream in
stream <<< """
import PackageDescription
let package = Package(
name: "Trivial",
targets: [
.target(
name: "foo",
dependencies: []),
]
)
"""
}
let diagnostics = DiagnosticsEngine()
let delegate = ManifestTestDelegate()
let manifestLoader = ManifestLoader(manifestResources: Resources.default, cacheDir: path, delegate: delegate)
let identityResolver = DefaultIdentityResolver()
// warm up caches
let manifest = try tsc_await { manifestLoader.load(at: manifestPath.parentDirectory,
packageIdentity: .plain("Trivial"),
packageKind: .local,
packageLocation: manifestPath.pathString,
version: nil,
revision: nil,
toolsVersion: .v4_2,
identityResolver: identityResolver,
fileSystem: localFileSystem,
on: .global(),
completion: $0) }
XCTAssertEqual(manifest.name, "Trivial")
XCTAssertEqual(manifest.targets[0].name, "foo")
let sync = DispatchGroup()
for _ in 0 ..< total {
sync.enter()
manifestLoader.load(at: manifestPath.parentDirectory,
packageIdentity: .plain("Trivial"),
packageKind: .local,
packageLocation: manifestPath.pathString,
version: nil,
revision: nil,
toolsVersion: .v4_2,
identityResolver: identityResolver,
fileSystem: localFileSystem,
diagnostics: diagnostics,
on: .global()) { result in
defer { sync.leave() }
switch result {
case .failure(let error):
XCTFail("\(error)")
case .success(let manifest):
XCTAssertEqual(manifest.name, "Trivial")
XCTAssertEqual(manifest.targets[0].name, "foo")
}
}
}
if case .timedOut = sync.wait(timeout: .now() + 30) {
XCTFail("timeout")
}
XCTAssertEqual(delegate.loaded.count, total+1)
XCTAssertFalse(diagnostics.hasWarnings, diagnostics.description)
XCTAssertFalse(diagnostics.hasErrors, diagnostics.description)
}
}
// run this with TSAN/ASAN to detect concurrency issues
func testConcurrencyNoWarmUp() throws {
let total = 1000
try testWithTemporaryDirectory { path in
let diagnostics = DiagnosticsEngine()
let delegate = ManifestTestDelegate()
let manifestLoader = ManifestLoader(manifestResources: Resources.default, cacheDir: path, delegate: delegate)
let identityResolver = DefaultIdentityResolver()
let sync = DispatchGroup()
for _ in 0 ..< total {
let random = Int.random(in: 0 ... total / 4)
let manifestPath = path.appending(components: "pkg-\(random)", "Package.swift")
if !localFileSystem.exists(manifestPath) {
try localFileSystem.writeFileContents(manifestPath) { stream in
stream <<< """
import PackageDescription
let package = Package(
name: "Trivial-\(random)",
targets: [
.target(
name: "foo-\(random)",
dependencies: []),
]
)
"""
}
}
sync.enter()
manifestLoader.load(at: manifestPath.parentDirectory,
packageIdentity: .plain("Trivial-\(random)"),
packageKind: .local,
packageLocation: manifestPath.pathString,
version: nil,
revision: nil,
toolsVersion: .v4_2,
identityResolver: identityResolver,
fileSystem: localFileSystem,
diagnostics: diagnostics,
on: .global()) { result in
defer { sync.leave() }
switch result {
case .failure(let error):
XCTFail("\(error)")
case .success(let manifest):
XCTAssertEqual(manifest.name, "Trivial-\(random)")
XCTAssertEqual(manifest.targets[0].name, "foo-\(random)")
}
}
}
if case .timedOut = sync.wait(timeout: .now() + 600) {
XCTFail("timeout")
}
XCTAssertEqual(delegate.loaded.count, total)
XCTAssertFalse(diagnostics.hasWarnings, diagnostics.description)
XCTAssertFalse(diagnostics.hasErrors, diagnostics.description)
}
}
final class ManifestTestDelegate: ManifestLoaderDelegate {
private let lock = Lock()
private var _loaded: [AbsolutePath] = []
private var _parsed: [AbsolutePath] = []
func willLoad(manifest: AbsolutePath) {
self.lock.withLock {
self._loaded.append(manifest)
}
}
func willParse(manifest: AbsolutePath) {
self.lock.withLock {
self._parsed.append(manifest)
}
}
func clear() {
self.lock.withLock {
self._loaded.removeAll()
self._parsed.removeAll()
}
}
var loaded: [AbsolutePath] {
self.lock.withLock {
self._loaded
}
}
var parsed: [AbsolutePath] {
self.lock.withLock {
self._parsed
}
}
}
}
extension DiagnosticsEngine {
public var hasWarnings: Bool {
return diagnostics.contains(where: { $0.message.behavior == .warning })
}
}
| 38.846739 | 247 | 0.496488 |
645aab40c19f53a3d209d0a49f7758e24ffbfdc7 | 3,741 | //
// GAPlistManager.swift
// YYFramework
//
// Created by 侯佳男 on 2018/8/14.
// Copyright © 2018年 houjianan. All rights reserved.
// plist文件读写管理类
/*
GAPlistManager.share.writeArrayPlist(data: ["123", "123123"], fileName: "test5")
GAPlistManager.share.removeArrayPlist(fileName: "test3")
GAPlistManager.share.yy_fileNames()
*/
import Foundation
typealias GAPlistManagerFinishedHandler = (_ finish: Bool) -> ()
class GAPlistManager {
static let share: GAPlistManager = GAPlistManager()
private let kGAPlistManagerFileNames = "comJiananGA"
private var ga_lock: NSLock = NSLock()
public func plistPath(name: String = "yy") -> String {
let path = NSHomeDirectory() + "/Documents/yyplist"
if !FileManager.default.fileExists(atPath: path) {
try! FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
}
let fileName = name + ".plist"
return path + "/" + fileName
}
public func writeDicPlist(data: [String : Any], fileName: String, handler: @escaping GAPlistManagerFinishedHandler) {
let dic = data as NSDictionary
if dic.write(toFile: plistPath(name: fileName), atomically: true) {
writeFileName(fileName: fileName)
handler(true)
} else {
handler(false)
}
}
public func readDicPlist(fileName: String) -> [String : Any]? {
let json = NSDictionary(contentsOfFile: plistPath(name: fileName)) as? [String : Any]
return json
}
public func writeArrayPlist(data: [Any], fileName: String) -> Bool {
let array = data as NSArray
if array.write(toFile: plistPath(name: fileName), atomically: true) {
writeFileName(fileName: fileName)
return true
} else {
return false
}
}
public func readArrayPlist(fileName: String) -> [Any]? {
return NSArray(contentsOfFile: plistPath(name: fileName)) as? [Any]
}
public func removeArrayPlist(fileName: String, handler: @escaping GAPlistManagerFinishedHandler) -> Bool {
if FileManager.default.isDeletableFile(atPath: plistPath(name: fileName)) {
DispatchQueue.global().async {
[weak self] in
if let weakSelf = self {
try? FileManager.default.removeItem(atPath: weakSelf.plistPath(name: fileName))
weakSelf.deleteFileName(fileName: fileName)
DispatchQueue.main.async {
handler(true)
}
}
}
return true
}
return false
}
public func yy_fileNames() -> [String] {
let array = NSArray(contentsOfFile: plistPath(name: kGAPlistManagerFileNames)) as? [String] ?? []
return array
}
private func writeFileName(fileName: String) {
var array = yy_fileNames()
if !array.contains(fileName) {
array.append(fileName)
_ = (array as NSArray).write(toFile: plistPath(name: kGAPlistManagerFileNames), atomically: true)
}
}
private func deleteFileName(fileName: String) {
var array = yy_fileNames()
var index = -1
for i in 0..<array.count {
if fileName == array[i] {
index = i
}
}
if index != -1 {
array.remove(at: index)
}
_ = (array as NSArray).write(toFile: plistPath(name: kGAPlistManagerFileNames), atomically: true)
}
deinit {
print( "deinit GAPlistManager")
}
}
| 31.436975 | 121 | 0.58594 |
33e1e1fbe8ac5c6aa967830f14d3407f42e2fdcd | 310 | import UIKit
class GradientPattern: NSObject {
var name: String
var fromColors: [String]
var gradient: GradientLayer
init(name: String, fromColors: [String], gradient: GradientLayer) {
self.name = name
self.fromColors = fromColors
self.gradient = gradient
}
}
| 22.142857 | 71 | 0.651613 |
e401b18d65a85f3100dcda51e31f755e85cf2f18 | 1,278 | //
// TestUUID.swift
// SRChocoDemo-OSX
//
// Created by Heeseung Seo on 2014. 10. 8..
// Copyright (c) 2014 Seorenn. All rights reserved.
//
import Foundation
import XCTest
import SRChoco
class TestUUID: 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 testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
func testDefaultUUID() {
var uuids = [String]()
let testCount = 50
for _ in 0..<testCount {
let uuid = SRUUID()
uuids.append(uuid.normalizedString)
}
for currentUUID in uuids {
var matchCount = 0
for occurUUID in uuids {
if occurUUID == currentUUID {
matchCount += 1
}
}
XCTAssertEqual(matchCount, 1)
}
}
}
| 24.576923 | 111 | 0.555556 |
7934d9c8d5bbd1219d1750a1687dac25189d2b7e | 8,794 | //
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
import XCTest
import CloudKit
import ProcedureKit
import TestingProcedureKit
@testable import ProcedureKitCloud
class TestCKModifyRecordZonesOperation: TestCKDatabaseOperation, CKModifyRecordZonesOperationProtocol, AssociatedErrorProtocol {
typealias AssociatedError = ModifyRecordZonesError<RecordZone, RecordZoneID>
var saved: [RecordZone]? = nil
var deleted: [RecordZoneID]? = nil
var error: Error? = nil
var recordZonesToSave: [RecordZone]? = nil
var recordZoneIDsToDelete: [RecordZoneID]? = nil
var modifyRecordZonesCompletionBlock: (([RecordZone]?, [RecordZoneID]?, Error?) -> Void)? = nil
init(saved: [RecordZone]? = nil, deleted: [RecordZoneID]? = nil, error: Error? = nil) {
self.saved = saved
self.deleted = deleted
self.error = error
super.init()
}
override func main() {
modifyRecordZonesCompletionBlock?(saved, deleted, error)
}
}
class CKModifyRecordZonesOperationTests: CKProcedureTestCase {
var target: TestCKModifyRecordZonesOperation!
var operation: CKProcedure<TestCKModifyRecordZonesOperation>!
override func setUp() {
super.setUp()
target = TestCKModifyRecordZonesOperation()
operation = CKProcedure(operation: target)
}
override func tearDown() {
target = nil
operation = nil
super.tearDown()
}
func test__set_get__recordZonesToSave() {
let recordZonesToSave = [ "a-record-zone", "another-record-zone" ]
operation.recordZonesToSave = recordZonesToSave
XCTAssertNotNil(operation.recordZonesToSave)
XCTAssertEqual(operation.recordZonesToSave ?? [], recordZonesToSave)
XCTAssertNotNil(target.recordZonesToSave)
XCTAssertEqual(target.recordZonesToSave ?? [], recordZonesToSave)
}
func test__set_get__recordZoneIDsToDelete() {
let recordZoneIDsToDelete = [ "a-record-zone-id", "another-record-zone-id" ]
operation.recordZoneIDsToDelete = recordZoneIDsToDelete
XCTAssertNotNil(operation.recordZoneIDsToDelete)
XCTAssertEqual(operation.recordZoneIDsToDelete ?? [], recordZoneIDsToDelete)
XCTAssertNotNil(target.recordZoneIDsToDelete)
XCTAssertEqual(target.recordZoneIDsToDelete ?? [], recordZoneIDsToDelete)
}
func test__success_without_completion_block() {
wait(for: operation)
XCTAssertProcedureFinishedWithoutErrors(operation)
}
func test__success_with_completion_block() {
var didExecuteBlock = false
operation.setModifyRecordZonesCompletionBlock { savedRecordZones, deletedRecordZoneIDs in
didExecuteBlock = true
}
wait(for: operation)
XCTAssertProcedureFinishedWithoutErrors(operation)
XCTAssertTrue(didExecuteBlock)
}
func test__error_without_completion_block() {
target.error = TestError()
wait(for: operation)
XCTAssertProcedureFinishedWithoutErrors(operation)
}
func test__error_with_completion_block() {
var didExecuteBlock = false
operation.setModifyRecordZonesCompletionBlock { savedRecordZones, deletedRecordZoneIDs in
didExecuteBlock = true
}
target.error = TestError()
wait(for: operation)
XCTAssertProcedureFinishedWithErrors(operation, count: 1)
XCTAssertFalse(didExecuteBlock)
}
}
class CloudKitProcedureModifyRecordZonesOperationTests: CKProcedureTestCase {
typealias T = TestCKModifyRecordZonesOperation
var cloudkit: CloudKitProcedure<T>!
override func setUp() {
super.setUp()
cloudkit = CloudKitProcedure(strategy: .immediate) { TestCKModifyRecordZonesOperation() }
cloudkit.container = container
cloudkit.recordZonesToSave = [ "record zone 1" ]
cloudkit.recordZoneIDsToDelete = [ "record zone 2 ID" ]
}
override func tearDown() {
cloudkit = nil
super.tearDown()
}
func test__set_get__errorHandlers() {
cloudkit.set(errorHandlers: [.internalError: cloudkit.passthroughSuggestedErrorHandler])
XCTAssertEqual(cloudkit.errorHandlers.count, 1)
XCTAssertNotNil(cloudkit.errorHandlers[.internalError])
}
func test__set_get_container() {
cloudkit.container = "I'm a different container!"
XCTAssertEqual(cloudkit.container, "I'm a different container!")
}
func test__set_get_database() {
cloudkit.database = "I'm a different database!"
XCTAssertEqual(cloudkit.database, "I'm a different database!")
}
func test__set_get_previousServerChangeToken() {
cloudkit.previousServerChangeToken = "I'm a different token!"
XCTAssertEqual(cloudkit.previousServerChangeToken, "I'm a different token!")
}
func test__set_get_resultsLimit() {
cloudkit.resultsLimit = 20
XCTAssertEqual(cloudkit.resultsLimit, 20)
}
func test__set_get_recordZonesToSave() {
cloudkit.recordZonesToSave = [ "record zone 3" ]
XCTAssertEqual(cloudkit.recordZonesToSave ?? [], [ "record zone 3" ])
}
func test__set_get_recordZoneIDsToDelete() {
cloudkit.recordZoneIDsToDelete = [ "record zone 4 ID" ]
XCTAssertEqual(cloudkit.recordZoneIDsToDelete ?? [], [ "record zone 4 ID" ])
}
func test__cancellation() {
cloudkit.cancel()
wait(for: cloudkit)
XCTAssertProcedureCancelledWithoutErrors(cloudkit)
}
func test__success_without_completion_block_set() {
wait(for: cloudkit)
XCTAssertProcedureFinishedWithoutErrors(cloudkit)
}
func test__success_with_completion_block_set() {
var didExecuteBlock = false
cloudkit.setModifyRecordZonesCompletionBlock { _, _ in
didExecuteBlock = true
}
wait(for: cloudkit)
XCTAssertProcedureFinishedWithoutErrors(cloudkit)
XCTAssertTrue(didExecuteBlock)
}
func test__error_without_completion_block_set() {
cloudkit = CloudKitProcedure(strategy: .immediate) {
let operation = TestCKModifyRecordZonesOperation()
operation.error = NSError(domain: CKErrorDomain, code: CKError.internalError.rawValue, userInfo: nil)
return operation
}
wait(for: cloudkit)
XCTAssertProcedureFinishedWithoutErrors(cloudkit)
}
func test__error_with_completion_block_set() {
cloudkit = CloudKitProcedure(strategy: .immediate) {
let operation = TestCKModifyRecordZonesOperation()
operation.error = NSError(domain: CKErrorDomain, code: CKError.internalError.rawValue, userInfo: nil)
return operation
}
var didExecuteBlock = false
cloudkit.setModifyRecordZonesCompletionBlock { _, _ in
didExecuteBlock = true
}
wait(for: cloudkit)
XCTAssertProcedureFinishedWithErrors(cloudkit, count: 1)
XCTAssertFalse(didExecuteBlock)
}
func test__error_which_retries_using_retry_after_key() {
var shouldError = true
cloudkit = CloudKitProcedure(strategy: .immediate) {
let op = TestCKModifyRecordZonesOperation()
if shouldError {
let userInfo = [CKErrorRetryAfterKey: NSNumber(value: 0.001)]
op.error = NSError(domain: CKErrorDomain, code: CKError.Code.serviceUnavailable.rawValue, userInfo: userInfo)
shouldError = false
}
return op
}
var didExecuteBlock = false
cloudkit.setModifyRecordZonesCompletionBlock { _, _ in didExecuteBlock = true }
wait(for: cloudkit)
XCTAssertProcedureFinishedWithoutErrors(cloudkit)
XCTAssertTrue(didExecuteBlock)
}
func test__error_which_retries_using_custom_handler() {
var shouldError = true
cloudkit = CloudKitProcedure(strategy: .immediate) {
let op = TestCKModifyRecordZonesOperation()
if shouldError {
op.error = NSError(domain: CKErrorDomain, code: CKError.Code.limitExceeded.rawValue, userInfo: nil)
shouldError = false
}
return op
}
var didRunCustomHandler = false
cloudkit.set(errorHandlerForCode: .limitExceeded) { _, _, _, suggestion in
didRunCustomHandler = true
return suggestion
}
var didExecuteBlock = false
cloudkit.setModifyRecordZonesCompletionBlock { _, _ in didExecuteBlock = true }
wait(for: cloudkit)
XCTAssertProcedureFinishedWithoutErrors(cloudkit)
XCTAssertTrue(didExecuteBlock)
XCTAssertTrue(didRunCustomHandler)
}
}
| 35.459677 | 128 | 0.684444 |
acbc9ba93a735b56dcc00e8ab3590e1878f1180f | 26,608 | //
// Renderer.swift
// Siblog
//
// Created by Simon Rodriguez on 27/01/2015.
// Copyright (c) 2015 Simon Rodriguez. All rights reserved.
//
import Foundation
//TODO: générer sitemap.xml
/**
* This class is in charge of rendering Articles objects as HTML pages on disk, generating an index page, a feed XML file and managing pictures and additional data.
*/
class Renderer {
// MARK: Properties
/// The array of articles to render
let articlesToRender : [Article]
/// The path of the output directory
let exportPath: String
/// The path to the directory where the template files are stored
let templatePath : String
/// The path to the additional resources directory
let resourcesPath : String
/// The path to the folder containing the articles files
let articlesPath : String
/// The title of the blog
let blogTitle : String
/// The root directory of the site once uploaded to the server
let siteRoot : String
/// Stores the HTML content of the article being currently generated
fileprivate var articleHtml : NSString = ""
/// Stores the HTML content of the index page
fileprivate var indexHtml : NSString = ""
/// The HTML code corresponding to a given articleon the index page
fileprivate var snippetHtml : NSString = ""
/// HTML content of the header
fileprivate var headerHtml : NSString = ""
/// HTML content for code syntax highlighting
fileprivate var syntaxHtml : NSString = ""
/// HTML content of the footer
fileprivate var footerHtml : NSString = ""
/// Index of the article being currently generated
fileprivate var insertIndex = 0
/// Shared instance of the Markdown parser
fileprivate var markdown : Markdown
/// Denotes if a ressource file has been modified
public var dirtyRessources : Bool = false
// MARK: Initialisation
/**
Initialisation method for the Renderer
- parameter articles: an array of articles to render
- parameter articlesPath: the path to the articles folder on disk
- parameter exportPath: the path of the output folder
- parameter rootPath: the path of the directory where the ressources directory is
- parameter templatePath: the path to the tempalte folder
- parameter defaultWidth: the default width of images inserted in articles
- parameter blogTitle: the title of the blog
- parameter imagesLink: if true, the images in articles are linking to the full size version of themselves
- parameter siteRoot: the root of the site once uploaded
*/
init(articles: [Article], articlesPath : String, exportPath : String, rootPath : String, templatePath: String, defaultWidth : String, blogTitle : String, imagesLink : Bool, siteRoot : String){
self.exportPath = exportPath
self.articlesPath = articlesPath
self.templatePath = templatePath
self.resourcesPath = rootPath.stringByAppendingPathComponent("resources")
self.articlesToRender = articles
self.blogTitle = blogTitle
self.siteRoot = siteRoot
var options = MarkdownOptions()
options.defaultWidth = defaultWidth
options.imagesAsLinks = imagesLink
markdown = Markdown(options: options)
if !FileManager.default.fileExists(atPath: exportPath) {
do {
try FileManager.default.createDirectory(atPath: exportPath, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
}
initializeTemplate()
loadTemplate()
}
// MARK: Template management
/**
Copies the template files in the output folder
*/
fileprivate func initializeTemplate(){
let templateFiles = (try! FileManager.default.contentsOfDirectory(atPath: templatePath))
for path in templateFiles{
let sourcePath = templatePath.stringByAppendingPathComponent(path)
let destinationPath = exportPath.stringByAppendingPathComponent(path.lastPathComponent)
if !FileManager.default.contentsEqual(atPath: sourcePath, andPath: destinationPath){
do {
if FileManager.default.fileExists(atPath: destinationPath){
try FileManager.default.removeItem(atPath: destinationPath)
}
try FileManager.default.copyItem(atPath: sourcePath, toPath: destinationPath)
} catch _ {
print("Unable to handle file \(sourcePath)")
}
}
}
do {
// Don't suppress index, it could have been generated on a previous run.
try FileManager.default.removeItem(atPath: exportPath.stringByAppendingPathComponent("article.html"))
try FileManager.default.removeItem(atPath: exportPath.stringByAppendingPathComponent("syntax.html"))
} catch _ {
print("Unable to delete a template file.")
}
}
/**
Loads the template data (HTML snippets) from the template files
*/
fileprivate func loadTemplate(){
if let data: Data = FileManager.default.contents(atPath: templatePath.stringByAppendingPathComponent("article.html")) {
if let str = NSString(data: data, encoding : String.Encoding.utf8.rawValue) {
articleHtml = str
} else {
print("Unable to load the article.html template.")
}
} else {
print("Unable to load the article.html template.")
}
if let data: Data = FileManager.default.contents(atPath: templatePath.stringByAppendingPathComponent("syntax.html")) {
if let str = NSString(data: data, encoding : String.Encoding.utf8.rawValue) {
syntaxHtml = str
} else {
print("Unable to load the syntax highlighting header template, default to \"\".")
syntaxHtml = ""
}
} else {
}
if let data: Data = FileManager.default.contents(atPath: templatePath.stringByAppendingPathComponent("index.html")) {
if let str = NSString(data: data, encoding : String.Encoding.utf8.rawValue) {
indexHtml = str
} else {
print("Unable to load the index.html template.")
}
} else {
print("Unable to load the index.html template.")
}
if indexHtml.length > 0 {
snippetHtml = extractSnippetHtml(indexHtml)
if snippetHtml.length == 0 {
print("Unable to extract the short-article snippet from the index.html template file.")
return
}
headerHtml = indexHtml.substring(to: insertIndex) as NSString
//println("\(snippetHtml.length),\(insertIndex)")
footerHtml = indexHtml.substring(from: insertIndex + 30 + snippetHtml.length) as NSString
}
}
/**
Restores the template content in the output folder
*/
fileprivate func restoreTemplate(){
let templateFiles = (try! FileManager.default.contentsOfDirectory(atPath: templatePath))
for path in templateFiles{
do {
try FileManager.default.copyItem(atPath: templatePath.stringByAppendingPathComponent(path), toPath: exportPath.stringByAppendingPathComponent(path.lastPathComponent))
} catch _ {
print("Unable to copy file \(templatePath.stringByAppendingPathComponent(path))")
}
}
do {
try FileManager.default.removeItem(atPath: exportPath.stringByAppendingPathComponent("index.html"))
try FileManager.default.removeItem(atPath: exportPath.stringByAppendingPathComponent("article.html"))
try FileManager.default.removeItem(atPath: exportPath.stringByAppendingPathComponent("syntax.html"))
} catch _ {
print("Unable to delete a template file.")
}
}
/**
Extracts the HTMl code corresponding to an article on the index page
- parameter code: the HTML code of the index page from the template
- returns: the extracted HTML snippet
*/
fileprivate func extractSnippetHtml(_ code : NSString)-> NSString{
let scanner = Scanner(string: code as String)
var res : NSString?
scanner.scanUpTo("{#ARTICLE_BEGIN}", into: nil)
insertIndex = scanner.scanLocation
scanner.scanUpTo("{#ARTICLE_END}", into: &res)
if let str2 : NSString = res?.substring(from: 16) as NSString? {
return str2
}
return ""
}
//MARK: Combining functions
/**
Renders the index page, and updates the resources directory.
*/
func updateIndex(){
for article in articlesToRender {
if !article.isDraft {
var contentHtml = markdown.transform(article.content)
contentHtml = addFootnotes(contentHtml)
article.content = contentHtml
}
}
renderIndex()
copyResources(false)
}
/**
Default export. Renders the new articles, clean and renders drafts again, renders the index and draft index pages, and updates the resources directory.
*/
func defaultExport(){
renderArticles(false)
renderDrafts(true)
renderIndex()
renderDraftIndex()
copyResources(false)
print("Index written at path " + exportPath.stringByAppendingPathComponent("index.html"))
}
/**
Regenerates all published articles, renders the index page and update the resources directory.
*/
func articlesOnly(){
renderArticles(true)
renderIndex()
copyResources(false)
print("Index written at path " + exportPath.stringByAppendingPathComponent("index.html"))
}
/**
Regenerates all published articles, update drafts, renders index and draft index pages, and updates the resources directory.
*/
func articlesForceOnly() {
renderArticles(true)
renderDrafts(false)
renderIndex()
renderDraftIndex()
copyResources(false)
print("Index written at path " + exportPath.stringByAppendingPathComponent("index.html"))
}
/**
Regenerates all draft articles, renders the drafts index page and update the resources directory.
*/
func draftsOnly(){
renderDrafts(true)
renderDraftIndex()
copyResources(false)
print("Drafts index written at path " + exportPath.stringByAppendingPathComponent("index-drafts.html"))
}
/**
Regenerates all draft articles, update published articles, renders index and draft index pages, and updates the resources directory.
*/
func draftsForceOnly() {
renderDrafts(true)
renderArticles(false)
renderDraftIndex()
renderIndex()
copyResources(false)
print("Drafts index written at path " + exportPath.stringByAppendingPathComponent("index-drafts.html"))
}
/**
Cleans the output directory, restores the template, generates all articles and drafts, the index and drafts index pages, and copies the resources directory.
*/
func fullExport() {
clean()
restoreTemplate()
renderArticles(true)
renderDrafts(true)
renderIndex()
renderDraftIndex()
copyResources(true)
print("Index written at path " + exportPath.stringByAppendingPathComponent("index.html"))
}
/**
Force-update the resources directory
*/
func updateResources(){
copyResources(true)
}
/**
Copies additional resources in the output directory.
- parameter forceUpdate: if true, previous resources will be erased
*/
fileprivate func copyResources(_ forceUpdate : Bool){
//print("Copying ressources...")
if FileManager.default.fileExists(atPath: resourcesPath) {
let exportResourcesPath = exportPath //.stringByAppendingPathComponent("resources")
if !FileManager.default.fileExists(atPath: exportResourcesPath) {
do {
try FileManager.default.createDirectory(atPath: exportResourcesPath, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
}
let paths = (try! FileManager.default.contentsOfDirectory(atPath: resourcesPath))
// We iterate on the first hierarchy level (we can't directly to a directory wide compare as the export directory is the output root).
for path in paths {
let sourcePath = resourcesPath.stringByAppendingPathComponent(path as String)
let destinationPath = exportResourcesPath.stringByAppendingPathComponent(path as String)
if forceUpdate || !FileManager.default.contentsEqual(atPath: sourcePath, andPath: destinationPath) {
do {
//print("Copying \(sourcePath) to \(destinationPath)")
if FileManager.default.fileExists(atPath: destinationPath){
try FileManager.default.removeItem(atPath: destinationPath)
}
try FileManager.default.copyItem(atPath: sourcePath, toPath: destinationPath)
dirtyRessources = true
} catch _ {
print("Unable to handle file \(sourcePath)")
}
}
}
}
}
//MARK: Rendering
/**
Renders the published articles as HTML files on disk, parsing the markdown content and mananging the pictures and ressources.
- parameter forceUpdate: true if previously generated articles should be generated
*/
fileprivate func renderArticles(_ forceUpdate : Bool){
if forceUpdate {
cleanFolder("articles")
}
for article in articlesToRender {
if !article.isDraft {
renderArticle(article, inFolder: "articles", forceUpdate : forceUpdate)
}
}
}
/**
Renders the index page listing all published articles, and the feed.xml RSS file.
*/
fileprivate func renderIndex() {
//println("Rendering index")
indexHtml = footerHtml.copy() as! NSString
var feedXml = "<?xml version=\"1.0\" ?>\n"
+ "<rss version=\"2.0\">\n"
+ "<channel>\n"
+ "<title>\(blogTitle)</title>\n"
feedXml = feedXml + "<link>http://" + siteRoot + "</link>\n"
+ "<description>\(blogTitle), a blog.</description>\n"
let dateOutputFormatter = DateFormatter()
dateOutputFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
dateOutputFormatter.locale = Locale(identifier: "en")
for article in articlesToRender {
if !article.isDraft {
var html : NSString = snippetHtml.copy() as! NSString
html = html.replacingOccurrences(of: "{#TITLE}", with: article.title) as NSString
html = html.replacingOccurrences(of: "{#DATE}", with: article.dateString) as NSString
html = html.replacingOccurrences(of: "{#AUTHOR}", with: article.author) as NSString
html = html.replacingOccurrences(of: "{#LINK}", with: "articles/"+article.getUrlPathname()) as NSString
let contentHtml : NSString = article.getSummary()
html = html.replacingOccurrences(of: "{#SUMMARY}", with: contentHtml as String) as NSString
indexHtml = NSString(format: "%@\n%@", html,indexHtml)
let dateOutput = dateOutputFormatter.string(from: article.date! as Date)
// println("date: \(article.date)")
feedXml = feedXml
+ "<item>\n"
feedXml = feedXml + "<title>\(article.title)</title>\n"
+ "<pubDate>" + dateOutput + "</pubDate>\n"
+ "<link>http://" + siteRoot + "/articles/\(article.getUrlPathname())</link>\n"
+ "<description>\(contentHtml)</description>\n"
feedXml = feedXml + "<guid>http://" + siteRoot + "/articles/\(article.getUrlPathname())</guid>\n"
+ "</item>\n"
}
}
feedXml = feedXml + "</channel>\n</rss>"
indexHtml = headerHtml.appending(indexHtml as String) as NSString
indexHtml = indexHtml.replacingOccurrences(of: "{#BLOG_TITLE}", with: blogTitle) as NSString
FileManager.default.createFile(atPath: exportPath.stringByAppendingPathComponent("index.html"), contents: indexHtml.data(using: String.Encoding.utf8.rawValue), attributes: nil)
FileManager.default.createFile(atPath: exportPath.stringByAppendingPathComponent("feed.xml"), contents: feedXml.data(using: String.Encoding.utf8), attributes: nil)
}
/**
Renders the draft index page, listing only draft articles.
*/
fileprivate func renderDraftIndex() {
indexHtml = footerHtml.copy() as! NSString
for article in articlesToRender {
if article.isDraft {
var html : NSString = snippetHtml.copy() as! NSString
html = html.replacingOccurrences(of: "{#TITLE}", with: article.title) as NSString
html = html.replacingOccurrences(of: "{#DATE}", with: article.dateString) as NSString
html = html.replacingOccurrences(of: "{#AUTHOR}", with: article.author) as NSString
html = html.replacingOccurrences(of: "{#LINK}", with: "drafts/"+article.getUrlPathname()) as NSString
let contentHtml = article.getSummary()
html = html.replacingOccurrences(of: "{#SUMMARY}", with: contentHtml as String) as NSString
indexHtml = NSString(format: "%@\n%@", html,indexHtml)
}
}
indexHtml = headerHtml.appending(indexHtml as String) as NSString
indexHtml = indexHtml.replacingOccurrences(of: "{#BLOG_TITLE}", with: blogTitle + " - Drafts") as NSString
FileManager.default.createFile(atPath: exportPath.stringByAppendingPathComponent("index-drafts.html"), contents: indexHtml.data(using: String.Encoding.utf8.rawValue), attributes: nil)
}
/**
Renders the drafts articles as HTML files on disk, parsing the markdown content and mananging the pictures and ressources.
- parameter forceUpdate: true if previously generated drafts should be generated
*/
fileprivate func renderDrafts(_ forceUpdate : Bool){
if forceUpdate {
cleanFolder("drafts")
}
for article in articlesToRender {
if article.isDraft {
renderArticle(article, inFolder: "drafts", forceUpdate : forceUpdate)
}
}
}
/**
Renders a given article in the given folder, generating an HTML file and additionally copying linked images in a specific sub-folder.
- parameter article: the article to render
- parameter folder: the directory in which the generated HTML article should be exported
- parameter forceUpdate: true if previous version of the article should be erased
*/
fileprivate func renderArticle(_ article : Article, inFolder folder : String, forceUpdate : Bool){
//print("Rendering article: \(article.title)")
let filePath = exportPath.stringByAppendingPathComponent(folder).stringByAppendingPathComponent(article.getUrlPathname())
var contentHtml = markdown.transform(article.content)
contentHtml = addFootnotes(contentHtml)
// Save back, for summary generation.
article.content = contentHtml
if forceUpdate || !FileManager.default.fileExists(atPath: filePath){
var html: NSString = articleHtml.copy() as! NSString
html = html.replacingOccurrences(of: "{#TITLE}", with: article.title) as NSString
html = html.replacingOccurrences(of: "{#DATE}", with: article.dateString) as NSString
html = html.replacingOccurrences(of: "{#AUTHOR}", with: article.author) as NSString
html = html.replacingOccurrences(of: "{#BLOG_TITLE}", with: blogTitle) as NSString
html = html.replacingOccurrences(of: "{#LINK}", with: article.getUrlPathname()) as NSString
html = html.replacingOccurrences(of: "{#SUMMARY}", with: article.getSummary() as String) as NSString
contentHtml = manageFiles(content: contentHtml, path: filePath, forceUpdate : forceUpdate)
// Might want to rework when the supplemental HTML snippet is inserted. Flag in the article ?
if (contentHtml.range(of: "<pre><code>")?.lowerBound != nil ){
html = html.replacingOccurrences(of: "</head>", with: "\n" + (syntaxHtml as String) + "\n</head>") as NSString
}
html = html.replacingOccurrences(of: "{#CONTENT}", with: contentHtml) as NSString
FileManager.default.createFile(atPath: filePath, contents: html.data(using: String.Encoding.utf8.rawValue), attributes: nil)
}
}
//MARK: Additional processing
/**
Parses the article content to detect local file links (images, audio,...), copy the files in an article-specific directory and update the links accordingly.
- parameter content: the content of the article (in HTML)
- parameter filePath: the path to the folder where the files should be copied
- parameter forceUpdate: indicates whether the files should be force-updated or not
- returns: return the updated HTML content of the article
*/
private func manageFiles(content: String, path filePath: String, forceUpdate : Bool) -> String {
let scanner = Scanner(string: content)
var links = Set<String>()
var linkContent : NSString?
while !scanner.isAtEnd {
scanner.scanUpTo("src=\"", into: nil)
if scanner.isAtEnd {
break
}
scanner.scanString("src=\"", into: nil)
scanner.scanUpTo("\"", into: &linkContent)
scanner.scanString("\"", into: nil)
if let link = linkContent, !link.hasPrefix("http") && !link.hasPrefix("www."){
links.insert(String(link))
}
}
if links.isEmpty {
return content
}
var content = content
if !FileManager.default.fileExists(atPath: filePath.stringByDeletingPathExtension) {
do {
try FileManager.default.createDirectory(atPath: filePath.stringByDeletingPathExtension, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
}
for link in links {
let path = expandLink(link)
if FileManager.default.fileExists(atPath: path) {
let newFilePath = filePath.stringByDeletingPathExtension.stringByAppendingPathComponent(path.lastPathComponent)
if forceUpdate || !FileManager.default.fileExists(atPath: newFilePath) {
do {
try FileManager.default.copyItem(atPath: path, toPath: newFilePath)
} catch _ {
print("Unable to copy file \(path)")
}
content = content.replacingOccurrences(of: link, with: filePath.lastPathComponent.stringByDeletingPathExtension.stringByAppendingPathComponent(path.lastPathComponent), options: [], range: nil)
}
} else {
print("Warning: some referenced files were not found")
}
}
return content
}
/**
Convenience method to expand filepaths
- parameter link: the path String to expand
- returns: the expanded path
*/
fileprivate func expandLink(_ link : String) -> String {
if link.hasPrefix("/") {
//Absolute path
return link
} else {
//Relative path
//Apparemment NSFileManager gère ça tout seul, à tester avec des images dans un dossier du dossier parent.
return articlesPath.stringByAppendingPathComponent(link)
}
}
/**
Parses the article content to extract and generate footnotes HTML code.
- parameter content: the content of the article
- returns: the HTML content of the article, with the footnotes added at the end
*/
fileprivate func addFootnotes(_ content : String) -> String{
//TODO: gérer les footnotes référencées
var count = 1
let scanner1 = Scanner(string: content)
var newContent = ""
var tempContent : NSString?
var endContent = "\n<br>\n<br>\n<hr><ol>\n"
var footNote : NSString?
scanner1.scanUpTo("[^", into: &tempContent)
if scanner1.isAtEnd {
if let tempContent = tempContent {
newContent = newContent + (tempContent as String)
}
}
var isFirst = true
var loopUsed = false
while !scanner1.isAtEnd {
loopUsed = true
if let tempContent = tempContent {
if isFirst {
newContent = newContent + (tempContent as String)
isFirst = false
} else {
newContent = newContent + tempContent.substring(from: 1)
}
}
_ = scanner1.scanLocation
scanner1.scanUpTo("]", into: &footNote)
if var footNote : NSString = footNote {
footNote = footNote.substring(from: 2) as NSString
newContent = newContent + "<sup id=\"ref\(count)\"><a class=\"footnote-link\" href=\"#fn\(count)\" title=\"\" rel=\"footnote\">[\(count)]</a></sup>"
endContent = endContent + "<li id=\"fn\(count)\" class=\"footnote\"><p>\(footNote) <a class=\"footnote-link\" href=\"#ref\(count)\" title=\"Return to footnote in the text.\" >↩</a></p></li>\n"
count+=1
}
scanner1.scanUpTo("[^", into: &tempContent)
}
if loopUsed {
if let tempContent = tempContent {
newContent = newContent + tempContent.substring(from: 1)
}
}
endContent += "</ol>\n"
newContent += endContent
return newContent
}
//MARK: Cleaning
/**
Removes everything from the output folder before regenerating the directories
*/
fileprivate func clean(){
if FileManager.default.fileExists(atPath: exportPath) {
do {
try FileManager.default.removeItem(atPath: exportPath)
} catch _ {
print("Unable to delete \(exportPath)")
}
}
var createPath = exportPath
do {
try FileManager.default.createDirectory(atPath: createPath, withIntermediateDirectories: true, attributes: nil)
createPath = exportPath.stringByAppendingPathComponent("articles")
try FileManager.default.createDirectory(atPath: createPath , withIntermediateDirectories: true, attributes: nil)
createPath = exportPath.stringByAppendingPathComponent("drafts")
try FileManager.default.createDirectory(atPath: createPath, withIntermediateDirectories: true, attributes: nil)
} catch _ {
print("Unable to create \(createPath)")
}
}
/**
Cleans the given directory (empties it).
- parameter folder: the path to the folder to clean, relative to the export path
*/
fileprivate func cleanFolder(_ folder : String) {
let folderPath = exportPath.stringByAppendingPathComponent(folder)
if FileManager.default.fileExists(atPath: folderPath) {
do {
try FileManager.default.removeItem(atPath: folderPath)
} catch _ {
print("Unable to delete \(folderPath).")
}
}
do {
try FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
} catch _ {
print("Unable to create \(folderPath).")
}
}
}
| 38.618287 | 214 | 0.663823 |
5021d110e6094b6b93311a8724c51551926678f1 | 2,760 | //
// ViewController.swift
// ServiceDeskKit
//
// Created by willpowell8 on 11/10/2017.
// Copyright (c) 2017 willpowell8. All rights reserved.
//
import UIKit
import ServiceDeskKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
ServiceDesk.shared.setup(host: "{host}", serviceDeskId: "{serviceDeskId}", requestTypeId: "{requestTypeId}")
ServiceDesk.shared.preAuth(username: "{username}", password: "{password}")
ServiceDesk.shared.setup(host: "https://holtrenfrew.atlassian.net", serviceDeskId: "2", requestTypeId: "157")
ServiceDesk.shared.preAuth(username: "[email protected]", password: "R3nfr3w99")
/*ServiceDesk.shared.setup(host: "https://willptest.atlassian.net", serviceDeskId: "1", requestTypeId: "1")
ServiceDesk.shared.preAuth(username: "[email protected]", password: "plokij8u")*/
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
startServiceDesk()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func createPDF()->String{
let fileName = "test.pdf"
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0] as NSString
let pathForPDF = documentsDirectory.appending("/" + fileName)
UIGraphicsBeginPDFContextToFile(pathForPDF, .zero, nil)
let pageSize = CGRect(x:0,y:0,width:400,height:500)
UIGraphicsBeginPDFPageWithInfo(pageSize, nil)
let font = UIFont(name: "Helvetica", size: 12.0)
let textRect = CGRect(x:5,y:5,width:500,height:18)
let paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.alignment = NSTextAlignment.left
paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
let textColor = UIColor.black
let textFontAttributes = [
NSAttributedString.Key.font: font!,
NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.paragraphStyle: paragraphStyle
]
let text = "HELLO WORLD"
text.draw(in: textRect, withAttributes: textFontAttributes)
UIGraphicsEndPDFContext()
return "file://"+pathForPDF
}
func startServiceDesk(){
ServiceDesk.shared.raise(defaultFields: ["customfield_11902":"17801","description":"username: [email protected]","attachment":createPDF()])
}
}
| 37.808219 | 155 | 0.671377 |
f73115d7e4f5bafa66906338f98e81d62b46a1c1 | 343 | //
// BrazilAgeRating.swift
// AppStoreConnect-Swift-SDK
//
// Created by Morten Bjerg Gregersen on 23/08/2020.
//
import Foundation
public enum BrazilAgeRating: String, Codable {
case l = "L"
case ten = "TEN"
case twelve = "TWELVE"
case fourteen = "FOURTEEN"
case sixteen = "SIXTEEN"
case eighteen = "EIGHTEEN"
}
| 19.055556 | 52 | 0.658892 |
ed701247aae73e723cdaf96d8e11e70c2f4690ae | 142 | //
// Receiver.swift
//
protocol Receiver {
associatedtype MessageType: CustomStringConvertible
func receive(message: MessageType)
}
| 15.777778 | 55 | 0.746479 |
e2bbeaaa32e379025d0877cc6a9e630a6241892b | 326 | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "ScrollCounter",
platforms: [
.iOS(.v10),
],
products: [
.library(name: "ScrollCounter", targets: ["ScrollCounter"]),
],
targets: [
.target(name: "ScrollCounter", path: "ScrollCounter"),
]
)
| 20.375 | 68 | 0.58589 |
1ad24f8889a66f4a1a4b1702a9d05e863679d5d3 | 6,515 | //
// SynchronousDataTransaction.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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
import CoreData
// MARK: - SynchronousDataTransaction
/**
The `SynchronousDataTransaction` provides an interface for `DynamicObject` creates, updates, and deletes. A transaction object should typically be only used from within a transaction block initiated from `DataStack.beginSynchronous(_:)`.
*/
public final class SynchronousDataTransaction: BaseDataTransaction {
/**
Cancels a transaction by throwing `CoreStoreError.userCancelled`.
```
try transaction.cancel()
```
- Important: Always use plain `try` on a `cancel()` call. Never use `try?` or `try!`. Using `try?` will swallow the cancellation and the transaction will proceed to commit as normal. Using `try!` will crash the app as `cancel()` will *always* throw an error.
*/
public func cancel() throws -> Never {
throw CoreStoreError.userCancelled
}
// MARK: BaseDataTransaction
/**
Creates a new `NSManagedObject` or `CoreStoreObject` with the specified entity type.
- parameter into: the `Into` clause indicating the destination `NSManagedObject` or `CoreStoreObject` entity type and the destination configuration
- returns: a new `NSManagedObject` or `CoreStoreObject` instance of the specified entity type.
*/
public override func create<O>(_ into: Into<O>) -> O {
Internals.assert(
!self.isCommitted,
"Attempted to create an entity of type \(Internals.typeName(into.entityClass)) from an already committed \(Internals.typeName(self))."
)
return super.create(into)
}
/**
Returns an editable proxy of a specified `NSManagedObject` or `CoreStoreObject`.
- parameter object: the `NSManagedObject` or `CoreStoreObject` to be edited
- returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`.
*/
public override func edit<O: DynamicObject>(_ object: O?) -> O? {
Internals.assert(
!self.isCommitted,
"Attempted to update an entity of type \(Internals.typeName(object)) from an already committed \(Internals.typeName(self))."
)
return super.edit(object)
}
/**
Returns an editable proxy of the object with the specified `NSManagedObjectID`.
- parameter into: an `Into` clause specifying the entity type
- parameter objectID: the `NSManagedObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`.
*/
public override func edit<O>(_ into: Into<O>, _ objectID: NSManagedObjectID) -> O? {
Internals.assert(
!self.isCommitted,
"Attempted to update an entity of type \(Internals.typeName(into.entityClass)) from an already committed \(Internals.typeName(self))."
)
return super.edit(into, objectID)
}
/**
Deletes the objects with the specified `NSManagedObjectID`s.
- parameter objectIDs: the `NSManagedObjectID`s of the objects to delete
*/
public override func delete<S: Sequence>(objectIDs: S) where S.Iterator.Element: NSManagedObjectID {
Internals.assert(
!self.isCommitted,
"Attempted to delete an entities from an already committed \(Internals.typeName(self))."
)
super.delete(objectIDs: objectIDs)
}
/**
Deletes the specified `NSManagedObject`s or `CoreStoreObject`s represented by series of `ObjectRepresentation`s.
- parameter object: the `ObjectRepresentation` representing an `NSManagedObject` or `CoreStoreObject` to be deleted
- parameter objects: other `ObjectRepresentation`s representing `NSManagedObject`s or `CoreStoreObject`s to be deleted
*/
public override func delete<O: ObjectRepresentation>(_ object: O?, _ objects: O?...) {
Internals.assert(
!self.isCommitted,
"Attempted to delete an entities from an already committed \(Internals.typeName(self))."
)
super.delete(([object] + objects).compactMap { $0 })
}
/**
Deletes the specified `NSManagedObject`s or `CoreStoreObject`s represented by an `ObjectRepresenation`.
- parameter objects: the `ObjectRepresenation`s representing `NSManagedObject`s or `CoreStoreObject`s to be deleted
*/
public override func delete<S: Sequence>(_ objects: S) where S.Iterator.Element: ObjectRepresentation {
Internals.assert(
!self.isCommitted,
"Attempted to delete an entities from an already committed \(Internals.typeName(self))."
)
super.delete(objects)
}
// MARK: Internal
internal init(mainContext: NSManagedObjectContext, queue: DispatchQueue) {
super.init(mainContext: mainContext, queue: queue, supportsUndo: false, bypassesQueueing: false)
}
internal func autoCommit(waitForMerge: Bool) -> (hasChanges: Bool, error: CoreStoreError?) {
self.isCommitted = true
let result = self.context.saveSynchronously(waitForMerge: waitForMerge)
self.result = result
defer {
self.context.reset()
}
return result
}
}
| 39.011976 | 263 | 0.677667 |
e25f37658f9586da30116255595190c0fd8c065a | 2,140 | //
// AppDelegate.swift
// ChoicewordDemo
//
// Created by Chakery on 16/9/2.
// Copyright © 2016年 Chakery. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.531915 | 285 | 0.754206 |
9cbdac09bf429d9f459e300cbe9f6e86fd90d47e | 446 | import SwiftUI
struct PlaceIndicator: View {
// MARK: - Properties
let text: String
let isA: Bool
// MARK: - UI Elements
var body: some View {
Text(text)
.font(.system(size: 30, design: .rounded))
.bold()
.foregroundColor(isA ? .white : .black)
.padding()
.background(Circle().fill(isA ? Color.mainBackground : Color.indicatorBackground))
}
}
| 23.473684 | 94 | 0.549327 |
b9758dfa920df460f9543a588d8284edb29368b9 | 553 | //
// RemoveDuplicatesFromSortedOrderLinkedListTest.swift
// AlgorithmsTests
//
// Created by Tieda Wei on 2021-02-06.
//
import XCTest
@testable import Algorithms
class RemoveDuplicatesFromSortedOrderLinkedListTest: XCTestCase {
func test() {
[
([1], "[1]"),
([1, 2, 3], "[1, 2, 3]"),
([1, 1, 3, 4, 4, 4, 5, 6, 6], "[1, 3, 4, 5, 6]")
].forEach { (list, result) in
expect(result, when: RemoveDuplicatesFromSortedOrderLinkedList.solution(list: list).description)
}
}
}
| 25.136364 | 108 | 0.58047 |
76e1d6e94c9c4699be15483c4a2a02f19452ea71 | 347 | //
// AUITitlePickerItemController.swift
// Level
//
// Created by Ihor Myroniuk on 11/7/18.
// Copyright © 2018 Brander. All rights reserved.
//
import Foundation
public protocol AUITitlePickerItemController: AUIPickerItemController {
// MARK: Title
var title: String? { get }
var attributedTitle: NSAttributedString? { get }
}
| 19.277778 | 71 | 0.717579 |
7a2910c4490fdde6f5c8362a0246227ec0a66a7e | 1,160 | // https://github.com/Quick/Quick
import Quick
import Nimble
import KDCalenderPicker
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| 22.745098 | 60 | 0.361207 |
0975880600adaf43f9ea674b1320abd8c87d3f73 | 1,102 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "FluentSQLite",
products: [
.library(name: "FluentSQLite", targets: ["FluentSQLite"]),
],
dependencies: [
// 🌎 Utility package containing tools for byte manipulation, Codable, OS APIs, and debugging.
.package(url: "https://github.com/vapor/core.git", from: "3.0.0"),
// ✳️ Swift ORM framework (queries, models, and relations) for building NoSQL and SQL database integrations.
.package(url: "https://github.com/smeger/fluent.git", from: "3.0.0-rc"),
// 📦 Dependency injection / inversion of control framework.
.package(url: "https://github.com/vapor/service.git", from: "1.0.0"),
// 🔵 SQLite 3 wrapper for Swift
.package(url: "https://github.com/vapor/sqlite.git", from: "3.0.0-rc"),
],
targets: [
.target(name: "FluentSQLite", dependencies: ["Async", "FluentSQL", "Service", "SQLite"]),
.testTarget(name: "FluentSQLiteTests", dependencies: ["FluentBenchmark", "FluentSQLite", "SQLite"]),
]
)
| 40.814815 | 116 | 0.627042 |
69b4440f323cd4e08a08fe399c29ad409472dc8b | 516 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "Stripe",
defaultLocalization: "en",
platforms: [
.iOS(.v11)
],
products: [
.library(
name: "Stripe",
targets: ["Stripe"]
)
],
targets: [
.binaryTarget(
name: "Stripe",
url: "https://d37ugbyn3rpeym.cloudfront.net/terminal/payments-ios-releases/21.0.1/Stripe.xcframework.zip",
checksum: "d42ac188d64ae2106402f96e78eeebd00e3f9a0b037bb9f7ae8d9d69f95f5027"
)
]
)
| 21.5 | 112 | 0.641473 |
38acaf1cf2fa3e9d8d9dd1131120b1c79923903f | 2,104 | //
// Reusable.swift
// GBHFacebookImagePicker
//
// Created by Florian Gabach on 21/11/2018.
//
import UIKit
public protocol Reusable: class {
static var reuseIdentifier: String { get }
}
public extension Reusable {
static var reuseIdentifier: String {
return String(describing: self)
}
}
extension UITableView {
final func register<T: UITableViewCell>(cellType: T.Type)
where T: Reusable {
self.register(cellType.self, forCellReuseIdentifier: cellType.reuseIdentifier)
}
final func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath, cellType: T.Type = T.self) -> T
where T: Reusable {
guard let cell = self.dequeueReusableCell(withIdentifier: cellType.reuseIdentifier, for: indexPath) as? T else {
fatalError(
"Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). "
+ "Check that the reuseIdentifier is set properly in your XIB/Storyboard "
+ "and that you registered the cell beforehand"
)
}
return cell
}
}
extension UICollectionView {
func register<T: UICollectionViewCell>(cellType: T.Type)
where T: Reusable {
self.register(cellType.self, forCellWithReuseIdentifier: cellType.reuseIdentifier)
}
func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath, cellType: T.Type = T.self) -> T
where T: Reusable {
let bareCell = self.dequeueReusableCell(withReuseIdentifier: cellType.reuseIdentifier, for: indexPath)
guard let cell = bareCell as? T else {
fatalError(
"Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). "
+ "Check that the reuseIdentifier is set properly in your XIB/Storyboard "
+ "and that you registered the cell beforehand"
)
}
return cell
}
}
| 36.275862 | 124 | 0.627376 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.