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
bbcaa6004a94d1f6dce021c35af8f9590c319a24
173
import Foundation extension unichar: ExpressibleByUnicodeScalarLiteral { public init(unicodeScalarLiteral value: Character) { self = value.utf16.first! } }
21.625
56
0.739884
79faa603e4504bae0cc33e67da4e46e784b1d00f
1,398
// // ThirdOBViewController.swift // AnywhereFitness // // Created by Dillon P on 10/27/19. // Copyright © 2019 Julltron. All rights reserved. // import UIKit class ThirdOBViewController: UIViewController { @IBOutlet weak var cancelBtnImage: UIImageView! @IBOutlet weak var getStartedButton: UIButton! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) cancelBtnImage.pulsate() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ @IBAction func getStartedTapped(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "AppHomeStoryboard") vc.modalPresentationStyle = .fullScreen self.present(vc, animated: true, completion: nil) } }
29.125
106
0.660944
3a8aa5a3d05bd7af7b35dfea2e947fe95d1d5f57
1,207
/** * (C) Copyright IBM Corp. 2021. * * 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 /** An object specifying target channels available for the transfer. Each property of this object represents an available transfer target. Currently, the only supported property is **chat**, representing the web chat integration. */ public struct ChannelTransferTarget: Codable, Equatable { /** Information for transferring to the web chat integration. */ public var chat: ChannelTransferTargetChat? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case chat = "chat" } }
33.527778
118
0.732394
76220b984fd03231adb584f8ffa4e1c75045300c
3,394
// // AppDelegate.swift // HSSDKXSwiftSample // // Created by Sagar Dagdu on 24/05/21. // Copyright © 2021 Sagar Dagdu. All rights reserved. // import UIKit import UserNotifications import HelpshiftX @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { #warning("TODO: To start using this project, copy-paste your APP_ID as the value of hsPlatformId and comment this line") let hsPlatformId = ""; #warning("TODO: To start using this project, copy-paste your DOMAIN as the value of hsDomain and comment this line") let hsDomain = ""; Helpshift.install(withPlatformId: hsPlatformId, domain: hsDomain, config: nil) // Set the delegate Helpshift.sharedInstance().delegate = HelpshiftEventsHandler.shared; registerForPush() //handle when app is not in background and opened for push notification if let launchOptions = launchOptions { if let userInfo = launchOptions[UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable:Any], let origin = userInfo["origin"] as? String, origin == "helpshift" { Helpshift.handleNotification(withUserInfoDictionary: userInfo, isAppLaunch: true, with: (window?.rootViewController)!) } } return true } } //MARK:- Push Notifications extension AppDelegate: UNUserNotificationCenterDelegate { func registerForPush() { #if targetEnvironment(simulator) // there is no push on simulator so skip #else let notificationCenter = UNUserNotificationCenter.current() notificationCenter.delegate = self notificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in guard error == nil else { print("Error while requesting Notification permissions.") return } if granted { DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } #endif } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Helpshift.registerDeviceToken(deviceToken) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Error in registering for remote notifications: \(error)") } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo if let origin = userInfo["origin"] as? String, origin == "helpshift" { print("userNotificationCenter:willPresentNotification for helpshift origin") Helpshift.handleNotification(withUserInfoDictionary: userInfo, isAppLaunch: false, with: (window?.rootViewController)!) } completionHandler([]) } }
37.711111
207
0.666176
791826b12a3e9e8bca2d155ec11a8ceea5e1e307
2,340
// // Error+Extension.swift // Wei // // Created by yuzushioh on 2018/04/25. // Copyright © 2018 popshoot All rights reserved. // import Foundation import EthereumKit extension APIClientError: AlertConvertable { var title: String? { switch self { case .connectionError: return R.string.localizable.errorTitleNoConnection() case .systemError: return R.string.localizable.errorTitleSystemError() } } var message: String? { switch self { case .connectionError: return R.string.localizable.errorMessageNoConnection() case .systemError: return R.string.localizable.errorMessageSystemError() } } } extension EthereumKitError: AlertConvertable { var title: String? { switch self { case .cryptoError, .requestError: return R.string.localizable.errorTitleUnexpected() case .responseError(let error): switch error { case .connectionError: return R.string.localizable.errorTitleNoConnection() case .jsonrpcError(let error): switch error { case .responseError(_, let message, _): return message default: return R.string.localizable.errorTitleSystemError() } default: return R.string.localizable.errorTitleSystemError() } case .contractError, .convertError: fatalError("EthereumKit.ContractError should not be thrown in Wei wallet") } } var message: String? { switch self { case .cryptoError, .requestError: return R.string.localizable.errorMessageUnexpected() case .responseError(let error): switch error { case .connectionError: return R.string.localizable.errorMessageNoConnection() default: return R.string.localizable.errorMessageSystemError() } case .contractError, .convertError: fatalError("EthereumKit.ContractError should not be thrown in Wei wallet") } } }
29.25
86
0.564103
f558399ebfde602ea55f346f24e693b4a0dc95d5
1,064
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "DictionaryEncoder", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "DictionaryEncoder", targets: ["DictionaryEncoder"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "DictionaryEncoder", dependencies: []), .testTarget( name: "DictionaryEncoderTests", dependencies: ["DictionaryEncoder"]), ] )
36.689655
117
0.636278
f988a8c639cb6e51e08083f906f151b85b10d97c
1,092
// Copyright 2020, OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import OpenTelemetryApi /// Interface for getting the current time. public protocol Clock: AnyObject { /// Obtains the current epoch timestamp in nanos from this clock. var now: UInt64 { get } /// Returns a time measurement with nanosecond precision that can only be used to calculate elapsed /// time. var nanoTime: UInt64 { get } } public func == (lhs: Clock, rhs: Clock) -> Bool { return lhs.now == rhs.now && lhs.nanoTime == rhs.nanoTime }
34.125
103
0.722527
2382e03fdc72351ae50e1e17451dd0dc79957316
1,910
import Foundation struct Instruction { var cmd: Character var value: Int } func getInput() -> [Instruction] { var res = [Instruction]() let contents = try! String(contentsOfFile: "./inputs/day12.txt", encoding: .utf8) for cmd in contents.split(separator: "\n") { res.append(Instruction( cmd: cmd[cmd.startIndex], value: Int(cmd[cmd.index(after: cmd.startIndex)...])! )) } return res } func intRotate(vec: (Int, Int), deg: Int) -> (Int, Int) { let toDeg = Double.pi / 180 let x = Double(vec.0) * cos(toDeg*Double(deg)) - Double(vec.1) * sin(toDeg*Double(deg)) let y = Double(vec.0) * sin(toDeg*Double(deg)) + Double(vec.1) * cos(toDeg*Double(deg)) return (Int(x.rounded()), Int(y.rounded())) } func part1() -> Int { var dir = (1, 0) var pos = (0, 0) for instr in getInput() { switch instr.cmd { case "F": pos.0 += dir.0 * instr.value pos.1 += dir.1 * instr.value case "L": dir = intRotate(vec: dir, deg: instr.value) case "R": dir = intRotate(vec: dir, deg: 360 - instr.value) case "N": pos.1 += instr.value case "E": pos.0 += instr.value case "S": pos.1 -= instr.value case "W": pos.0 -= instr.value default: break; } } return abs(pos.0) + abs(pos.1) } func part2() -> Int { var pos = (0, 0) var waypoint = (10, 1) for instr in getInput() { switch instr.cmd { case "F": pos.0 += waypoint.0 * instr.value pos.1 += waypoint.1 * instr.value case "L": waypoint = intRotate(vec: waypoint, deg: instr.value) case "R": waypoint = intRotate(vec: waypoint, deg: 360 - instr.value) case "N": waypoint.1 += instr.value case "E": waypoint.0 += instr.value case "S": waypoint.1 -= instr.value case "W": waypoint.0 -= instr.value default: break; } } return abs(pos.0) + abs(pos.1) } print(""" day 12: part 1: \(part1()) part 2: \(part2()) """)
20.105263
88
0.589529
bb55b6039986481278d433fa6ac52e2dba27b9cc
24,909
/* This source file is part of the Swift.org open source project Copyright (c) 2018 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 Foundation // MARK: - file system extension Package { /// A package dependency of a Swift package. /// /// A package dependency consists of a Git URL to the source of the package, /// and a requirement for the version of the package. /// /// The Swift Package Manager performs a process called *dependency resolution* to /// figure out the exact version of the package dependencies that an app or other /// Swift package can use. The `Package.resolved` file records the results of the /// dependency resolution and lives in the top-level directory of a Swift package. /// If you add the Swift package as a package dependency to an app for an Apple platform, /// you can find the `Package.resolved` file inside your `.xcodeproj` or `.xcworkspace`. public class Dependency: Encodable { @available(_PackageDescription, introduced: 5.6) public enum Kind { case fileSystem(name: String?, path: String) case sourceControl(name: String?, location: String, requirement: SourceControlRequirement) case registry(id: String, requirement: RegistryRequirement) } @available(_PackageDescription, introduced: 5.6) public let kind: Kind /// The name of the dependency, or `nil` to deduce the name using the package's Git URL. @available(_PackageDescription, deprecated: 5.6, message: "use kind instead") public var name: String? { get { switch self.kind { case .fileSystem(name: let name, path: _): return name case .sourceControl(name: let name, location: _, requirement: _): return name case .registry: return nil } } } /// The location of the dependency. @available(_PackageDescription, deprecated: 5.6, message: "use kind instead") public var url: String? { get { switch self.kind { case .fileSystem(name: _, path: let path): return path case .sourceControl(name: _, location: let location, requirement: _): return location case .registry: return nil } } } /// The requirement of the dependency. @available(_PackageDescription, deprecated: 5.6, message: "use kind instead") public var requirement: Requirement { get { switch self.kind { case .fileSystem: return .localPackageItem case .sourceControl(name: _, location: _, requirement: let requirement): switch requirement { case .branch(let branch): return .branchItem(branch) case .exact(let version): return .exactItem(version) case .range(let range): return .rangeItem(range) case .revision(let revision): return .revisionItem(revision) } case .registry(id: _, requirement: let requirement): switch requirement { case .exact(let version): return .exactItem(version) case .range(let range): return .rangeItem(range) } } } } /// Initializes and returns a newly allocated requirement with the specified url and requirements. @available(_PackageDescription, deprecated: 5.6) convenience init(name: String?, url: String, requirement: Requirement) { switch requirement { case .localPackageItem: self.init(name: name, path: url) case .branchItem(let branch): self.init(name: name, location: url, requirement: .branch(branch)) case .exactItem(let version): self.init(name: name, location: url, requirement: .exact(version)) case .revisionItem(let revision): self.init(name: name, location: url, requirement: .revision(revision)) case .rangeItem(let range): self.init(name: name, location: url, requirement: .range(range)) } } init(kind: Kind) { self.kind = kind } convenience init(name: String?, path: String) { self.init(kind: .fileSystem(name: name, path: path)) } convenience init(name: String?, location: String, requirement: SourceControlRequirement) { self.init(kind: .sourceControl(name: name, location: location, requirement: requirement)) } convenience init(id: String, requirement: RegistryRequirement) { self.init(kind: .registry(id: id, requirement: requirement)) } } } // MARK: - file system extension Package.Dependency { /// Adds a package dependency to a local package on the filesystem. /// /// The Swift Package Manager uses the package dependency as-is /// and does not perform any source control access. Local package dependencies /// are especially useful during development of a new package or when working /// on multiple tightly coupled packages. /// /// - Parameters /// - path: The file system path to the package. public static func package( path: String ) -> Package.Dependency { return .init(name: nil, path: path) } /// Adds a package dependency to a local package on the filesystem. /// /// The Swift Package Manager uses the package dependency as-is /// and doesn't perform any source control access. Local package dependencies /// are especially useful during development of a new package or when working /// on multiple tightly coupled packages. /// /// - Parameters /// - name: The name of the Swift package, used only for target dependencies lookup. /// - path: The file system path to the package. @available(_PackageDescription, introduced: 5.2) public static func package( name: String, path: String ) -> Package.Dependency { return .init(name: name, path: path) } } // MARK: - source control extension Package.Dependency { /// Adds a package dependency that uses the version requirement, starting with the given minimum version, /// going up to the next major version. /// /// This is the recommended way to specify a remote package dependency. /// It allows you to specify the minimum version you require, allows updates that include bug fixes /// and backward-compatible feature updates, but requires you to explicitly update to a new major version of the dependency. /// This approach provides the maximum flexibility on which version to use, /// while making sure you don't update to a version with breaking changes, /// and helps to prevent conflicts in your dependency graph. /// /// The following example allows the Swift Package Manager to select a version /// like a `1.2.3`, `1.2.4`, or `1.3.0`, but not `2.0.0`. /// /// .package(url: "https://example.com/example-package.git", from: "1.2.3"), /// /// - Parameters: /// - name: The name of the package, or nil to deduce it from the URL. /// - url: The valid Git URL of the package. /// - version: The minimum version requirement. public static func package( url: String, from version: Version ) -> Package.Dependency { return .package(url: url, .upToNextMajor(from: version)) } /// Adds a package dependency that uses the version requirement, starting with the given minimum version, /// going up to the next major version. /// /// This is the recommended way to specify a remote package dependency. /// It allows you to specify the minimum version you require, allows updates that include bug fixes /// and backward-compatible feature updates, but requires you to explicitly update to a new major version of the dependency. /// This approach provides the maximum flexibility on which version to use, /// while making sure you don't update to a version with breaking changes, /// and helps to prevent conflicts in your dependency graph. /// /// The following example allows the Swift Package Manager to select a version /// like a `1.2.3`, `1.2.4`, or `1.3.0`, but not `2.0.0`. /// /// .package(url: "https://example.com/example-package.git", from: "1.2.3"), /// /// - Parameters: /// - name: The name of the package, or nil to deduce it from the URL. /// - url: The valid Git URL of the package. /// - version: The minimum version requirement. @available(_PackageDescription, introduced: 5.2, deprecated: 5.6, message: "use package(url:from:) instead") public static func package( name: String, url: String, from version: Version ) -> Package.Dependency { return .package(name: name, url: url, .upToNextMajor(from: version)) } /// Adds a remote package dependency given a branch requirement. /// /// .package(url: "https://example.com/example-package.git", branch: "main"), /// /// - Parameters: /// - url: The valid Git URL of the package. /// - branch: A dependency requirement. See static methods on `Package.Dependency.Requirement` for available options. @available(_PackageDescription, introduced: 5.5) public static func package( url: String, branch: String ) -> Package.Dependency { return .package(url: url, requirement: .branch(branch)) } /// Adds a remote package dependency given a branch requirement. /// /// .package(url: "https://example.com/example-package.git", branch: "main"), /// /// - Parameters: /// - name: The name of the package, or nil to deduce it from the URL. /// - url: The valid Git URL of the package. /// - branch: A dependency requirement. See static methods on `Package.Dependency.Requirement` for available options. @available(_PackageDescription, introduced: 5.5, deprecated: 5.6, message: "use package(url:branch:) instead") public static func package( name: String, url: String, branch: String ) -> Package.Dependency { return .package(name: name, url: url, requirement: .branch(branch)) } /// Adds a remote package dependency given a revision requirement. /// /// .package(url: "https://example.com/example-package.git", revision: "aa681bd6c61e22df0fd808044a886fc4a7ed3a65"), /// /// - Parameters: /// - url: The valid Git URL of the package. /// - revision: A dependency requirement. See static methods on `Package.Dependency.Requirement` for available options. @available(_PackageDescription, introduced: 5.5) public static func package( url: String, revision: String ) -> Package.Dependency { return .package(url: url, requirement: .revision(revision)) } /// Adds a remote package dependency given a revision requirement. /// /// .package(url: "https://example.com/example-package.git", revision: "aa681bd6c61e22df0fd808044a886fc4a7ed3a65"), /// /// - Parameters: /// - name: The name of the package, or nil to deduce it from the URL. /// - url: The valid Git URL of the package. /// - revision: A dependency requirement. See static methods on `Package.Dependency.Requirement` for available options. @available(_PackageDescription, introduced: 5.5, deprecated: 5.6, message: "use package(url:revision:) instead") public static func package( name: String, url: String, revision: String ) -> Package.Dependency { return .package(name: name, url: url, requirement: .revision(revision)) } /// Adds a package dependency starting with a specific minimum version, up to /// but not including a specified maximum version. /// /// The following example allows the Swift Package Manager to pick /// versions `1.2.3`, `1.2.4`, `1.2.5`, but not `1.2.6`. /// /// .package(url: "https://example.com/example-package.git", "1.2.3"..<"1.2.6"), /// /// - Parameters: /// - name: The name of the package, or nil to deduce it from the URL. /// - url: The valid Git URL of the package. /// - range: The custom version range requirement. public static func package( url: String, _ range: Range<Version> ) -> Package.Dependency { return .package(name: nil, url: url, requirement: .range(range)) } /// Adds a package dependency starting with a specific minimum version, up to /// but not including a specified maximum version. /// /// The following example allows the Swift Package Manager to pick /// versions `1.2.3`, `1.2.4`, `1.2.5`, but not `1.2.6`. /// /// .package(url: "https://example.com/example-package.git", "1.2.3"..<"1.2.6"), /// /// - Parameters: /// - name: The name of the package, or `nil` to deduce it from the URL. /// - url: The valid Git URL of the package. /// - range: The custom version range requirement. @available(_PackageDescription, introduced: 5.2, deprecated: 5.6, message: "use package(url:_:) instead") public static func package( name: String, url: String, _ range: Range<Version> ) -> Package.Dependency { return .package(name: name, url: url, requirement: .range(range)) } /// Adds a package dependency starting with a specific minimum version, going /// up to and including a specific maximum version. /// /// The following example allows the Swift Package Manager to pick /// versions 1.2.3, 1.2.4, 1.2.5, as well as 1.2.6. /// /// .package(url: "https://example.com/example-package.git", "1.2.3"..."1.2.6"), /// /// - Parameters: /// - name: The name of the package, or `nil` to deduce it from the URL. /// - url: The valid Git URL of the package. /// - range: The closed version range requirement. public static func package( url: String, _ range: ClosedRange<Version> ) -> Package.Dependency { return .package(name: nil, url: url, closedRange: range) } /// Adds a package dependency starting with a specific minimum version, going /// up to and including a specific maximum version. /// /// The following example allows the Swift Package Manager to pick /// versions 1.2.3, 1.2.4, 1.2.5, as well as 1.2.6. /// /// .package(url: "https://example.com/example-package.git", "1.2.3"..."1.2.6"), /// /// - Parameters: /// - name: The name of the package, or `nil` to deduce it from the URL. /// - url: The valid Git URL of the package. /// - range: The closed version range requirement. @available(_PackageDescription, introduced: 5.2, deprecated: 5.6, message: "use package(url:_:) instead") public static func package( name: String, url: String, _ range: ClosedRange<Version> ) -> Package.Dependency { return .package(name: name, url: url, closedRange: range) } private static func package( name: String?, url: String, closedRange: ClosedRange<Version> ) -> Package.Dependency { // Increase upperbound's patch version by one. let upper = closedRange.upperBound let upperBound = Version( upper.major, upper.minor, upper.patch + 1, prereleaseIdentifiers: upper.prereleaseIdentifiers, buildMetadataIdentifiers: upper.buildMetadataIdentifiers) return .package(name: name, url: url, requirement: .range(closedRange.lowerBound ..< upperBound)) } /// Adds a package dependency that uses the exact version requirement. /// /// This is the recommended way to specify a remote package dependency. /// It allows you to specify the minimum version you require, allows updates that include bug fixes /// and backward-compatible feature updates, but requires you to explicitly update to a new major version of the dependency. /// This approach provides the maximum flexibility on which version to use, /// while making sure you don't update to a version with breaking changes, /// and helps to prevent conflicts in your dependency graph. /// /// The following example instruct the Swift Package Manager to use version `1.2.3`. /// /// .package(url: "https://example.com/example-package.git", exact: "1.2.3"), /// /// - Parameters: /// - url: The valid Git URL of the package. /// - version: The minimum version requirement. @available(_PackageDescription, introduced: 5.6) public static func package( url: String, exact version: Version ) -> Package.Dependency { return .package(url: url, requirement: .exact(version)) } /// Adds a remote package dependency given a version requirement. /// /// - Parameters: /// - name: The name of the package, or nil to deduce it from the URL. /// - url: The valid Git URL of the package. /// - requirement: A dependency requirement. See static methods on `Package.Dependency.Requirement` for available options. @available(_PackageDescription, deprecated: 5.6, message: "use specific requirement APIs instead (e.g. use 'branch:' instead of '.branch')") public static func package( url: String, _ requirement: Package.Dependency.Requirement ) -> Package.Dependency { return .package(name: nil, url: url, requirement) } /// Adds a remote package dependency with a given version requirement. /// /// - Parameters: /// - name: The name of the package, or `nil` to deduce it from the URL. /// - url: The valid Git URL of the package. /// - requirement: A dependency requirement. See static methods on `Package.Dependency.Requirement` for available options. @available(_PackageDescription, introduced: 5.2, deprecated: 5.6, message: "use specific requirement APIs instead (e.g. use 'branch:' instead of '.branch')") public static func package( name: String?, url: String, _ requirement: Package.Dependency.Requirement ) -> Package.Dependency { precondition(!requirement.isLocalPackage, "Use `.package(path:)` API to declare a local package dependency") return .init(name: name, url: url, requirement: requirement) } // intentionally private to hide enum detail private static func package( name: String? = nil, url: String, requirement: Package.Dependency.SourceControlRequirement ) -> Package.Dependency { return .init(name: name, location: url, requirement: requirement) } } // MARK: - registry extension Package.Dependency { /// Adds a package dependency that uses the version requirement, starting with the given minimum version, /// going up to the next major version. /// /// This is the recommended way to specify a remote package dependency. /// It allows you to specify the minimum version you require, allows updates that include bug fixes /// and backward-compatible feature updates, but requires you to explicitly update to a new major version of the dependency. /// This approach provides the maximum flexibility on which version to use, /// while making sure you don't update to a version with breaking changes, /// and helps to prevent conflicts in your dependency graph. /// /// The following example allows the Swift Package Manager to select a version /// like a `1.2.3`, `1.2.4`, or `1.3.0`, but not `2.0.0`. /// /// .package(id: "scope.name", from: "1.2.3"), /// /// - Parameters: /// - id: The identity of the package. /// - version: The minimum version requirement. @available(_PackageDescription, introduced: 999) public static func package( id: String, from version: Version ) -> Package.Dependency { return .package(id: id, .upToNextMajor(from: version)) } /// Adds a package dependency that uses the exact version requirement. /// /// This is the recommended way to specify a remote package dependency. /// It allows you to specify the minimum version you require, allows updates that include bug fixes /// and backward-compatible feature updates, but requires you to explicitly update to a new major version of the dependency. /// This approach provides the maximum flexibility on which version to use, /// while making sure you don't update to a version with breaking changes, /// and helps to prevent conflicts in your dependency graph. /// /// The following example instruct the Swift Package Manager to use version `1.2.3`. /// /// .package(id: "scope.name", exact: "1.2.3"), /// /// - Parameters: /// - id: The identity of the package. /// - version: The minimum version requirement. @available(_PackageDescription, introduced: 999) public static func package( id: String, exact version: Version ) -> Package.Dependency { return .package(id: id, requirement: .exact(version)) } /// Adds a package dependency starting with a specific minimum version, up to /// but not including a specified maximum version. /// /// The following example allows the Swift Package Manager to pick /// versions `1.2.3`, `1.2.4`, `1.2.5`, but not `1.2.6`. /// /// .package(id: "scope.name", "1.2.3"..<"1.2.6"), /// /// - Parameters: /// - id: The identity of the package. /// - range: The custom version range requirement. @available(_PackageDescription, introduced: 999) public static func package( id: String, _ range: Range<Version> ) -> Package.Dependency { return .package(id: id, requirement: .range(range)) } /// Adds a package dependency starting with a specific minimum version, going /// up to and including a specific maximum version. /// /// The following example allows the Swift Package Manager to pick /// versions 1.2.3, 1.2.4, 1.2.5, as well as 1.2.6. /// /// .package(id: "scope.name", "1.2.3"..."1.2.6"), /// /// - Parameters: /// - id: The identity of the package. /// - range: The closed version range requirement. @available(_PackageDescription, introduced: 999) public static func package( id: String, _ range: ClosedRange<Version> ) -> Package.Dependency { // Increase upperbound's patch version by one. let upper = range.upperBound let upperBound = Version( upper.major, upper.minor, upper.patch + 1, prereleaseIdentifiers: upper.prereleaseIdentifiers, buildMetadataIdentifiers: upper.buildMetadataIdentifiers) return .package(id: id, range.lowerBound ..< upperBound) } // intentionally private to hide enum detail @available(_PackageDescription, introduced: 999) private static func package( id: String, requirement: Package.Dependency.RegistryRequirement ) -> Package.Dependency { let pattern = #"\A[a-zA-Z\d](?:[a-zA-Z\d]|-(?=[a-zA-Z\d])){0,38}\.[a-zA-Z0-9](?:[a-zA-Z0-9]|[-_](?=[a-zA-Z0-9])){0,99}\z"# if id.range(of: pattern, options: .regularExpression) == nil { errors.append("Invalid package identifier: \(id)") } return .init(id: id, requirement: requirement) } } // MARK: - common APIs used by mistake as unavailable to provide better error messages. extension Package.Dependency { @available(*, unavailable, message: "use package(url:exact:) instead") public static func package(url: String, version: Version) -> Package.Dependency { fatalError() } @available(*, unavailable, message: "use package(url:_:) instead") public static func package(url: String, range: Range<Version>) -> Package.Dependency { fatalError() } }
43.471204
161
0.626079
fb9053317c225b7e3efa6ddb12c8dc231fe1f183
7,550
import Flutter import UIKit import iOSDFULibrary import CoreBluetooth public class SwiftFlutterNordicDfuPlugin: NSObject, FlutterPlugin, DFUServiceDelegate, DFUProgressDelegate, LoggerDelegate { let registrar: FlutterPluginRegistrar let channel: FlutterMethodChannel var pendingResult: FlutterResult? var deviceAddress: String? init(_ registrar: FlutterPluginRegistrar, _ channel: FlutterMethodChannel) { self.registrar = registrar self.channel = channel } public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "com.timeyaa.flutter_nordic_dfu/method", binaryMessenger: registrar.messenger()) let instance = SwiftFlutterNordicDfuPlugin(registrar, channel) registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { if (call.method == "startDfu") { guard let arguments = call.arguments as? Dictionary<String, AnyObject> else { result(FlutterError(code: "ABNORMAL_PARAMETER", message: "no parameters", details: nil)) return } let name = arguments["name"] as? String guard let address = arguments["address"] as? String, var filePath = arguments["filePath"] as? String else { result(FlutterError(code: "ABNORMAL_PARAMETER", message: "address and filePath are required", details: nil)) return } let forceDfu = arguments["forceDfu"] as? Bool let enableUnsafeExperimentalButtonlessServiceInSecureDfu = arguments["enableUnsafeExperimentalButtonlessServiceInSecureDfu"] as? Bool let fileInAsset = (arguments["fileInAsset"] as? Bool) ?? false if (fileInAsset) { let key = registrar.lookupKey(forAsset: filePath) guard let pathInAsset = Bundle.main.path(forResource: key, ofType: nil) else { result(FlutterError(code: "ABNORMAL_PARAMETER", message: "file in asset not found \(filePath)", details: nil)) return } filePath = pathInAsset } let alternativeAdvertisingNameEnabled = arguments["alternativeAdvertisingNameEnabled"] as? Bool startDfu(address, name: name, filePath: filePath, forceDfu: forceDfu, enableUnsafeExperimentalButtonlessServiceInSecureDfu: enableUnsafeExperimentalButtonlessServiceInSecureDfu, alternativeAdvertisingNameEnabled: alternativeAdvertisingNameEnabled, result: result) } } private func startDfu( _ address: String, name: String?, filePath: String, forceDfu: Bool?, enableUnsafeExperimentalButtonlessServiceInSecureDfu: Bool?, alternativeAdvertisingNameEnabled: Bool?, result: @escaping FlutterResult) { guard let uuid = UUID(uuidString: address) else { result(FlutterError(code: "DEVICE_ADDRESS_ERROR", message: "Device address conver to uuid failed", details: "Device uuid \(address) convert to uuid failed")) return } guard let firmware = DFUFirmware(urlToZipFile: URL(fileURLWithPath: filePath)) else { result(FlutterError(code: "DFU_FIRMWARE_NOT_FOUND", message: "Could not dfu zip file", details: nil)) return } let dfuInitiator = DFUServiceInitiator(queue: nil) .with(firmware: firmware); dfuInitiator.delegate = self dfuInitiator.progressDelegate = self dfuInitiator.logger = self if let enableUnsafeExperimentalButtonlessServiceInSecureDfu = enableUnsafeExperimentalButtonlessServiceInSecureDfu { dfuInitiator.enableUnsafeExperimentalButtonlessServiceInSecureDfu = enableUnsafeExperimentalButtonlessServiceInSecureDfu } if let forceDfu = forceDfu { dfuInitiator.forceDfu = forceDfu } if let alternativeAdvertisingNameEnabled = alternativeAdvertisingNameEnabled { dfuInitiator.alternativeAdvertisingNameEnabled = alternativeAdvertisingNameEnabled } pendingResult = result deviceAddress = address _ = dfuInitiator.start(targetWithIdentifier: uuid) print("dfuInitiator have start") } //MARK: DFUServiceDelegate public func dfuStateDidChange(to state: DFUState) { switch state { case .completed: pendingResult?(deviceAddress) pendingResult = nil print("\(deviceAddress!) onDfuCompleted") channel.invokeMethod("onDfuCompleted", arguments: deviceAddress) case .disconnecting: print("\(deviceAddress!) onDeviceDisconnecting") channel.invokeMethod("onDeviceDisconnecting", arguments: deviceAddress) case .aborted: pendingResult?(FlutterError(code: "DFU_ABORRED", message: "Device address: \(deviceAddress!)", details: nil)) pendingResult = nil print("\(deviceAddress!) onDfuAborted") channel.invokeMethod("onDfuAborted", arguments: deviceAddress) case .connecting: print("\(deviceAddress!) onDeviceConnecting") channel.invokeMethod("onDeviceConnecting", arguments: deviceAddress) case .starting: print("\(deviceAddress!) onDfuProcessStarting") channel.invokeMethod("onDfuProcessStarting", arguments: deviceAddress) case .enablingDfuMode: print("\(deviceAddress!) onEnablingDfuMode") channel.invokeMethod("onEnablingDfuMode", arguments: deviceAddress) case .validating: print("\(deviceAddress!) onFirmwareValidating") channel.invokeMethod("onFirmwareValidating", arguments: deviceAddress) case .uploading: print("\(deviceAddress!) onFirmwareUploading") channel.invokeMethod("onFirmwareUploading", arguments: deviceAddress) } } public func dfuError(_ error: DFUError, didOccurWithMessage message: String) { print("\(deviceAddress!) onError, message : \(message)") channel.invokeMethod("onError", arguments: deviceAddress) pendingResult?(FlutterError(code: "DFU_FAILED", message: "Device address: \(deviceAddress!)", details: nil)) pendingResult = nil } //MARK: DFUProgressDelegate public func dfuProgressDidChange(for part: Int, outOf totalParts: Int, to progress: Int, currentSpeedBytesPerSecond: Double, avgSpeedBytesPerSecond: Double) { print("onProgressChanged: \(progress)") channel.invokeMethod("onProgressChanged", arguments: [ "percent": progress, "speed": currentSpeedBytesPerSecond, "avgSpeed": avgSpeedBytesPerSecond, "currentPart": part, "partsTotal": totalParts, "deviceAddress": deviceAddress! ]) } //MARK: - LoggerDelegate public func logWith(_ level: LogLevel, message: String) { print("\(level.name()): \(message)") channel.invokeMethod("logs", arguments: "\(level.name()): \(message)") } }
44.674556
169
0.639603
cc8fd4aa41aac963f2004e4695742f4b582a0b83
840
// // MyButton.swift // ResponderTestApp // // Created by Aleksandr Fetisov on 15.10.2021. // import UIKit class MyButton: UIButton { var touchAreaPadding: UIEdgeInsets? override init(frame: CGRect) { super.init(frame: frame) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { guard let insets = touchAreaPadding else { return super.point(inside: point, with: event) } let rect = bounds.inset(by: insets.inverted()) return rect.contains(point) } } extension UIEdgeInsets { func inverted() -> UIEdgeInsets { return UIEdgeInsets(top: -top, left: -left, bottom: -bottom, right: -right) } }
22.105263
83
0.611905
bfc6138ee9d5b96b5b9c35873dd8f2effc71f7a2
5,351
// Copyright 2019-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. // // AWSModelErrorsDelegate.swift // SmokeAWSModelGenerate // import Foundation import ServiceModelCodeGeneration import ServiceModelEntities struct AWSModelErrorsDelegate: ModelErrorsDelegate { let optionSetGeneration: ErrorOptionSetGeneration = .noGeneration let generateEncodableConformance: Bool = false let generateCustomStringConvertibleConformance: Bool = false let canExpectValidationError: Bool = false let awsClientAttributes: AWSClientAttributes let modelOverride: ModelOverride? let baseName: String func addAccessDeniedError(errorTypes: [ErrorType]) -> Bool { for error in errorTypes where error.normalizedName == "accessDenied" { return false } return true } func errorTypeAdditionalImportsGenerator(fileBuilder: FileBuilder, errorTypes: [ErrorType]) { // nothing to do } func errorTypeAdditionalErrorIdentitiesGenerator(fileBuilder: FileBuilder, errorTypes: [ErrorType]) { guard addAccessDeniedError(errorTypes: errorTypes) else { return } fileBuilder.appendLine(""" private let __accessDeniedIdentity = "AccessDenied" """) } func errorTypeWillAddAdditionalCases(fileBuilder: FileBuilder, errorTypes: [ErrorType]) -> Int { var additionCount = 2 if addAccessDeniedError(errorTypes: errorTypes) { additionCount += 1 } return additionCount } func errorTypeAdditionalErrorCasesGenerator(fileBuilder: FileBuilder, errorTypes: [ErrorType]) { if addAccessDeniedError(errorTypes: errorTypes) { fileBuilder.appendLine(""" case accessDenied(message: String?) """) } fileBuilder.appendLine(""" case validationError(reason: String) case unrecognizedError(String, String?) """) } func errorTypeCodingKeysGenerator(fileBuilder: FileBuilder, errorTypes: [ErrorType]) { var typeCodingKey: String var messageCodingKey: String switch awsClientAttributes.contentType.contentTypePayloadType { case .xml: typeCodingKey = "Code" messageCodingKey = "Message" case .json: typeCodingKey = "__type" messageCodingKey = "message" } if let codingKeyOverrides = modelOverride?.codingKeyOverrides { typeCodingKey = codingKeyOverrides["\(baseName)Error.type"] ?? typeCodingKey messageCodingKey = codingKeyOverrides["\(baseName)Error.message"] ?? messageCodingKey } fileBuilder.appendLine(""" enum CodingKeys: String, CodingKey { case type = "\(typeCodingKey)" case message = "\(messageCodingKey)" } """) } func errorTypeIdentityGenerator(fileBuilder: FileBuilder, codingErrorUnknownError: String) -> String { fileBuilder.appendLine(""" let values = try decoder.container(keyedBy: CodingKeys.self) var errorReason = try values.decode(String.self, forKey: .type) let errorMessage = try values.decodeIfPresent(String.self, forKey: .message) if let index = errorReason.firstIndex(of: "#") { errorReason = String(errorReason[errorReason.index(index, offsetBy: 1)...]) } """) return "errorReason" } func errorTypeAdditionalErrorDecodeStatementsGenerator(fileBuilder: FileBuilder, errorTypes: [ErrorType]) { guard addAccessDeniedError(errorTypes: errorTypes) else { return } fileBuilder.appendLine(""" case __accessDeniedIdentity: self = .accessDenied(message: errorMessage) """) } func errorTypeAdditionalErrorEncodeStatementsGenerator(fileBuilder: FileBuilder, errorTypes: [ErrorType]) { // nothing to do } func errorTypeAdditionalDescriptionCases(fileBuilder: FileBuilder, errorTypes: [ErrorType]) { guard addAccessDeniedError(errorTypes: errorTypes) else { return } fileBuilder.appendLine(""" case .accessDenied return __accessDeniedIdentity """) } }
35.673333
105
0.59914
d590eab7fdc0da77635fa44eb1516bd2357f078b
2,849
// OperatorsTest.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // 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 XCTest @testable import Eureka class OperatorsTest: BaseEurekaTests { func testOperators() { // test the operators var form = Form() form +++ TextRow("textrow1_ctx") <<< TextRow("textrow2_ctx") form = form + (TextRow("textrow3_ctx") <<< TextRow("textrow4_ctx") +++ TextRow("textrow5_ctx") <<< TextRow("textrow6_ctx")) + (TextRow("textrow7_ctx") +++ TextRow("textrow8_ctx")) XCTAssertEqual(form.count, 5) XCTAssertEqual(form[0].count, 2) XCTAssertEqual(form[1].count, 2) XCTAssertEqual(form[2].count, 2) form +++ IntRow("introw1_ctx") form +++ IntRow("introw2_ctx") <<< IntRow("introw3_ctx") <<< IntRow("introw4_ctx") // form: // text1 // text2 // ----- // text3 // text4 // ----- // text5 // text6 // ----- // text7 // ----- // text8 // ----- // int1 // ---- // int2 // int3 // int4 XCTAssertEqual(form.count, 7) XCTAssertEqual(form[0].count, 2) XCTAssertEqual(form[1].count, 2) XCTAssertEqual(form[2].count, 2) XCTAssertEqual(form[3].count, 1) XCTAssertEqual(form[4].count, 1) XCTAssertEqual(form[5].count, 1) XCTAssertEqual(form[6].count, 3) } }
33.916667
80
0.570376
0ef94737fa1db1c42298e1f14d7a4cf2e535d2af
13,044
// // AffineTransformTests.swift // SwiftyHaru // // Created by Sergej Jaskiewicz on 25/06/2017. // // import XCTest import SwiftyHaru final class AffineTransformTests: TestCase { static let allTests = [ ("testAffineTransformDescription", testAffineTransformDescription), ("testMakeRotation", testMakeRotation), ("testMakeScale", testMakeScale), ("testMakeTranslation", testMakeTranslation), ("testConcatenate", testConcatenate), ("testInvert", testInvert), ("testConcatenateWithRotation", testConcatenateWithRotation), ("testConcatenateWithScaling", testConcatenateWithScaling), ("testConcatenateWithTranslation", testConcatenateWithTranslation), ("testApplyTransformToSize", testApplyTransformToSize), ("testApplyTransformToPoint", testApplyTransformToPoint) ] func testAffineTransformDescription() { // Given let transform = AffineTransform(a: 200, b: 1, c: 12.333, d: -3, tx: 0, ty: 1223) let expectedRepresentation = """ / 200.0 1.0 0 \\ | 12.333 -3.0 0 | \\ 0.0 1223.0 1 / """ // When let returnedRepresentation = transform.description // Then XCTAssertEqual(expectedRepresentation, returnedRepresentation) } func testMakeRotation() { // Given let expectedTransform1 = AffineTransform(a: -0.903692185, b: -0.428182662, c: 0.428182662, d: -0.903692185, tx: 0, ty: 0) let expectedTransform2 = AffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0) let expectedTransform3 = AffineTransform(a: 1, b: -0.000000301991605, c: 0.000000301991605, d: 1, tx: 0, ty: 0) let expectedTransform4 = AffineTransform(a: 0.50000006, b: -0.866025388, c: 0.866025388, d: 0.50000006, tx: 0, ty: 0) // When let returnedTransform1 = AffineTransform(rotationAngle: 35) let returnedTransform2 = AffineTransform(rotationAngle: 0) let returnedTransform3 = AffineTransform(rotationAngle: 2 * .pi) let returnedTransform4 = AffineTransform(rotationAngle: -.pi / 3) // Then XCTAssertEqual(expectedTransform1, returnedTransform1) XCTAssertEqual(expectedTransform2, returnedTransform2) XCTAssertEqual(expectedTransform3, returnedTransform3) XCTAssertEqual(expectedTransform4, returnedTransform4) XCTAssertEqual(returnedTransform1.determinant, 1, accuracy: 0.0001) XCTAssertEqual(returnedTransform2.determinant, 1, accuracy: 0.0001) XCTAssertEqual(returnedTransform3.determinant, 1, accuracy: 0.0001) XCTAssertEqual(returnedTransform4.determinant, 1, accuracy: 0.0001) } func testMakeScale() { // Given let expectedTransform1 = AffineTransform(a: 2, b: 0, c: 0, d: 3, tx: 0, ty: 0) let expectedTransform2 = AffineTransform(a: 0, b: 0, c: 0, d: 0, tx: 0, ty: 0) let expectedTransform3 = AffineTransform(a: -1, b: 0, c: 0, d: 1, tx: 0, ty: 0) // When let returnedTransform1 = AffineTransform(scaleX: 2, y: 3) let returnedTransform2 = AffineTransform(scaleX: 0, y: 0) let returnedTransform3 = AffineTransform(scaleX: -1, y: 1) let returnedTransform4 = AffineTransform(scaleX: 1, y: 1) // Then XCTAssertEqual(expectedTransform1, returnedTransform1) XCTAssertEqual(expectedTransform2, returnedTransform2) XCTAssertEqual(expectedTransform3, returnedTransform3) XCTAssertTrue(returnedTransform4.isIdentity) XCTAssertEqual(returnedTransform1.determinant, 6, accuracy: 0.0001) XCTAssertEqual(returnedTransform2.determinant, 0, accuracy: 0.0001) XCTAssertEqual(returnedTransform3.determinant, -1, accuracy: 0.0001) XCTAssertEqual(returnedTransform4.determinant, 1, accuracy: 0.0001) } func testMakeTranslation() { // Given let expectedTransform1 = AffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 12, ty: 43) let expectedTransform2 = SwiftyHaru.AffineTransform.identity let expectedTransform3 = AffineTransform(a: 1, b: 0, c: 0, d: 1, tx: -4, ty: 15) // When let returnedTransform1 = AffineTransform(translationX: 12, y: 43) let returnedTransform2 = AffineTransform(translationX: 0, y: 0) let returnedTransform3 = AffineTransform(translationX: -4, y: 15) // Then XCTAssertEqual(expectedTransform1, returnedTransform1) XCTAssertEqual(expectedTransform2, returnedTransform2) XCTAssertEqual(expectedTransform3, returnedTransform3) } func testConcatenate() { // Given let transform11 = AffineTransform(a: 1, b: 5, c: 4, d: 6, tx: 12, ty: 43) let transform12 = AffineTransform(a: 76, b: 4, c: 8, d: 51, tx: 0, ty: 2) let expectedTransform1 = AffineTransform(a: 116, b: 259, c: 352, d: 322, tx: 1256, ty: 2243) let expectedTransform2 = AffineTransform(a: 4, b: 5, c: 9, d: 11, tx: 44, ty: 2) // When let returnedTransform1 = transform11 * transform12 let returnedTransform2 = expectedTransform2 * .identity // Then XCTAssertEqual(expectedTransform1, returnedTransform1) XCTAssertEqual(expectedTransform2, returnedTransform2) } func testInvert() { // Given let transform1 = AffineTransform(a: 1, b: 5, c: 4, d: 6, tx: 12, ty: 43) let expectedTransform1 = AffineTransform(a: -0.428571428571429, b: 0.357142857142857, c: 0.285714285714286, d: -0.0714285714285714, tx: -7.14285714285714, ty: -1.21428571428571) let expectedTransform2 = AffineTransform(a: 3, b: 0, c: 4.99999952, d: 2, tx: 9.99999904, ty: 1) let expectedInvertedDegenerateTransform = AffineTransform(a: 1, b: 5, c: 1, d: 5, tx: 12, ty: 43) // When let returnedTransform1 = transform1.inverted() let returnedTransform2 = expectedTransform2.inverted().inverted() let returnedInvertedDegenerateTransform = expectedInvertedDegenerateTransform.inverted() // Then XCTAssertEqual(expectedTransform1, returnedTransform1) XCTAssertEqual(expectedTransform2, returnedTransform2) XCTAssertEqual(expectedInvertedDegenerateTransform, returnedInvertedDegenerateTransform) } func testConcatenateWithRotation() { // Given let transform1 = AffineTransform(a: 1, b: 5, c: 4, d: 6, tx: 12, ty: 43) let expectedTransform1 = AffineTransform(a: -2.61642289, b: -7.08755684, c: -3.18658614, d: -3.28123975, tx: 12, ty: 43) let transform2 = AffineTransform(a: 1, b: 0, c: 3, d: 2, tx: 12, ty: 43) let expectedTransform2 = AffineTransform(a: -0.999999523, b: 0.000000301991605, c: -3.00000024, d: -2, tx: 12, ty: 43) // When let returnedTransform1 = transform1.rotated(byAngle: 35) let returnedTransform2 = transform2.rotated(byAngle: .pi) // Then XCTAssertEqual(expectedTransform1, returnedTransform1) XCTAssertEqual(expectedTransform2, returnedTransform2) } func testConcatenateWithScaling() { // Given let transform1 = AffineTransform(a: 1, b: 5, c: 4, d: 6, tx: 12, ty: 43) let expectedTransform1 = AffineTransform(a: 2.6, b: 13.0, c: 1.6, d: 2.4, tx: 12, ty: 43) let transform2 = AffineTransform(a: 1, b: 0, c: 3, d: 2, tx: 12, ty: 43) let expectedTransform2 = AffineTransform(a: -1, b: 0, c: 3, d: 2, tx: 12, ty: 43) // When let returnedTransform1 = transform1.scaled(byX: 2.6, y: 0.4) let returnedTransform2 = transform2.scaled(byX: -1, y: 1) // Then XCTAssertEqual(expectedTransform1, returnedTransform1) XCTAssertEqual(expectedTransform2, returnedTransform2) } func testConcatenateWithTranslation() { // Given let transform1 = AffineTransform(a: 1, b: 5, c: 4, d: 6, tx: 12, ty: 43) let expectedTransform1 = AffineTransform(a: 1, b: 5, c: 4, d: 6, tx: 6, ty: 69) let transform2 = AffineTransform(a: 1, b: 0, c: 3, d: 2, tx: 12, ty: 43) let expectedTransform2 = AffineTransform(a: 1, b: 0, c: 3, d: 2, tx: 114, ty: 111) // When let returnedTransform1 = transform1.translated(byX: 10, y: -4) let returnedTransform2 = transform2.translated(byX: 0, y: 34) // Then XCTAssertEqual(expectedTransform1, returnedTransform1) XCTAssertEqual(expectedTransform2, returnedTransform2) } func testApplyTransformToSize() { // Given let size = Size(width: 44, height: 12) let transform = AffineTransform(a: 1, b: 5, c: 4, d: 6, tx: 12, ty: 43) let expectedSize = Size(width: 92, height: 292) // When let returnedSize = size.applying(transform) // Then XCTAssertEqual(expectedSize, returnedSize) } func testApplyTransformToPoint() { // Given let point = Point(x: 44, y: 12) let transform = AffineTransform(a: 1, b: 5, c: 4, d: 6, tx: 12, ty: 43) let expectedPoint = Point(x: 104, y: 335) // When let returnedPoint = point.applying(transform) // Then XCTAssertEqual(expectedPoint, returnedPoint) } }
40.890282
97
0.462665
8fbe8589409730821670d10440054038c906f0af
3,754
// // ViewController.swift // ReCaptcha // // Created by Flávio Caetano on 03/22/17. // Copyright © 2018 ReCaptcha. All rights reserved. // import ReCaptcha import RxCocoa import RxSwift import UIKit class ViewController: UIViewController { private struct Constants { static let webViewTag = 123 static let testLabelTag = 321 } private var recaptcha: ReCaptcha! private var disposeBag = DisposeBag() private var locale: Locale? private var endpoint = ReCaptcha.Endpoint.default @IBOutlet private weak var label: UILabel! @IBOutlet private weak var spinner: UIActivityIndicatorView! @IBOutlet private weak var localeSegmentedControl: UISegmentedControl! @IBOutlet private weak var endpointSegmentedControl: UISegmentedControl! @IBOutlet private weak var visibleChallengeSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() setupReCaptcha() } @IBAction func didPressEndpointSegmentedControl(_ sender: UISegmentedControl) { label.text = "" switch sender.selectedSegmentIndex { case 0: endpoint = .default case 1: endpoint = .alternate default: assertionFailure("invalid index") } setupReCaptcha() } @IBAction func didPressLocaleSegmentedControl(_ sender: UISegmentedControl) { label.text = "" switch sender.selectedSegmentIndex { case 0: locale = nil case 1: locale = Locale(identifier: "zh-CN") default: assertionFailure("invalid index") } setupReCaptcha() } @IBAction private func didPressButton(button: UIButton) { disposeBag = DisposeBag() let validate = recaptcha.rx.validate(on: view) .debug("validate") .share() let isLoading = validate .map { _ in false } .startWith(true) .share(replay: 1) isLoading .bind(to: spinner.rx.isAnimating) .disposed(by: disposeBag) let isEnabled = isLoading .map { !$0 } .catchErrorJustReturn(false) .share(replay: 1) isEnabled .bind(to: button.rx.isEnabled) .disposed(by: disposeBag) isEnabled .bind(to: endpointSegmentedControl.rx.isEnabled) .disposed(by: disposeBag) validate .map { [weak self] _ in self?.view.viewWithTag(Constants.webViewTag) } .subscribe(onNext: { subview in subview?.removeFromSuperview() }) .disposed(by: disposeBag) validate .bind(to: label.rx.text) .disposed(by: disposeBag) visibleChallengeSwitch.rx.value .subscribe(onNext: { [weak recaptcha] value in recaptcha?.forceVisibleChallenge = value }) .disposed(by: disposeBag) } private func setupReCaptcha() { // swiftlint:disable:next force_try recaptcha = try! ReCaptcha(endpoint: endpoint, locale: locale) recaptcha.configureWebView { [weak self] webview in webview.frame = self?.view.bounds ?? CGRect.zero webview.tag = Constants.webViewTag // For testing purposes // If the webview requires presentation, this should work as a way of detecting the webview in UI tests self?.view.viewWithTag(Constants.testLabelTag)?.removeFromSuperview() let label = UILabel(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) label.tag = Constants.testLabelTag label.accessibilityLabel = "webview" self?.view.addSubview(label) } } }
29.559055
115
0.612147
2091ece6b1a3d0344da286435272a2126000ebd8
3,637
import UIKit import ARKit public enum MessageFromContentsToLiveView: PlaygroundMessage { // List of case case startTimeTravel case createSun(radius: CGFloat, position: SCNVector3) case setSpeedRotationToSun(speedRotation: Int) case setTextureToSun case createParentEarth case createEarth case createSolarSystem // Create a Enumeration public enum MessageType: String, PlaygroundMessageType { case startTimeTravel case createSun case setSpeedRotationToSun case setTextureToSun case createParentEarth case createEarth case createSolarSystem } // Define the type of message that I can have public var messageType: MessageType { switch self { case .startTimeTravel: return .startTimeTravel case .createSun(radius:position:): return .createSun case .setTextureToSun: return .setTextureToSun case .setSpeedRotationToSun(speedRotation:): return .setSpeedRotationToSun case .createParentEarth: return .createParentEarth case .createEarth: return .createEarth case .createSolarSystem: return .createSolarSystem } } // MARK: - Init public init?(messageType: MessageType, parametersEncoded: Data?) { let decoder = JSONDecoder() // If there are parameters, I'll get them switch messageType { case .startTimeTravel: self = .startTimeTravel case .createSun: guard let parametersEncoded = parametersEncoded, let parameters = try? decoder.decode(createSunParameters.self, from: parametersEncoded) else { return nil } self = .createSun(radius: parameters.radius, position: parameters.position); case .setTextureToSun: self = .setTextureToSun case .setSpeedRotationToSun: guard let parametersEncoded = parametersEncoded, let parameters = try? decoder.decode(setSpeedRotationParameters.self, from: parametersEncoded) else { return nil } self = .setSpeedRotationToSun(speedRotation: parameters.speedRotation) case .createParentEarth: self = .createParentEarth case .createEarth: self = .createEarth case .createSolarSystem: self = .createSolarSystem } } // MARK: - Functions // Decode the parameters public func encodeParameters() -> Data? { let encoder = JSONEncoder() switch self { case .startTimeTravel: return nil case let .createSun(radius: radius, position: position): let parameters = createSunParameters(radius: radius, position: position) return try! encoder.encode(parameters) case .setTextureToSun: return nil; case let .setSpeedRotationToSun(speedRotation: speedRotation): let parameters = setSpeedRotationParameters(speedRotation: speedRotation) return try! encoder.encode(parameters) case .createParentEarth: return nil case .createEarth: return nil case .createSolarSystem: return nil } } }
29.569106
112
0.580423
89620efaf3eddc7d28becb7b4600e941bc51bf08
3,052
import UIKit class LiveAuctionPlainLotCollectionViewLayout: UICollectionViewFlowLayout, LiveAuctionLotCollectionViewLayoutType { unowned let delegate: LiveAuctionLotCollectionViewDelegateLayout init(delegate: LiveAuctionLotCollectionViewDelegateLayout) { self.delegate = delegate super.init() scrollDirection = .horizontal minimumLineSpacing = 0 } required init?(coder aDecoder: NSCoder) { return nil } var repulsionConstant: CGFloat = 0 { didSet { invalidateLayout() } } fileprivate var maxHeight: CGFloat { guard let height = collectionView?.bounds.height else { return 0 } return height - 40 } class override var layoutAttributesClass : AnyClass { return LiveAuctionLotCollectionViewLayoutAttributes.self } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { // Regardless of the rect, we always return the one layout attributes return [layoutAttributesForItem(at: IndexPath(item: 1, section: 0))].compactMap { $0 } } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return super.layoutAttributesForItem(at: indexPath).flatMap { modifiedLayoutAttributesCopy($0) } } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override func prepare() { super.prepare() let width = collectionView?.frame.size.width ?? 0 itemSize = CGSize(width: width, height: maxHeight) } func modifiedLayoutAttributesCopy(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { guard let copy = layoutAttributes.copy() as? LiveAuctionLotCollectionViewLayoutAttributes else { return layoutAttributes } copy.size.width -= 80 // For side margins, done upfront so we can rely on copy.size for the remainder of the function. let index: RelativeIndex = (copy.indexPath as IndexPath).item let aspectRatio = delegate.aspectRatioForIndex(index) let isWide = (aspectRatio > itemSize.width / maxHeight) // copy has size = itemSize by default, we just need to set the appropriate dimension, based on aspect ratio. // This is a simplified version of the fancy layout math. if isWide { copy.size.height = itemSize.width / aspectRatio - repulsionConstant / aspectRatio } else { copy.size.width = itemSize.height * aspectRatio - repulsionConstant * aspectRatio } // Center the item vertically, minus repulsion copy.center.y = (collectionView?.frame.midY ?? 0) - (repulsionConstant / 2) // Center horizontally according to current contentSize (which is the bounds size in all scroll views) copy.center.x = collectionView?.bounds.midX ?? 0 copy.url = delegate.thumbnailURLForIndex(index) return copy } }
36.333333
130
0.694626
08769ef5cc6b67459084461b72c0ef9a3b91ebb2
888
import Foundation class MFightFacingNegative:MFightFacing { override func initialPosition() -> MFightPosition { let position:MFightPosition = MFightPosition( positionX:kInitialX, positionY:kInitialY) return position } override func direction() -> MetalSpatialBaseTexturedDirection { let direction:MetalSpatialBaseTexturedDirectionNegative = MetalSpatialBaseTexturedDirectionNegative() return direction } override func normalizeDistance(distance:Float) -> Float { return -distance } override func normalizeReach(position:Float) -> Float { return position - kReachDelta } override func overlaps(outsider:Float, me:Float) -> Bool { let isOverlaping:Bool = outsider >= me return isOverlaping } }
23.368421
109
0.638514
09683b2544c6cbd97127923c97458ca354c97540
2,427
// swift-tools-version:5.3 // THIS FILE IS GENERATED. DO NOT EDIT. import PackageDescription let package = Package( name: "BeyondIdentitySDKs", defaultLocalization: "en", platforms: [.iOS(.v12), .macOS(.v10_15)], products: [ .library( name: "BeyondIdentityAuthenticator", targets: ["BeyondIdentityAuthenticator"]), .library( name: "BeyondIdentityEmbedded", targets: ["BeyondIdentityEmbedded"]), .library( name: "BeyondIdentityEmbeddedUI", targets: ["BeyondIdentityEmbeddedUI"]) ], dependencies: [ .package(url: "https://github.com/Rightpoint/Anchorage.git", from: "4.5.0"), ], targets: [ .target( name: "BeyondIdentityAuthenticator", dependencies: ["CoreSDK", "DeviceInfoSDK", "EnclaveSDK", "SharedDesign"], path: "Sources/Authenticator/" ), .target( name: "BeyondIdentityEmbedded", dependencies: ["CoreSDK", "DeviceInfoSDK", "EnclaveSDK"], path: "Sources/Embedded/" ), .target( name: "BeyondIdentityEmbeddedUI", dependencies: ["Anchorage", "BeyondIdentityEmbedded", "SharedDesign"], path: "Sources/EmbeddedUI/" ), .target( name: "SharedDesign", path: "Sources/SharedDesign/", resources: [.process("Resources/Fonts")] ), .binaryTarget( name: "CoreSDK", url: "https://packages.beyondidentity.com/public/bi-sdk-swift/raw/versions/0.5.0/CoreSDK.xcframework.zip", checksum: "ad4d1a680b309d5fd693a93a5b64d9e890899e79d27818b6382642c59074c7ac" ), .binaryTarget( name: "DeviceInfoSDK", url: "https://packages.beyondidentity.com/public/bi-sdk-swift/raw/versions/0.5.0/DeviceInfoSDK.xcframework.zip", checksum: "dbb7e4925c72a5d47278c190a1fef0c9efefbd2cd18dadb68294e0d34936d36c" ), .binaryTarget( name: "EnclaveSDK", url: "https://packages.beyondidentity.com/public/bi-sdk-swift/raw/versions/0.5.0/EnclaveSDK.xcframework.zip", checksum: "f56436b087004cf6790a80b047f98fa5694a64e77fa75a7a02cdc8bdad91827c" ), .testTarget( name: "UnitTests", dependencies: ["BeyondIdentityAuthenticator", "BeyondIdentityEmbedded", "SharedDesign"], path: "Tests/UnitTests", exclude: [] ) ] )
35.691176
117
0.620519
d943411b41ff413deb29a201dc0f329a96e6afd1
2,406
//------------------------------------------------------------------------------ // Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: enums.fbe // FBE version: 1.10.0.0 //------------------------------------------------------------------------------ import Foundation public enum EnumInt8Enum { typealias RawValue = Int8 case ENUM_VALUE_0 case ENUM_VALUE_1 case ENUM_VALUE_2 case ENUM_VALUE_3 case ENUM_VALUE_4 case ENUM_VALUE_5 var rawValue: RawValue { switch self { case .ENUM_VALUE_0: return 0 + 0 case .ENUM_VALUE_1: return -128 + 0 case .ENUM_VALUE_2: return -128 + 1 case .ENUM_VALUE_3: return 126 + 0 case .ENUM_VALUE_4: return 126 + 1 case .ENUM_VALUE_5: return Self.ENUM_VALUE_3.rawValue } } init(value: Int8) { self = EnumInt8Enum(rawValue: NSNumber(value: value).int8Value) } init(value: Int16) { self = EnumInt8Enum(rawValue: NSNumber(value: value).int8Value) } init(value: Int32) { self = EnumInt8Enum(rawValue: NSNumber(value: value).int8Value) } init(value: Int64) { self = EnumInt8Enum(rawValue: NSNumber(value: value).int8Value) } init(value: EnumInt8Enum) { self = EnumInt8Enum(rawValue: value.rawValue) } init(rawValue: Int8) { self = Self.mapValue(value: rawValue)! } var description: String { switch self { case .ENUM_VALUE_0: return "ENUM_VALUE_0" case .ENUM_VALUE_1: return "ENUM_VALUE_1" case .ENUM_VALUE_2: return "ENUM_VALUE_2" case .ENUM_VALUE_3: return "ENUM_VALUE_3" case .ENUM_VALUE_4: return "ENUM_VALUE_4" case .ENUM_VALUE_5: return "ENUM_VALUE_5" } } static let rawValuesMap: [RawValue: EnumInt8Enum] = { var value = [RawValue: EnumInt8Enum]() value[EnumInt8Enum.ENUM_VALUE_0.rawValue] = .ENUM_VALUE_0 value[EnumInt8Enum.ENUM_VALUE_1.rawValue] = .ENUM_VALUE_1 value[EnumInt8Enum.ENUM_VALUE_2.rawValue] = .ENUM_VALUE_2 value[EnumInt8Enum.ENUM_VALUE_3.rawValue] = .ENUM_VALUE_3 value[EnumInt8Enum.ENUM_VALUE_4.rawValue] = .ENUM_VALUE_4 value[EnumInt8Enum.ENUM_VALUE_5.rawValue] = .ENUM_VALUE_5 return value }() static func mapValue(value: Int8) -> EnumInt8Enum? { return rawValuesMap[value] } }
38.190476
90
0.633416
6a544020ae2c5e1d482d956f32b0cadead0bd1b2
4,047
// Copyright (c) 2021 Spotify AB. // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. @testable import XCMetricsBackendLib import XCTVapor import Fluent final class StatisticsControllerTests: XCTestCase { func testBuildCounts() throws { let app = Application(.testing) try configure(app) try app.register(collection: StatisticsController(repository: FakeStatisticsRepository())) defer { app.shutdown() } let firstDay = Date().xcm_truncateTime().xcm_ago(days: 13)! // Since today is supposed to be included let lastDay = Date().xcm_truncateTime() try app.test(.GET, "v1/statistics/build/count?days=14", afterResponse: { res in XCTAssertEqual(res.status, .ok) let dayCounts = try res.content.decode([DayCount].self) XCTAssertEqual(dayCounts.count, 14) XCTAssertEqual(dayCounts.first!.id, firstDay) XCTAssertEqual(dayCounts.last!.id, lastDay) }) // Missing parameter try app.test(.GET, "v1/statistics/build/count", afterResponse: { res in XCTAssertEqual(res.status, .badRequest) }) // Invalid parameter try app.test(.GET, "v1/statistics/build/count?days=0", afterResponse: { res in XCTAssertEqual(res.status, .badRequest) }) } func testBuildTimes() throws { let app = Application(.testing) try configure(app) try app.register(collection: StatisticsController(repository: FakeStatisticsRepository())) defer { app.shutdown() } let firstDay = Date().xcm_truncateTime().xcm_ago(days: 13)! // Since today is supposed to be included let lastDay = Date().xcm_truncateTime() try app.test(.GET, "v1/statistics/build/time?days=14", afterResponse: { res in XCTAssertEqual(res.status, .ok) let dayCounts = try res.content.decode([DayBuildTime].self) XCTAssertEqual(dayCounts.count, 14) XCTAssertEqual(dayCounts.first!.id, firstDay) XCTAssertEqual(dayCounts.last!.id, lastDay) }) // Missing parameter try app.test(.GET, "v1/statistics/build/time", afterResponse: { res in XCTAssertEqual(res.status, .badRequest) }) // Invalid parameter try app.test(.GET, "v1/statistics/build/time?days=0", afterResponse: { res in XCTAssertEqual(res.status, .badRequest) }) } func testBuildStatus() throws { let app = Application(.testing) try configure(app) try app.register(collection: StatisticsController(repository: FakeStatisticsRepository())) defer { app.shutdown() } try app.test(.GET, "v1/statistics/build/status", afterResponse: { res in XCTAssertEqual(res.status, .ok) XCTAssertNoThrow(try res.content.decode(Page<BuildStatusResult>.self)) }) // Pagination parameters try app.test(.GET, "v1/statistics/build/status?page=1&per=1", afterResponse: { res in XCTAssertEqual(res.status, .ok) }) // Invalid parameter try app.test(.GET, "v1/statistics/build/status?page=invalid", afterResponse: { res in XCTAssertEqual(res.status, .badRequest) }) } }
38.913462
109
0.657524
fb455803336f407b40ea23de4c52099977163310
1,289
// Copyright © 2021 SpotHero, Inc. All rights reserved. import Foundation import UtilityBeltNetworking public extension StubbedDataCollection { /// Returns a stubbed response if there is a stubbed request that matches. /// - Parameter urlRequest: The URL, URLRequest, or URL String to match against stubbed requests. func getResponse(for urlRequest: URLRequestConvertible) -> StubResponse? { let request = StubRequest(urlRequest: urlRequest) return self.getResponse(for: request) } /// Determines whether or not a matching request has been stubbed. /// - Parameter urlRequest: The URL, URLRequest, or URL String to match against stubbed requests. func hasStub(for urlRequest: URLRequestConvertible) -> Bool { let request = StubRequest(urlRequest: urlRequest) return self.hasStub(for: request) } /// Adds a response to the stub response collection. /// - Parameter urlRequest: The URL, URLRequest, or URL String to stub. /// - Parameter response: The response to return upon receiving the given request. func stub(_ urlRequest: URLRequestConvertible, with response: StubResponse) { let request = StubRequest(urlRequest: urlRequest) return self.stub(request, with: response) } }
44.448276
101
0.716835
f421341cdcd79e35557bc0e155d869ecff14a9d2
5,264
// // UBIBadgeView.swift // // Created by Yuki Yasoshima on 2017/05/24. // Copyright © 2017 Ubiregi inc. All rights reserved. // import UIKit @objc(UBIBadgeView) @IBDesignable open class UBIBadgeView: UIView { private let frameView: UIView = UIView() private let label = UBIBadgeViewLabel() public enum Alignment { case center case left case right } override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.addSubview(self.frameView) self.addSubview(self.label) self.label.textAlignment = .center self.label.font = self.font self.label.textColor = self.textColor self.label.layoutBlock = { [weak self] in self?.updateLayout() } self.updateText() self.frameView.layer.backgroundColor = self.frameBackgroundColor.cgColor self.frameView.layer.borderColor = self.frameBorderColor.cgColor self.frameView.layer.cornerRadius = self.cornerRadius self.frameView.layer.borderWidth = self.borderWidth } public var font: UIFont = UIFont(name: "Helvetica-Bold", size: 15.0)! { didSet { self.label.font = font self.label.sizeToFit() } } @IBInspectable public var textColor: UIColor = .white { didSet { self.label.textColor = textColor } } @IBInspectable public var value: Int = 0 { didSet { self.updateText() } } @IBInspectable public var frameBackgroundColor: UIColor = .orange { didSet { self.frameView.layer.backgroundColor = frameBackgroundColor.cgColor } } @IBInspectable public var frameBorderColor: UIColor = .white { didSet { self.frameView.layer.borderColor = frameBorderColor.cgColor } } @IBInspectable public var cornerRadius: CGFloat = 10.5 { didSet { self.frameView.layer.cornerRadius = cornerRadius } } @IBInspectable public var borderWidth: CGFloat = 1.0 { didSet { self.frameView.layer.borderWidth = borderWidth } } @IBInspectable public var minWidth: CGFloat = 23 { didSet { self.updateLayout() } } @IBInspectable public var isHiddenIfZero: Bool = false { didSet { self.updateHiddenSubviews() } } @IBInspectable public var paddingWidth: CGFloat = 14.0 { didSet { self.updateLayout() } } @IBInspectable public var paddingHeight: CGFloat = 4.0 { didSet { self.updateLayout() } } public var alignment: Alignment = .center { didSet { self.updateLayout(); } } private func updateText() { if self.value >= 1000 { self.label.text = "999+" } else { self.label.text = String(self.value) } self.label.sizeToFit() self.updateHiddenSubviews() } private func updateLayout() { let labelSize = self.label.frame.size; let frameSize = CGSize(width: max(labelSize.width + self.paddingWidth, self.minWidth), height: labelSize.height + self.paddingHeight) self.frameView.frame.size = frameSize let center = self.convert(self.center, from: self.superview) switch self.alignment { case .center: self.frameView.center = center self.label.center = center case .left: let position = CGPoint(x: center.x + frameSize.width * 0.5, y: center.y) self.frameView.center = position self.label.center = position case .right: let position = CGPoint(x: center.x - frameSize.width * 0.5, y: center.y) self.frameView.center = position self.label.center = position } self.frameView.frame = self.roundFrame(self.frameView.frame) self.label.frame = self.roundFrame(self.label.frame) } private func updateHiddenSubviews() { if self.isHiddenIfZero && self.value == 0 { self.frameView.isHidden = true self.label.isHidden = true } else { self.frameView.isHidden = false self.label.isHidden = false } } private func roundFrame(_ rect: CGRect) -> CGRect { return CGRect(x: self.roundPosition(rect.origin.x), y: self.roundPosition(rect.origin.y), width: rect.size.width, height: rect.size.height) } private func roundPosition(_ pos: CGFloat) -> CGFloat { let scale = UIScreen.main.scale return round(pos * scale) / scale } } class UBIBadgeViewLabel: UILabel { var layoutBlock: (() -> Void)? override func layoutSubviews() { super.layoutSubviews() if let block = self.layoutBlock { block() } } }
27.560209
147
0.575038
4b156f32e8fd5b263be981020cac29398a193a6b
1,398
// // EtherchainGasPrice.swift // eNotes // // Created by Smiacter on 2018/8/14. // Copyright © 2018 eNotes. All rights reserved. // // 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. // public struct EtherchainGasPrice: Decodable { public var safeLow: String public var standard: String public var fast: String public var fastest: String }
42.363636
81
0.745351
56729859518b690e705571a08cf343a1c860cec5
169
import Foundation public struct SGFeedParser { public private(set) var parser: FeedParser public init(url: URL) { parser = FeedParser(url: url) } }
18.777778
46
0.668639
110ab2e44f84bdd3767195d3576f333dde7305b5
1,042
// Copyright © 2021 Lunabee Studio // // 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. // // DemoText.swift // LBBottomSheet-Demo // // Created by Lunabee Studio / Date - 26/10/2021 - for the LBBottomSheet-Demo Swift Package. // import Foundation import LBBottomSheet struct DemoTestCase { let title: String let menuTitle: String let explanations: String var codeUrl: URL? var theme: () -> BottomSheetController.Theme = { .init() } var behavior: () -> BottomSheetController.Behavior = { .init() } }
32.5625
93
0.712092
e294343b6715e3d27a1eb48a026ec7dd4e0c078d
3,458
// // FlexView.swift // memo // // Created by stevecai on 2021/11/20. // import SwiftUI struct FlexView<Data: Collection, Content: View>: View where Data.Element: Hashable { let data: Data let spacing: CGFloat let alignment: HorizontalAlignment @Binding var isExpand: Bool let useScrollView: Bool = true let content: (Data.Element) -> Content @State private var availableWidth: CGFloat = 0 @State private var itemHeight: CGFloat = 0 @State private var maxLines: CGFloat = 1 private var maxViewHeight: CGFloat { get { return itemHeight * maxLines + spacing * (maxLines - 1) } } @State var elementsSize: [Data.Element: CGSize] = [:] func allSizeComputed() -> Bool { var computed = true data.forEach { elem in if (!elementsSize.contains{ $0.key == elem}) { computed = false return } } return computed } var body: some View { ZStack(alignment: Alignment(horizontal: alignment, vertical: .center)) { Color.white .frame(height: 1) .readSize { size in availableWidth = size.width } if (isExpand && useScrollView) { ScrollView(showsIndicators: false) { _body }.frame(maxHeight: maxViewHeight) } else { _body } } } var _body: some View { Group { // 有未确定大小的 view 的情况下,先读一遍 view 的大小,下面再进行真正的构造 if (!allSizeComputed()) { VStack { ForEach(Array(data), id: \.self) { elem in content(elem) .fixedSize() .readSize { size in elementsSize[elem] = size if (itemHeight == 0) { itemHeight = size.height } } } } } else { VStack(alignment: alignment, spacing: spacing) { ForEach(computeRows(), id: \.self) { rowElements in HStack(spacing: spacing) { ForEach(rowElements, id: \.self) { element in content(element) } } } } } } } func computeRows() -> [[Data.Element]] { var rows: [[Data.Element]] = [[]] var currentRow = 0 var remainingWidth = availableWidth for element in data { let elementSize = elementsSize[element, default: CGSize(width: 1, height: 1)] if remainingWidth - elementSize.width >= 0 { rows[currentRow].append(element) } else { currentRow = currentRow + 1 rows.append([element]) remainingWidth = availableWidth } remainingWidth = remainingWidth - (elementSize.width + spacing) } if (!isExpand) { return [rows[0]] } DispatchQueue.main.async { maxLines = currentRow < 3 ? CGFloat(currentRow + 1) : 3 } return rows } }
30.60177
89
0.459225
4aa9dcc441291eca98d7197bebd76e5f6b068c89
380
// // CardInfoDescriptionTableViewCell.swift // CardsMobile-Contest // // Created by Ванурин Алексей Максимович on 02.12.2020. // import UIKit final class CardInfoDescriptionTableViewCell: UITableViewCell { @IBOutlet weak var descriptionLabel: UILabel! func setUp(_ model: CardInfoDescription) { descriptionLabel.text = model.text } }
19
63
0.702632
feb25ead0f8a55d0c16c821c2643022eb19d723c
1,261
// // PKHUDProgressVIew.swift // PKHUD // // Created by Philip Kluz on 6/12/15. // Copyright (c) 2016 NSExceptional. All rights reserved. // Licensed under the MIT license. // import UIKit import QuartzCore /// PKHUDProgressView provides an indeterminate progress view. open class PKHUDProgressView: PKHUDSquareBaseView, PKHUDAnimating { public init(title: String? = nil, subtitle: String? = nil) { super.init(image: PKHUDAssets.progressActivityImage, title: title, subtitle: subtitle) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public func startAnimation() { imageView.layer.add(PKHUDAnimation.discreteRotation, forKey: "progressAnimation") } public func stopAnimation() { } public func changeTitleLabelTextColor(textColor: UIColor) { self.titleLabel.textColor = textColor } public func changeTitleLabelTextFont(textFont: UIFont) { self.titleLabel.font = textFont } public func changeSubTitleLabelTextColor(textColor: UIColor) { self.subtitleLabel.textColor = textColor } public func changeSubTitleLabelTextFont(textFont: UIFont) { self.subtitleLabel.font = textFont } }
26.829787
94
0.69548
e553a7ead945fc1ec7c35abf5ce138b521576a15
9,256
// // BlueViewController.swift // TwitterThor // // Created by Paul Thormahlen on 2/25/16. // Copyright © 2016 Paul Thormahlen. All rights reserved. // import UIKit import AFNetworking class ProfileViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate{ @IBOutlet weak var tableView: UITableView! var user: User? var showMentions: Bool = false override func viewDidLoad() { super.viewDidLoad() print("self.navigationItem.title = \(self.navigationItem.title)") if let navVC = navigationController as? ProfileNavigationViewController{ showMentions = navVC.showMentions print("ProfileViews Navigation controller mentions flag is \(navVC.showMentions)") if let _user = navVC.user{ print("Got user from NavVC") self.user = _user } } if(self.user == nil){ print("set user to current user") self.user = User.currentUser } if showMentions{ self.title = "mentions @\(user!.screenname!)" }else{ self.title = user!.screenname } configTableView() setupRefreshControl() getUsersStatus() setHeaderImage() } @IBOutlet weak var blurEffectView: UIVisualEffectView! @IBOutlet weak var bannerBackgroundImageView: UIImageView! var tweets: [Tweet] = [Tweet]() var bannerImageView: UIImageView = UIImageView() var profileCell:ProfileDetailsTableViewCell! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func configTableView(){ tableView.backgroundColor = UIColor.clearColor() tableView.dataSource = self tableView.delegate = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 180 } func setHeaderImage(){ if (user!.profile_banner_url != nil){ let avatarImage = NSURL(string: user!.profile_banner_url!) if avatarImage != nil{ print("set header image") bannerBackgroundImageView.setImageWithURL(avatarImage!) } } } func customizeNavbar(){ if let navigationBar = self.navigationController?.navigationBar{ navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) navigationBar.shadowImage = UIImage() navigationBar.translucent = true } } func getUsersStatus(){ let successBlock: ([Tweet]?, NSError?) ->() = {(tweets, error) ->() in if let newTweets = tweets{ self.tweets = newTweets self.tableView.reloadData() self.refreshControl?.endRefreshing() }else{ print("error: \(error?.description)") } } if(showMentions){ print("Display mentions on profile") user!.mentions(successBlock) }else{ print("display \(self.user?.screenname)'s tweets") user!.statuses(successBlock, forUser: self.user!) } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if(indexPath.row == 0 ){ let cell = tableView.dequeueReusableCellWithIdentifier("ProfileHeaderTableViewCell", forIndexPath: indexPath) as! ProfileHeaderTableViewCell cell.contentView.backgroundColor = UIColor.clearColor() cell.backgroundView?.backgroundColor = UIColor.clearColor() return cell }else if(indexPath.row == 1){ let cell = tableView.dequeueReusableCellWithIdentifier("ProfileDetailsTableViewCell", forIndexPath: indexPath) as! ProfileDetailsTableViewCell profileCell = cell cell.user = self.user return cell } else{ let cell = tableView.dequeueReusableCellWithIdentifier("BasicTweetTableViewCell", forIndexPath: indexPath) as UITableViewCell as! BasicTweetTableViewCell //TODO this would be better managed by having table sections cell.tweet = tweets[indexPath.row - 1] cell.navigationController = self.navigationController return cell } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets.count + 1 } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if(indexPath.row == 0){ cell.backgroundColor = UIColor.clearColor() } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func refreshControlAction(refreshControl: UIRefreshControl) { getUsersStatus() refreshControl.endRefreshing() } /****** * REFESH CONTROLE SECTION WITH ANIMATED BACKGROUND IMAGE * **/ var refreshControl: UIRefreshControl! var refreshLoadingView : UIView! var refreshColorView : UIView! var compass_background : UIImageView! var compass_spinner : UIImageView! var isRefreshIconsOverlap = false var isRefreshAnimating = false func setupRefreshControl() { // Programmatically inserting a UIRefreshControl self.refreshControl = UIRefreshControl() // Setup the loading view, which will hold the moving graphics refreshLoadingView = UIView(frame: self.refreshControl!.bounds) refreshLoadingView.backgroundColor = UIColor.clearColor() // Setup the color view, which will display the rainbowed background self.refreshColorView = UIView(frame: self.refreshControl!.bounds) self.refreshColorView.backgroundColor = UIColor.clearColor() self.refreshColorView.alpha = 0.30 // Create the graphic image views compass_background = UIImageView(image: UIImage(named: "compass_background")) self.compass_spinner = UIImageView(image: UIImage(named: "compass_spinner")) // Initalize flags self.isRefreshIconsOverlap = false; self.isRefreshAnimating = false; tableView.insertSubview(refreshControl, atIndex: 0) // When activated, invoke our refresh function refreshControl?.addTarget(self, action: "getUsersStatus", forControlEvents: UIControlEvents.ValueChanged) } // func refresh(){ // // self.user!.statuses({(tweets, error) ->() in // if let newTweets = tweets{ // self.tweets = newTweets // self.tableView.reloadData() // self.refreshControl!.endRefreshing() // //self.resetAnimation() // }else{ // print("error: \(error?.description)") // } // }) // } func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { print("scrollViewDidEndScrollingAnimation") self.blurEffectView.alpha = 0 } func scrollViewDidScroll(scrollView: UIScrollView) { // Get the current size of the refresh controller var refreshBounds = self.refreshControl!.bounds; // Distance the table has been pulled >= 0 //let pullDistance = max(0.0, -self.refreshControl!.frame.origin.y); let pullDistance = -self.refreshControl!.frame.origin.y // Calculate the pull ratio, between 0.0-1.0 let pullRatio = min( max(pullDistance, 0.0), 100.0) / 100.0; if pullDistance > 20{ self.blurEffectView.alpha = pullRatio }else{ self.blurEffectView.alpha = 0 } let userHeaderHeight = pullDistance + 170 self.bannerBackgroundImageView.frame = CGRectMake(0 , 0, self.view.frame.width, userHeaderHeight) print("pullDistance \(pullDistance), pullRatio: \(pullRatio), midX: (midX), refreshing: \(self.refreshControl!.refreshing)") } func resetAnimation() { print("resetAnimation") // Reset our flags and }background color blurEffectView.alpha = 0 self.isRefreshAnimating = false; self.isRefreshIconsOverlap = false; self.refreshColorView.backgroundColor = UIColor.clearColor() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
34.537313
154
0.623163
5d8fc42f78ab4ab501128e5c86e6a7c8bd8f9027
315
// // MIDIHUIParameterProtocol.swift // MIDIKitControlSurfaces • https://github.com/orchetect/MIDIKitControlSurfaces // import Foundation public protocol MIDIHUIParameterProtocol { /// HUI zone and port constant for the parameter @inlinable var zoneAndPort: MIDI.HUI.ZoneAndPortPair { get } }
22.5
80
0.746032
16dee13b102370aaf0b50deaa6783816a343f934
1,374
// // XCTestCase+Localization.swift // EssentialFeedTests // // Created by Khoi Nguyen on 28/12/20. // Copyright © 2020 Essential Developer. All rights reserved. // import XCTest protocol LocalizationTest: XCTestCase {} extension LocalizationTest { typealias LocalizedBundle = (bundle: Bundle, localization: String) func allLocalizationBundles(in bundle: Bundle, file: StaticString = #filePath, line: UInt = #line) -> [LocalizedBundle] { return bundle.localizations.compactMap { localization in guard let path = bundle.path(forResource: localization, ofType: "lproj"), let localizedBundle = Bundle(path: path) else { XCTFail("Couldn't find bundle for localization: \(localization)", file: file, line: line) return nil } return (localizedBundle, localization) } } func allLocalizedStringKeys(in bundles: [LocalizedBundle], table: String, file: StaticString = #filePath, line: UInt = #line) -> Set<String> { return bundles.reduce([]) { (acc, current) in guard let path = current.bundle.path(forResource: table, ofType: "strings"), let strings = NSDictionary(contentsOfFile: path), let keys = strings.allKeys as? [String] else { XCTFail("Couldn't load localized strings for localization: \(current.localization)", file: file, line: line) return acc } return acc.union(Set(keys)) } } }
29.234043
143
0.704512
03b9da41a186f5a029dddc5df85df50dceeccdaf
3,503
// // SWCircleProgressViewController.swift // SWKit // // Created by 刘宏立 on 2019/12/27. // Copyright © 2019 刘宏立. All rights reserved. // import UIKit class SWCircleProgressViewController: UIViewController { var shapelayer = CAShapeLayer() var progressContainer: UIView! let urlString = "http://panm32w98.bkt.clouddn.com/short_video_20191116010728.mp4" deinit { print("deinit \(self)") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white title = "CircleProgress" setupUI() } func setupUI() { let width: CGFloat = 120 let height: CGFloat = 50 let offset_y: CGFloat = 120 let btn = UIButton.init(type: .custom) view.addSubview(btn) btn.frame = CGRect(x: (SWSize.screenWidth - width)/2, y: offset_y, width: width, height: height) btn.setTitle("视频下载", for: .normal) btn.titleLabel?.textColor = UIColor.init(white: 0.7, alpha: 1) btn.backgroundColor = .systemTeal btn.layer.cornerRadius = height / 2 btn.layer.masksToBounds = true btn.action { [weak self](sender) in self?.downLoadVideo() } let width_p: CGFloat = 100 let f = CGRect(x: (SWSize.screenWidth - width_p)/2, y: (SWSize.screenHeight - SWSize.navBarHeight - width_p)/2, width: width_p, height: width_p) progressContainer = UIView.init(frame: f) self.view.addSubview(progressContainer) progressContainer.backgroundColor = .lightGray // progressContainer.isHidden = true // 进度条 let frame = CGRect(x: 0, y: 0, width: width_p, height: width_p) // let progressView = SWCircleProgress.init(frame: frame, radius: width_p/2 - 5) let progressView = SWCircleProgress.init(frame: frame) progressContainer.addSubview(progressView) progressView.backgroundColor = .orange progressView.shapelayer.strokeEnd = 0.0 progressView.trackLineWidth = 8 progressView.shapeLineWidth = 6 self.shapelayer = progressView.shapelayer } func downLoadVideo() { print("attempting to animate stroke") let configuration = URLSessionConfiguration.default let operationQueue = OperationQueue() let urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: operationQueue) guard let url = URL(string:urlString) else {return} let downloadTask = urlSession.downloadTask(with: url) downloadTask.resume() } } extension SWCircleProgressViewController: URLSessionDownloadDelegate{ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let percentage = CGFloat(totalBytesWritten) / CGFloat(totalBytesExpectedToWrite) DispatchQueue.main.async { if percentage > 0 && percentage < 1 { self.progressContainer.isHidden = false } else { self.progressContainer.isHidden = true } self.shapelayer.strokeEnd = percentage } print(percentage) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { print("finished downloading file") } }
36.113402
176
0.644876
1ea3d566ea5380e721d209b532a6bb967d3de7ff
1,776
// // BounceFilterActor.swift // Aojet // // Created by Qihe Bian on 6/6/16. // Copyright © 2016 Qihe Bian. All rights reserved. // class BounceFilterActor: Actor { static let bounceDelay: TimeInterval = 0.3 var lastMessage: TimeInterval = 0 var message: Message? var flushCancellable: ActorCancellable? func onMessage(message: Message) { let time = ActorTime.currentTime() let delta = time - lastMessage if (delta > type(of: self).bounceDelay) { lastMessage = time; if self.message == nil || isOverride(current: self.message, next: message) { // Send message message.actorRef.send(message: message.object); } else { // Send old message self.message!.actorRef.send(message: self.message!.object); } self.message = nil; } else { // Too early if (self.message == nil || isOverride(current: self.message, next: message)) { self.message = message; if (flushCancellable != nil) { flushCancellable!.cancel(); flushCancellable = nil; } flushCancellable = schedule(obj: Flush(), delay: type(of: self).bounceDelay - delta); } } } func onFlush() { if (message != nil) { message!.actorRef.send(message: message!.object); message = nil; lastMessage = ActorTime.currentTime(); } } func isOverride(current: Message?, next: Message?) -> Bool { return true } override func onReceive(message: Any) throws { switch message { case let m as Message: onMessage(message: m) case is Flush: onFlush() default: try super.onReceive(message: message) } } struct Message { let object: Any let actorRef: ActorRef } struct Flush { } }
24.666667
93
0.615428
ab7e2b03d873c8c1fcb44c2cf9ab2b2d663a884a
1,635
import XCTest @testable import Responder final class ResponderEventTests: XCTestCase { func testCanExecute() throws { let sut = ObjectTarget2(nextResponder: nil) sut.tryToHandle(Action.here) let event = try XCTUnwrap(sut.event) XCTAssertEqual(event, .here) } func testCanExecuteOnChain() throws { let sut = ObjectTarget2() let out = ObjectTarget1(nextResponder: sut) out.tryToHandle(Action.here) let event = try XCTUnwrap(sut.event) XCTAssertEqual(event, .here) } func testFirstFindExecuteSkipOthers() throws { let sut = ObjectTarget2() let out1 = ObjectTarget2(nextResponder: sut) let out2 = ObjectTarget1(nextResponder: out1) out2.tryToHandle(Action.here) XCTAssertNil(sut.event) let event = try XCTUnwrap(out1.event) XCTAssertEqual(event, .here) } static var allTests = [ ("testCanExecute", testCanExecute), ("testCanExecuteOnChain", testCanExecuteOnChain), ("testFirstFindExecuteSkipOthers", testFirstFindExecuteSkipOthers), ] } class ObjectTarget1: Responder { var nextResponder: Responder? init(nextResponder: Responder? = nil) { self.nextResponder = nextResponder } } class ObjectTarget2: ObjectTarget1, ActionProtocol { private(set) var event: Action? func send(event: Action) { self.event = event } } protocol ActionProtocol { func send(event: Action) } enum Action: Event { case here func sendToHandler(_ handler: ActionProtocol) { handler.send(event: self) } }
24.044118
75
0.66055
ab9c7349595781749795757dc6c701c16b4bd726
209
import PackageDescription let package = Package( name: "Action", targets: [], dependencies: [ .Package(url: "https://github.com/ReactiveX/RxSwift.git", majorVersion: 3, minor: 4) ] )
19
92
0.631579
d74da5b21496bb431ab3a9a4e7c1bb6786f85ac2
18,420
// // YF_KLineModel.swift // YF-KLine // // Created by tsaievan on 1/3/18. // Copyright © 2018年 tsaievan. All rights reserved. // import UIKit class YF_KLineModel: NSObject { ///< 货币类型 var CoinType: YF_CoinType? ///< 前一个model lazy var previousKLineModel: YF_KLineModel? = { let pm = YF_KLineModel() pm.DIF = 0.0 pm.DEA = 0.0 pm.MACD = 0.0 pm.MA7 = 0.0 pm.MA12 = 0.0 pm.MA26 = 0.0 pm.MA30 = 0.0 pm.EMA7 = 0.0 pm.EMA12 = 0.0 pm.EMA26 = 0.0 pm.EMA30 = 0.0 pm.Volume_MA7 = 0.0 pm.Volume_MA30 = 0.0 pm.Volume_EMA7 = 0.0 pm.Volume_EMA30 = 0.0 pm.SumOfLastClose = 0.0 pm.SumOfLastVolume = 0.0 pm.KDJ_K = 50.0 pm.KDJ_D = 50.0 pm.MA20 = 0.0 pm.BOLL_MD = 0.0 pm.BOLL_MB = 0.0 pm.BOLL_DN = 0.0 pm.BOLL_UP = 0.0 pm.BOLL_SUBMD_SUM = 0.0 pm.BOLL_SUBMD = 0.0 return pm }() ///< 父modelArray: 用来给当前Model索引到parent数组 var parentGroupModel: YF_KLineGroupModel? ///< 该model及其之前所有收盘价之和 var SumOfLastClose: Double? ///< 该model及其之前所有成交量之和 var SumOfLastVolume: Double? ///< 日期 var date: String? ///< 开盘价 var Open: Double? ///< 收盘价 var Close: Double? ///< 最高价 var High: Double? ///< 最低价 var Low: Double? ///< 成交量 var Volume: Double? ///< 是否是某个月的第一个交易日 var isFirstTradeDate: Bool? // MARK: - 内部自动初始化 ///< 移动平均数分为MA(简单移动平均数)和EMA(指数移动平均数), 其计算公式如下: ///< [C为收盘价, N为周期数] : ///< MA(N)=(C1+C2+……CN)/N ///< MA(7)=(C1+C2+……C7)/7 lazy var MA7: Double? = { var ma7: Double? if YF_StockChartVariable.isEMALine == .MA { guard let array = parentGroupModel?.models as NSArray? else { return ma7 } let index = array.index(of: self) if index >= 6 { guard let sum = SumOfLastClose, let oriArr = array as? [YF_KLineModel] else { return ma7 } if index > 6 { ma7 = (sum - (oriArr[index - 7].SumOfLastClose ?? 0)) / 7 }else { ma7 = sum / 7 } } return ma7 }else { ma7 = EMA7 return ma7 } }() ///< MA(30)=(C1+C2+……C30)/30 lazy var MA30: Double? = { var ma30: Double? if YF_StockChartVariable.isEMALine == .MA { guard let array = parentGroupModel?.models as NSArray? else { return ma30 } let index = array.index(of: self) if index >= 29 { guard let sum = SumOfLastClose, let oriArr = array as? [YF_KLineModel] else { return ma30 } ma30 = (sum - (oriArr[index - 30].SumOfLastClose ?? 0)) / 30 return ma30 }else { guard let sum = SumOfLastClose else { return ma30 } ma30 = sum / 30 return ma30 } }else { ma30 = EMA30 return ma30 } }() lazy var MA12: Double? = { var ma12: Double? guard let array = parentGroupModel?.models as NSArray? else { return ma12 } let index = array.index(of: self) if index >= 11 { guard let sum = SumOfLastClose, let oriArr = parentGroupModel?.models as? [YF_KLineModel] else { return ma12 } if index > 11 { ma12 = (sum - (oriArr[index - 12].SumOfLastClose ?? 0)) / 12 return ma12 }else { ma12 = sum / 12 return ma12 } } return ma12 }() lazy var MA26: Double? = { var ma26: Double? guard let array = parentGroupModel?.models as NSArray? else { return ma26 } let index = array.index(of: self) if index >= 25 { guard let sum = SumOfLastClose, let oriArr = parentGroupModel?.models as? [YF_KLineModel] else { return ma26 } if index > 25 { ma26 = (sum - (oriArr[index - 26].SumOfLastClose ?? 0)) / 26 return ma26 }else { ma26 = sum / 26 return ma26 } } return ma26 }() lazy var Volume_MA7: Double? = { var vma7: Double? if YF_StockChartVariable.isEMALine == .MA { guard let array = parentGroupModel?.models as NSArray? else { return vma7 } let index = array.index(of: self) if index >= 6 { guard let sum = SumOfLastVolume, let oriArr = array as? [YF_KLineModel] else { return vma7 } if index > 6 { vma7 = (sum - (oriArr[index - 7].SumOfLastVolume ?? 0)) / 7 return vma7 }else { vma7 = sum / 7 return vma7 } } }else { vma7 = Volume_EMA7 return vma7 } return vma7 }() lazy var Volume_MA30: Double? = { var vma30: Double? if YF_StockChartVariable.isEMALine == .MA { guard let array = parentGroupModel?.models as NSArray? else { return vma30 } let index = array.index(of: self) if index >= 29 { guard let sum = SumOfLastVolume, let oriArr = array as? [YF_KLineModel] else { return vma30 } if index > 29 { vma30 = (sum - (oriArr[index - 30].SumOfLastVolume ?? 0)) / 30 }else { vma30 = sum / 30 } return vma30 } }else { vma30 = Volume_EMA30 return vma30 } return vma30 }() lazy var Volume_EMA7: Double? = { var vema7: Double = 0.0 guard let v = Volume, let pv = previousKLineModel?.Volume_EMA7 else { return vema7 } vema7 = (v + 3 * pv) / 4 return vema7 }() lazy var Volume_EMA30: Double? = { var vema30: Double = 0.0 guard let v = Volume, let pv = previousKLineModel?.Volume_EMA30 else { return vema30 } vema30 = (2 * v + 29 * pv) / 31 return vema30 }() // MARK: - BOLL线 lazy var MA20: Double? = { var ma20: Double? guard let array = parentGroupModel?.models as NSArray?, let sum = SumOfLastClose else { return ma20 } let index = array.index(of: self) if index >= 19 { guard let oriArr = array as? [YF_KLineModel] else { return ma20 } if index > 19 { ma20 = (sum - (oriArr[index - 20].SumOfLastClose ?? 0)) / 20 return ma20 }else { guard let sum = SumOfLastClose else { return ma20 } ma20 = sum / 20 return ma20 } } return ma20 }() lazy var BOLL_MD: Double? = { var bmd: Double? guard let array = parentGroupModel?.models as NSArray?, let sum = previousKLineModel?.BOLL_SUBMD_SUM else { return bmd } let index = array.index(of: self) if index >= 20 { guard let oriArr = parentGroupModel?.models as? [YF_KLineModel] else { return bmd } bmd = sqrt((sum - (oriArr[index - 20].BOLL_SUBMD_SUM ?? 0)) / 20) return bmd } return bmd }() lazy var BOLL_MB: Double? = { var bmb: Double? guard let array = parentGroupModel?.models as NSArray?, let sum = SumOfLastClose else { return bmb } let index = array.index(of: self) if index >= 19 { guard let oriArr = parentGroupModel?.models as? [YF_KLineModel] else { return bmb } if index > 19 { bmb = (sum - (oriArr[index - 19].SumOfLastClose ?? 0)) / 20 return bmb }else { bmb = sum / Double(index) return bmb } } return bmb }() lazy var BOLL_UP: Double? = { var bup: Double? guard let array = parentGroupModel?.models as NSArray? else { return bup } let index = array.index(of: self) guard let bmb = BOLL_MB, let bmd = BOLL_MD else { return bup } bup = bmb + 2 * bmd return bup }() lazy var BOLL_DN: Double? = { var bdn: Double? guard let array = parentGroupModel?.models as NSArray? else { return bdn } let index = array.index(of: self) guard let bmb = BOLL_MB, let bmd = BOLL_MD else { return bdn } bdn = bmb - 2 * bmd return bdn }() lazy var BOLL_SUBMD_SUM: Double? = { var bss: Double? guard let array = parentGroupModel?.models as NSArray? else { return bss } let index = array.index(of: self) guard let sum = previousKLineModel?.BOLL_SUBMD_SUM, let bs = BOLL_SUBMD else { return bss } bss = sum + bs return bss }() lazy var BOLL_SUBMD: Double? = { var bs: Double? guard let array = parentGroupModel?.models as NSArray? else { return bs } let index = array.index(of: self) guard let close = Close, let ma20 = MA20 else { return bs } if index >= 20 { bs = (close - ma20) * (close - ma20) return bs } return bs }() lazy var EMA7: Double? = { var ema7: Double? guard let close = Close, let pema7 = previousKLineModel?.EMA7 else { return ema7 } ema7 = (close + 3 * pema7) / 4 return ema7 }() lazy var EMA30: Double? = { var ema30: Double? guard let close = Close, let pema30 = previousKLineModel?.EMA30 else { return ema30 } ema30 = (2 * close + 29 * pema30) / 31 return ema30 }() lazy var EMA12: Double? = { var ema12: Double? guard let close = Close, let pema12 = previousKLineModel?.EMA12 else { return ema12 } ema12 = (2 * close + 11 * pema12) / 13 return ema12 }() lazy var EMA26: Double? = { var ema26: Double? guard let close = Close, let pema26 = previousKLineModel?.EMA26 else { return ema26 } ema26 = (2 * close + 25 * pema26) / 27 return ema26 }() lazy var DIF: Double? = { var dif: Double? guard let ema12 = EMA12, let ema26 = EMA26 else { return dif } dif = ema12 - ema26 return dif }() lazy var DEA: Double? = { var dea: Double? guard let d = previousKLineModel?.DEA, let dif = DIF else { return dea } dea = d * 0.8 + 0.2 * dif return dea }() lazy var MACD: Double? = { var macd: Double? guard let dif = DIF, let dea = DEA else { return macd } macd = 2 * (dif - dea) return macd }() ///< 9Clock内最低价 var NineClocksMinPrice: Double? ///< 9Clock内最高价 var NineClocksMaxPrice: Double? lazy var RSV_9: Double? = { var rsv_9 = 100.0 guard let min = NineClocksMinPrice, let max = NineClocksMaxPrice, let close = Close else { return rsv_9 } if min == max { return rsv_9 }else { rsv_9 = (close - min) * 100 / (max - min) return rsv_9 } }() lazy var KDJ_K: Double? = { var kdj_k: Double? guard let rsv_9 = RSV_9 else { return kdj_k } guard let pModel = previousKLineModel, let k = pModel.KDJ_K else { kdj_k = (rsv_9 + 2 * 50) / 3 return kdj_k } kdj_k = (rsv_9 + 2 * k) / 3 return kdj_k }() lazy var KDJ_D: Double? = { var kdj_d: Double? guard let kdj_k = KDJ_K else { return kdj_d } guard let pModel = previousKLineModel, let k = pModel.KDJ_D else { kdj_d = (kdj_k + 2 * 50) / 3 return kdj_d } kdj_d = (kdj_k + 2 * k) / 3 return kdj_d }() lazy var KDJ_J: Double? = { var kdj_j: Double? guard let k = KDJ_K, let d = KDJ_D else{ return kdj_j } kdj_j = 3 * k - 2 * d return kdj_j }() ///< 初始化一些基本数据 func initWith(array: [Any]) { date = array[0] as? String Open = (array[1] as? NSString)?.doubleValue Close = (array[2] as? NSString)?.doubleValue Low = (array[5] as? NSString)?.doubleValue High = (array[6] as? NSString)?.doubleValue Volume = (array[8] as? NSString)?.doubleValue SumOfLastClose = (Close ?? 0) + (previousKLineModel?.SumOfLastClose ?? 0) SumOfLastVolume = (Volume ?? 0) + (previousKLineModel?.SumOfLastVolume ?? 0) } func initFirstModel() { //FIXME: -不知道这么写对不对, 先把这俩函数调一遍吧 // getNineClocksMaxPrice() // getNineClocksMinPrice() KDJ_K = 55.27 KDJ_D = 55.27 KDJ_J = 55.27 EMA7 = Close EMA12 = Close EMA26 = Close EMA30 = Close NineClocksMinPrice = Low NineClocksMaxPrice = High DIF = DIF ?? 0 DEA = DEA ?? 0 MACD = MACD ?? 0 guard let _ = parentGroupModel?.models as? [YF_KLineModel] else{ return } rangeLastNinePrice(byArray: parentGroupModel?.models as! [YF_KLineModel], condition: .orderedAscending) rangeLastNinePrice(byArray: parentGroupModel?.models as! [YF_KLineModel], condition: .orderedDescending) RSV_9 = RSV_9 ?? 0 KDJ_K = KDJ_K ?? 0 KDJ_D = KDJ_D ?? 0 KDJ_J = KDJ_J ?? 0 MA20 = MA20 ?? 0 BOLL_MD = BOLL_MD ?? 0 BOLL_MB = BOLL_MB ?? 0 BOLL_UP = BOLL_UP ?? 0 BOLL_DN = BOLL_DN ?? 0 BOLL_SUBMD = BOLL_SUBMD ?? 0 BOLL_SUBMD_SUM = BOLL_SUBMD_SUM ?? 0 } func initData() { //FIXME:- 这里的算法还有点问题, 前7个点应该没有MA7数据的 MA7 = MA7 ?? 0 MA12 = MA12 ?? 0 MA26 = MA26 ?? 0 MA30 = MA30 ?? 0 EMA7 = EMA7 ?? 0 EMA12 = EMA12 ?? 0 EMA26 = EMA26 ?? 0 EMA30 = EMA30 ?? 0 DIF = DIF ?? 0 DEA = DEA ?? 0 MACD = MACD ?? 0 RSV_9 = RSV_9 ?? 0 KDJ_K = KDJ_K ?? 0 KDJ_D = KDJ_D ?? 0 KDJ_J = KDJ_J ?? 0 MA20 = MA20 ?? 0 BOLL_MD = BOLL_MD ?? 0 BOLL_MB = BOLL_MB ?? 0 BOLL_UP = BOLL_UP ?? 0 BOLL_DN = BOLL_DN ?? 0 BOLL_SUBMD = BOLL_SUBMD ?? 0 BOLL_SUBMD_SUM = BOLL_SUBMD_SUM ?? 0 } } extension YF_KLineModel { fileprivate func rangeLastNinePrice(byArray array: [YF_KLineModel], condition: ComparisonResult) { let count = array.count switch condition { case .orderedAscending: for j in (1...7).reversed() { var emMaxValue = 0.0 var em = j while em >= 0 { guard let high = array[em].High else { break } if emMaxValue < high { emMaxValue = high } em = em - 1 } array[j].NineClocksMaxPrice = emMaxValue } for j in (8 ..< count) { var i = 0 var emMaxValue = 0.0 var em = j while em >= i { guard let high = array[em].High else { break } if emMaxValue < high { emMaxValue = high } em = em - 1 } array[j].NineClocksMaxPrice = emMaxValue i = i + 1 } case .orderedDescending: for j in (1...7).reversed() { var emMinValue = 10000000000.0 var em = j while em >= 0 { guard let low = array[em].Low else { break } if emMinValue > low { emMinValue = low } em = em - 1 } array[j].NineClocksMinPrice = emMinValue } for j in (0 ..< count) { var i = 0 var emMinValue = 10000000000.0 var em = j while em >= i { guard let low = array[em].Low else { break } if emMinValue > low { emMinValue = low } em = em - 1 } array[j].NineClocksMinPrice = emMinValue i = i + 1 } default: break } } }
28.294931
112
0.446037
26e9d919aeac7833308537e16bb8ea40f4a79179
14,353
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import _SwiftDispatchOverlayShims public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { public typealias Iterator = DispatchDataIterator public typealias Index = Int public typealias Indices = DefaultIndices<DispatchData> public static let empty: DispatchData = DispatchData(data: _swift_dispatch_data_empty()) public enum Deallocator { /// Use `free` case free /// Use `munmap` case unmap /// A custom deallocator case custom(DispatchQueue?, @convention(block) () -> Void) fileprivate var _deallocator: (DispatchQueue?, @convention(block) () -> Void) { switch self { case .free: return (nil, _swift_dispatch_data_destructor_free()) case .unmap: return (nil, _swift_dispatch_data_destructor_munmap()) case .custom(let q, let b): return (q, b) } } } fileprivate var __wrapped: __DispatchData /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. @available(swift, deprecated: 4, message: "Use init(bytes: UnsafeRawBufferPointer) instead") public init(bytes buffer: UnsafeBufferPointer<UInt8>) { __wrapped = buffer.baseAddress == nil ? _swift_dispatch_data_empty() : _swift_dispatch_data_create(buffer.baseAddress!, buffer.count, nil, _swift_dispatch_data_destructor_default()) as! __DispatchData } /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. public init(bytes buffer: UnsafeRawBufferPointer) { __wrapped = buffer.baseAddress == nil ? _swift_dispatch_data_empty() : _swift_dispatch_data_create(buffer.baseAddress!, buffer.count, nil, _swift_dispatch_data_destructor_default()) as! __DispatchData } /// Initialize a `Data` without copying the bytes. /// /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer. @available(swift, deprecated: 4, message: "Use init(bytesNoCopy: UnsafeRawBufferPointer, deallocater: Deallocator) instead") public init(bytesNoCopy bytes: UnsafeBufferPointer<UInt8>, deallocator: Deallocator = .free) { let (q, b) = deallocator._deallocator __wrapped = bytes.baseAddress == nil ? _swift_dispatch_data_empty() : _swift_dispatch_data_create(bytes.baseAddress!, bytes.count, q, b) as! __DispatchData } /// Initialize a `Data` without copying the bytes. /// /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer. public init(bytesNoCopy bytes: UnsafeRawBufferPointer, deallocator: Deallocator = .free) { let (q, b) = deallocator._deallocator __wrapped = bytes.baseAddress == nil ? _swift_dispatch_data_empty() : _swift_dispatch_data_create(bytes.baseAddress!, bytes.count, q, b) as! __DispatchData } internal init(data: __DispatchData) { __wrapped = data } public var count: Int { return __dispatch_data_get_size(__wrapped) } public func withUnsafeBytes<Result, ContentType>( body: (UnsafePointer<ContentType>) throws -> Result) rethrows -> Result { var ptr: UnsafeRawPointer? var size = 0 let data = __dispatch_data_create_map(__wrapped, &ptr, &size) let contentPtr = ptr!.bindMemory( to: ContentType.self, capacity: size / MemoryLayout<ContentType>.stride) defer { _fixLifetime(data) } return try body(contentPtr) } @available(swift 4.2) public func enumerateBytes( _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Int, _ stop: inout Bool) -> Void) { enumerateBytesCommon(block) } @available(swift, obsoleted: 4.2, renamed: "enumerateBytes(_:)") public func enumerateBytes( block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Int, _ stop: inout Bool) -> Void) { enumerateBytesCommon(block) } private func enumerateBytesCommon( _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Int, _ stop: inout Bool) -> Void) { _swift_dispatch_data_apply(__wrapped) { (_, offset: Int, ptr: UnsafeRawPointer, size: Int) in let bytePtr = ptr.bindMemory(to: UInt8.self, capacity: size) let bp = UnsafeBufferPointer(start: bytePtr, count: size) var stop = false block(bp, offset, &stop) return stop ? 0 : 1 } } /// Append bytes to the data. /// /// - parameter bytes: A pointer to the bytes to copy in to the data. /// - parameter count: The number of bytes to copy. @available(swift, deprecated: 4, message: "Use append(_: UnsafeRawBufferPointer) instead") public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) { let data = _swift_dispatch_data_create(bytes, count, nil, _swift_dispatch_data_destructor_default()) as! __DispatchData self.append(DispatchData(data: data)) } /// Append bytes to the data. /// /// - parameter bytes: A pointer to the bytes to copy in to the data. /// - parameter count: The number of bytes to copy. public mutating func append(_ bytes: UnsafeRawBufferPointer) { // Nil base address does nothing. guard bytes.baseAddress != nil else { return } let data = _swift_dispatch_data_create(bytes.baseAddress!, bytes.count, nil, _swift_dispatch_data_destructor_default()) as! __DispatchData self.append(DispatchData(data: data)) } /// Append data to the data. /// /// - parameter data: The data to append to this data. public mutating func append(_ other: DispatchData) { let data = __dispatch_data_create_concat(__wrapped, other.__wrapped) __wrapped = data } /// Append a buffer of bytes to the data. /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { buffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: buffer.count * MemoryLayout<SourceType>.stride) { self.append($0, count: buffer.count * MemoryLayout<SourceType>.stride) } } private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: Range<Index>) { var copiedCount = 0 if range.isEmpty { return } let rangeSize = range.count __dispatch_data_apply(__wrapped) { (_, offset: Int, ptr: UnsafeRawPointer, size: Int) in if offset >= range.endIndex { return false } // This region is after endIndex let copyOffset = range.startIndex > offset ? range.startIndex - offset : 0 // offset of first byte, in this region if copyOffset >= size { return true } // This region is before startIndex let count = Swift.min(rangeSize - copiedCount, size - copyOffset) memcpy(pointer + copiedCount, ptr + copyOffset, count) copiedCount += count return copiedCount < rangeSize } } /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter count: The number of bytes to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes. @available(swift, deprecated: 4, message: "Use copyBytes(to: UnsafeMutableRawBufferPointer, count: Int) instead") public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) { _copyBytesHelper(to: pointer, from: 0..<count) } /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. The buffer must be large /// enough to hold `count` bytes. /// - parameter count: The number of bytes to copy. public func copyBytes(to pointer: UnsafeMutableRawBufferPointer, count: Int) { assert(count <= pointer.count, "Buffer too small to copy \(count) bytes") guard pointer.baseAddress != nil else { return } _copyBytesHelper(to: pointer.baseAddress!, from: 0..<count) } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter range: The range in the `Data` to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes. @available(swift, deprecated: 4, message: "Use copyBytes(to: UnsafeMutableRawBufferPointer, from: Range<Index>) instead") public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) { _copyBytesHelper(to: pointer, from: range) } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. The buffer must be large /// enough to hold `count` bytes. /// - parameter range: The range in the `Data` to copy. public func copyBytes(to pointer: UnsafeMutableRawBufferPointer, from range: Range<Index>) { assert(range.count <= pointer.count, "Buffer too small to copy \(range.count) bytes") guard pointer.baseAddress != nil else { return } _copyBytesHelper(to: pointer.baseAddress!, from: range) } /// Copy the contents of the data into a buffer. /// /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. /// - returns: Number of bytes copied into the destination buffer. public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int { let cnt = count guard cnt > 0 else { return 0 } let copyRange : Range<Index> if let r = range { guard !r.isEmpty else { return 0 } precondition(r.startIndex >= 0) precondition(r.startIndex < cnt, "The range is outside the bounds of the data") precondition(r.endIndex >= 0) precondition(r.endIndex <= cnt, "The range is outside the bounds of the data") copyRange = r.startIndex..<(r.startIndex + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count)) } else { copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt) } guard !copyRange.isEmpty else { return 0 } _copyBytesHelper(to: buffer.baseAddress!, from: copyRange) return copyRange.count } /// Sets or returns the byte at the specified index. public subscript(index: Index) -> UInt8 { var offset = 0 let subdata = __dispatch_data_copy_region(__wrapped, index, &offset) var ptr: UnsafeRawPointer? var size = 0 let map = __dispatch_data_create_map(subdata, &ptr, &size) defer { _fixLifetime(map) } return ptr!.load(fromByteOffset: index - offset, as: UInt8.self) } public subscript(bounds: Range<Int>) -> Slice<DispatchData> { return Slice(base: self, bounds: bounds) } /// Return a new copy of the data in a specified range. /// /// - parameter range: The range to copy. public func subdata(in range: Range<Index>) -> DispatchData { let subrange = __dispatch_data_create_subrange( __wrapped, range.startIndex, range.endIndex - range.startIndex) return DispatchData(data: subrange) } public func region(location: Int) -> (data: DispatchData, offset: Int) { var offset: Int = 0 let data = __dispatch_data_copy_region(__wrapped, location, &offset) return (DispatchData(data: data), offset) } public var startIndex: Index { return 0 } public var endIndex: Index { return count } public func index(before i: Index) -> Index { return i - 1 } public func index(after i: Index) -> Index { return i + 1 } /// An iterator over the contents of the data. /// /// The iterator will increment byte-by-byte. public func makeIterator() -> DispatchData.Iterator { return DispatchDataIterator(_data: self) } } public struct DispatchDataIterator : IteratorProtocol, Sequence { public typealias Element = UInt8 /// Create an iterator over the given DispatchData public init(_data: DispatchData) { var ptr: UnsafeRawPointer? self._count = 0 self._data = __dispatch_data_create_map( _data as __DispatchData, &ptr, &self._count) self._ptr = ptr self._position = _data.startIndex // The only time we expect a 'nil' pointer is when the data is empty. assert(self._ptr != nil || self._count == self._position) } /// Advance to the next element and return it, or `nil` if no next /// element exists. public mutating func next() -> DispatchData.Element? { if _position == _count { return nil } let element = _ptr.load(fromByteOffset: _position, as: UInt8.self) _position = _position + 1 return element } internal let _data: __DispatchData internal var _ptr: UnsafeRawPointer! internal var _count: Int internal var _position: DispatchData.Index } extension DispatchData { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> __DispatchData { return __wrapped } public static func _forceBridgeFromObjectiveC(_ input: __DispatchData, result: inout DispatchData?) { result = DispatchData(data: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: __DispatchData, result: inout DispatchData?) -> Bool { result = DispatchData(data: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: __DispatchData?) -> DispatchData { var result: DispatchData? _forceBridgeFromObjectiveC(source!, result: &result) return result! } }
39.108992
230
0.720337
c1c872986ef97ec5c3e4193d1fba729c43f3a10b
4,129
import Foundation import UIKit import AsyncDisplayKit public enum PeekControllerMenuItemColor { case accent case destructive } public enum PeekControllerMenuItemFont { case `default` case bold } public struct PeekControllerMenuItem { public let title: String public let color: PeekControllerMenuItemColor public let font: PeekControllerMenuItemFont public let action: (ASDisplayNode, CGRect) -> Bool public init(title: String, color: PeekControllerMenuItemColor, font: PeekControllerMenuItemFont = .default, action: @escaping (ASDisplayNode, CGRect) -> Bool) { self.title = title self.color = color self.font = font self.action = action } } final class PeekControllerMenuItemNode: HighlightTrackingButtonNode { private let item: PeekControllerMenuItem private let activatedAction: () -> Void private let separatorNode: ASDisplayNode private let highlightedBackgroundNode: ASDisplayNode private let textNode: ImmediateTextNode init(theme: PeekControllerTheme, item: PeekControllerMenuItem, activatedAction: @escaping () -> Void) { self.item = item self.activatedAction = activatedAction self.separatorNode = ASDisplayNode() self.separatorNode.isLayerBacked = true self.separatorNode.backgroundColor = theme.menuItemSeparatorColor self.highlightedBackgroundNode = ASDisplayNode() self.highlightedBackgroundNode.isLayerBacked = true self.highlightedBackgroundNode.backgroundColor = theme.menuItemHighligtedColor self.highlightedBackgroundNode.alpha = 0.0 self.textNode = ImmediateTextNode() self.textNode.isUserInteractionEnabled = false self.textNode.displaysAsynchronously = false let textColor: UIColor let textFont: UIFont switch item.color { case .accent: textColor = theme.accentColor case .destructive: textColor = theme.destructiveColor } switch item.font { case .default: textFont = Font.regular(20.0) case .bold: textFont = Font.medium(20.0) } self.textNode.attributedText = NSAttributedString(string: item.title, font: textFont, textColor: textColor) super.init() self.addSubnode(self.separatorNode) self.addSubnode(self.highlightedBackgroundNode) self.addSubnode(self.textNode) self.highligthedChanged = { [weak self] highlighted in if let strongSelf = self { if highlighted { strongSelf.view.superview?.bringSubviewToFront(strongSelf.view) strongSelf.highlightedBackgroundNode.alpha = 1.0 } else { strongSelf.highlightedBackgroundNode.alpha = 0.0 strongSelf.highlightedBackgroundNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.3) } } } self.addTarget(self, action: #selector(self.buttonPressed), forControlEvents: .touchUpInside) } func updateLayout(width: CGFloat, transition: ContainedViewLayoutTransition) -> CGFloat { let height: CGFloat = 57.0 transition.updateFrame(node: self.highlightedBackgroundNode, frame: CGRect(origin: CGPoint(), size: CGSize(width: width, height: height))) transition.updateFrame(node: self.separatorNode, frame: CGRect(origin: CGPoint(x: 0.0, y: height), size: CGSize(width: width, height: UIScreenPixel))) let textSize = self.textNode.updateLayout(CGSize(width: width - 10.0, height: height)) transition.updateFrame(node: self.textNode, frame: CGRect(origin: CGPoint(x: floor((width - textSize.width) / 2.0), y: floor((height - textSize.height) / 2.0)), size: textSize)) return height } @objc func buttonPressed() { self.activatedAction() if self.item.action(self, self.bounds) { } } }
37.880734
185
0.651005
6278b28fb8f89f6ddab7bf12c28a47f8c3647391
729
@testable import SendGrid import XCTest class SessionTests: XCTestCase { func testSendWithoutAuth() { let session = Session() let personalization = [Personalization(recipients: "[email protected]")] let email = Email(personalizations: personalization, from: Address(email: "[email protected]"), content: [Content.plainText(body: "plain")], subject: "Hello World") do { try session.send(request: email) XCTFail("Expected failure when sending a request without authentication, but nothing was thrown.") } catch SendGrid.Exception.Session.authenticationMissing { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } } }
38.368421
166
0.659808
4607fa64f4bd01aa5d1a660095628e83c1fc2f8a
12,869
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // 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 XCTest import RealmSwift import Foundation class ObjectTests: TestCase { // init() Tests are in ObjectCreationTests.swift // init(value:) tests are in ObjectCreationTests.swift func testRealm() { let standalone = SwiftStringObject() XCTAssertNil(standalone.realm) let realm = try! Realm() var persisted: SwiftStringObject! realm.write { persisted = realm.create(SwiftStringObject.self, value: [:]) XCTAssertNotNil(persisted.realm) XCTAssertEqual(realm, persisted.realm!) } XCTAssertNotNil(persisted.realm) XCTAssertEqual(realm, persisted.realm!) dispatchSyncNewThread { autoreleasepool { XCTAssertNotEqual(try! Realm(), persisted.realm!) } } } func testObjectSchema() { let object = SwiftObject() let schema = object.objectSchema XCTAssert(schema as AnyObject is ObjectSchema) XCTAssert(schema.properties as AnyObject is [Property]) XCTAssertEqual(schema.className, "SwiftObject") XCTAssertEqual(schema.properties.map { $0.name }, ["boolCol", "intCol", "floatCol", "doubleCol", "stringCol", "binaryCol", "dateCol", "objectCol", "arrayCol"]) } func testInvalidated() { let object = SwiftObject() XCTAssertFalse(object.invalidated) let realm = try! Realm() realm.write { realm.add(object) XCTAssertFalse(object.invalidated) } realm.write { realm.deleteAll() XCTAssertTrue(object.invalidated) } XCTAssertTrue(object.invalidated) } func testDescription() { let object = SwiftObject() XCTAssertEqual(object.description, "SwiftObject {\n\tboolCol = 0;\n\tintCol = 123;\n\tfloatCol = 1.23;\n\tdoubleCol = 12.3;\n\tstringCol = a;\n\tbinaryCol = <61 — 1 total bytes>;\n\tdateCol = 1970-01-01 00:00:01 +0000;\n\tobjectCol = SwiftBoolObject {\n\t\tboolCol = 0;\n\t};\n\tarrayCol = List<SwiftBoolObject> (\n\t\n\t);\n}") let recursiveObject = SwiftRecursiveObject() recursiveObject.objects.append(recursiveObject) XCTAssertEqual(recursiveObject.description, "SwiftRecursiveObject {\n\tobjects = List<SwiftRecursiveObject> (\n\t\t[0] SwiftRecursiveObject {\n\t\t\tobjects = List<SwiftRecursiveObject> (\n\t\t\t\t[0] SwiftRecursiveObject {\n\t\t\t\t\tobjects = <Maximum depth exceeded>;\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t);\n}") } func testPrimaryKey() { XCTAssertNil(Object.primaryKey(), "primary key should default to nil") XCTAssertNil(SwiftStringObject.primaryKey()) XCTAssertNil(SwiftStringObject().objectSchema.primaryKeyProperty) XCTAssertEqual(SwiftPrimaryStringObject.primaryKey()!, "stringCol") XCTAssertEqual(SwiftPrimaryStringObject().objectSchema.primaryKeyProperty!.name, "stringCol") } func testIgnoredProperties() { XCTAssertEqual(Object.ignoredProperties(), [], "ignored properties should default to []") XCTAssertEqual(SwiftIgnoredPropertiesObject.ignoredProperties().count, 2) XCTAssertNil(SwiftIgnoredPropertiesObject().objectSchema["runtimeProperty"]) } func testIndexedProperties() { XCTAssertEqual(Object.indexedProperties(), [], "indexed properties should default to []") XCTAssertEqual(SwiftIndexedPropertiesObject.indexedProperties().count, 1) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["stringCol"]!.indexed) } func testLinkingObjects() { let realm = try! Realm() let object = SwiftEmployeeObject() assertThrows(object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees")) realm.write { realm.add(object) self.assertThrows(object.linkingObjects(SwiftCompanyObject.self, forProperty: "noSuchCol")) XCTAssertEqual(0, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) for _ in 0..<10 { realm.create(SwiftCompanyObject.self, value: [[object]]) } XCTAssertEqual(10, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) } XCTAssertEqual(10, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) } func testValueForKey() { let test: (SwiftObject) -> () = { object in XCTAssertEqual(object.valueForKey("boolCol") as! Bool!, false) XCTAssertEqual(object.valueForKey("intCol") as! Int!, 123) XCTAssertEqual(object.valueForKey("floatCol") as! Float!, 1.23 as Float) XCTAssertEqual(object.valueForKey("doubleCol") as! Double!, 12.3) XCTAssertEqual(object.valueForKey("stringCol") as! String!, "a") XCTAssertEqual(object.valueForKey("binaryCol") as! NSData, "a".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) XCTAssertEqual(object.valueForKey("dateCol") as! NSDate!, NSDate(timeIntervalSince1970: 1)) XCTAssertEqual((object.valueForKey("objectCol")! as! SwiftBoolObject).boolCol, false) XCTAssert(object.valueForKey("arrayCol")! is List<SwiftBoolObject>) } test(SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) test(persistedObject) } } func setAndTestAllTypes(setter: (SwiftObject, AnyObject?, String) -> (), getter: (SwiftObject, String) -> (AnyObject?), object: SwiftObject) { setter(object, true, "boolCol") XCTAssertEqual(getter(object, "boolCol") as! Bool!, true) setter(object, 321, "intCol") XCTAssertEqual(getter(object, "intCol") as! Int!, 321) setter(object, 32.1 as Float, "floatCol") XCTAssertEqual(getter(object, "floatCol") as! Float!, 32.1 as Float) setter(object, 3.21, "doubleCol") XCTAssertEqual(getter(object, "doubleCol") as! Double!, 3.21) setter(object, "z", "stringCol") XCTAssertEqual(getter(object, "stringCol") as! String!, "z") setter(object, "z".dataUsingEncoding(NSUTF8StringEncoding), "binaryCol") XCTAssertEqual(getter(object, "binaryCol") as! NSData, "z".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) setter(object, NSDate(timeIntervalSince1970: 333), "dateCol") XCTAssertEqual(getter(object, "dateCol") as! NSDate!, NSDate(timeIntervalSince1970: 333)) let boolObject = SwiftBoolObject(value: [true]) setter(object, boolObject, "objectCol") XCTAssertEqual(getter(object, "objectCol") as! SwiftBoolObject, boolObject) XCTAssertEqual((getter(object, "objectCol")! as! SwiftBoolObject).boolCol, true) let list = List<SwiftBoolObject>() list.append(boolObject) setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).first!, boolObject) list.removeAll(); setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 0) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).first!, boolObject) } func dynamicSetAndTestAllTypes(setter: (DynamicObject, AnyObject?, String) -> (), getter: (DynamicObject, String) -> (AnyObject?), object: DynamicObject, boolObject: DynamicObject) { setter(object, true, "boolCol") XCTAssertEqual(getter(object, "boolCol") as! Bool, true) setter(object, 321, "intCol") XCTAssertEqual(getter(object, "intCol") as! Int, 321) setter(object, 32.1 as Float, "floatCol") XCTAssertEqual(getter(object, "floatCol") as! Float, 32.1 as Float) setter(object, 3.21, "doubleCol") XCTAssertEqual(getter(object, "doubleCol") as! Double, 3.21) setter(object, "z", "stringCol") XCTAssertEqual(getter(object, "stringCol") as! String, "z") setter(object, "z".dataUsingEncoding(NSUTF8StringEncoding), "binaryCol") XCTAssertEqual(getter(object, "binaryCol") as! NSData, "z".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) setter(object, NSDate(timeIntervalSince1970: 333), "dateCol") XCTAssertEqual(getter(object, "dateCol") as! NSDate, NSDate(timeIntervalSince1970: 333)) setter(object, boolObject, "objectCol") XCTAssertEqual(getter(object, "objectCol") as! DynamicObject, boolObject) XCTAssertEqual((getter(object, "objectCol") as! DynamicObject)["boolCol"] as! NSNumber, true as NSNumber) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).first!, boolObject) let list = getter(object, "arrayCol") as! List<DynamicObject> list.removeAll(); setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 0) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).first!, boolObject) } /// Yields a read-write migration `SwiftObject` to the given block private func withMigrationObject(block: ((MigrationObject, Migration) -> ())) { autoreleasepool { let realm = self.realmWithTestPath() realm.write { _ = realm.create(SwiftObject) } } autoreleasepool { var enumerated = false setSchemaVersion(1, realmPath: self.testRealmPath()) { migration, _ in migration.enumerate(SwiftObject.className()) { oldObject, newObject in if let newObject = newObject { block(newObject, migration) enumerated = true } } } self.realmWithTestPath() XCTAssert(enumerated) } } func testSetValueForKey() { let setter : (Object, AnyObject?, String) -> () = { object, value, key in object.setValue(value, forKey: key) return } let getter : (Object, String) -> (AnyObject?) = { object, key in object.valueForKey(key) } withMigrationObject { migrationObject, migration in let boolObject = migration.create("SwiftBoolObject", value: [true]) self.dynamicSetAndTestAllTypes(setter, getter: getter, object: migrationObject, boolObject: boolObject) } setAndTestAllTypes(setter, getter: getter, object: SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) self.setAndTestAllTypes(setter, getter: getter, object: persistedObject) } } func testSubscript() { let setter : (Object, AnyObject?, String) -> () = { object, value, key in object[key] = value return } let getter : (Object, String) -> (AnyObject?) = { object, key in object[key] } withMigrationObject { migrationObject, migration in let boolObject = migration.create("SwiftBoolObject", value: [true]) self.dynamicSetAndTestAllTypes(setter, getter: getter, object: migrationObject, boolObject: boolObject) } setAndTestAllTypes(setter, getter: getter, object: SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) self.setAndTestAllTypes(setter, getter: getter, object: persistedObject) } } }
44.684028
336
0.641309
de6f0249765832fc2b15a85c2d757ba076422db0
256
// // ViewController.swift // Demo // // Created by Esteban Torres on 6/7/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
15.058824
52
0.683594
5b5ef1048e056393ebc381e2b349a92179f66595
1,241
// // MDSATUITests.swift // MDSATUITests // // Created by Salman Qureshi on 5/25/18. // Copyright © 2018 Salman Qureshi. All rights reserved. // import XCTest class MDSATUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.540541
182
0.661563
2225a0f4050a42a32af620badd2e0dc6312e49ac
15,645
// // FormatsTableViewController.swift // GeneralSettingsSwift // // Created by Dynamsoft on 2021/12/5. // Copyright © Dynamsoft. All rights reserved. // import UIKit class FormatsTableViewController: UITableViewController { let tableDataArr = ["OneD", "GS1 DataBar", "Postal Code", "PDF417", "QR Code", "DataMatrix", "AZTEC", "MaxiCode", "Micro QR", "Micro PDF417", "GS1 Composite", "Patch Code", "Dot Code", "Pharma Code"] var format_pdf417CkBox:UIButton! var format_qrcodeCkBox:UIButton! var format_datamatrixCkBox:UIButton! var format_aztecCkBox:UIButton! var format_maxicodeCkBox:UIButton! var format_microqrCkBox:UIButton! var format_micropdf417CkBox:UIButton! var format_gs1compositeCkBox:UIButton! var format_patchcodeCkBox:UIButton! var format_dotcodeCkBox:UIButton! var format_pharmaCodeCkBox:UIButton! override func viewDidLoad() { super.viewDidLoad() self.tableView!.register(UINib(nibName:"SettingTableViewCell", bundle:nil),forCellReuseIdentifier:"settingCell") self.tableView!.tableFooterView = UIView(frame: CGRect.zero) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return self.tableDataArr.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "settingCell") as! SettingTableViewCell for subview in cell.contentView.subviews { subview.removeFromSuperview() } cell.frame = CGRect(x: cell.frame.origin.x, y: cell.frame.origin.y, width: tableView.bounds.width, height: cell.frame.height) cell.contentView.frame = cell.bounds cell.selectionStyle = .none cell.accessoryType = .none cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byCharWrapping cell.textLabel?.font = UIFont.systemFont(ofSize: 14) cell.textLabel?.textColor = UIColor(red: 27.999/255.0, green: 27.999/255.0, blue: 27.999/255.0, alpha: 1) //ComplexSettingsTableViewController.TextColor cell.textLabel?.text = self.tableDataArr[indexPath.row] switch(indexPath.row) { case 0: cell.accessoryType = .disclosureIndicator case 1: cell.accessoryType = .disclosureIndicator case 2: cell.accessoryType = .disclosureIndicator case 3: self.setupBarcodeFormatPDF417(cell:cell) case 4: self.setupBarcodeFormatQRCODE(cell:cell) case 5: self.setupBarcodeFormatDATAMATRIX(cell:cell) case 6: self.setupBarcodeFormatAZTEC(cell:cell) case 7: self.setupBarcodeFormatMAXICODE(cell:cell) case 8: self.setupBarcodeFormatMICROQR(cell:cell) case 9: self.setupBarcodeFormatMICROPDF417(cell:cell) case 10: self.setupBarcodeFormatGS1COMPOSITE(cell:cell) case 11: self.setupBarcodeFormatPATCHCODE(cell:cell) case 12: self.setupBarcodeFormatDOTCODE(cell:cell) case 13: self.setupBarcodeFormatPharma(cell: cell) default: break } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch(indexPath.row) { case 0: self.pushONED() break case 1: self.pushGS1DataBar() break case 2: self.pushPostalCode() break case 3: self.format_pdf417CkBox.isSelected = !self.format_pdf417CkBox.isSelected if(self.format_pdf417CkBox.isSelected) { GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds | EnumBarcodeFormat.PDF417.rawValue } else { let temp = ~EnumBarcodeFormat.PDF417.rawValue GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds & temp } break; case 4: self.format_qrcodeCkBox.isSelected = !self.format_qrcodeCkBox.isSelected if(self.format_qrcodeCkBox.isSelected) { GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds | EnumBarcodeFormat.QRCODE.rawValue } else { let temp = ~EnumBarcodeFormat.QRCODE.rawValue GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds & temp } break; case 5: self.format_datamatrixCkBox.isSelected = !self.format_datamatrixCkBox.isSelected if(self.format_datamatrixCkBox.isSelected) { GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds | EnumBarcodeFormat.DATAMATRIX.rawValue } else { let temp = ~EnumBarcodeFormat.DATAMATRIX.rawValue GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds & temp } break case 6: self.format_aztecCkBox.isSelected = !self.format_aztecCkBox.isSelected if(self.format_aztecCkBox.isSelected) { GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds | EnumBarcodeFormat.AZTEC.rawValue } else { let temp = ~EnumBarcodeFormat.AZTEC.rawValue GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds & temp } break case 7: self.format_maxicodeCkBox.isSelected = !self.format_maxicodeCkBox.isSelected if(self.format_maxicodeCkBox.isSelected) { GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds | EnumBarcodeFormat.MAXICODE.rawValue } else { let temp = ~EnumBarcodeFormat.MAXICODE.rawValue GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds & temp } break case 8: self.format_microqrCkBox.isSelected = !self.format_microqrCkBox.isSelected if(self.format_microqrCkBox.isSelected) { GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds | EnumBarcodeFormat.MICROQR.rawValue } else { let temp = ~EnumBarcodeFormat.MICROQR.rawValue GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds & temp } break case 9: self.format_micropdf417CkBox.isSelected = !self.format_micropdf417CkBox.isSelected if(self.format_micropdf417CkBox.isSelected) { GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds | EnumBarcodeFormat.MICROPDF417.rawValue } else { let temp = ~EnumBarcodeFormat.MICROPDF417.rawValue GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds & temp } break case 10: self.format_gs1compositeCkBox.isSelected = !self.format_gs1compositeCkBox.isSelected if(self.format_gs1compositeCkBox.isSelected) { GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds | EnumBarcodeFormat.GS1COMPOSITE.rawValue } else { let temp = ~EnumBarcodeFormat.GS1COMPOSITE.rawValue GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds & temp } break case 11: self.format_patchcodeCkBox.isSelected = !self.format_patchcodeCkBox.isSelected if(self.format_patchcodeCkBox.isSelected) { GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds | EnumBarcodeFormat.PATCHCODE.rawValue } else { let temp = ~EnumBarcodeFormat.PATCHCODE.rawValue GeneralSettings.instance.runtimeSettings.barcodeFormatIds = GeneralSettings.instance.runtimeSettings.barcodeFormatIds & temp } break case 12: self.format_dotcodeCkBox.isSelected = !self.format_dotcodeCkBox.isSelected if(self.format_dotcodeCkBox.isSelected) { GeneralSettings.instance.runtimeSettings.barcodeFormatIds_2 = GeneralSettings.instance.runtimeSettings.barcodeFormatIds_2 | EnumBarcodeFormat2.DOTCODE.rawValue } else { let temp = ~EnumBarcodeFormat2.DOTCODE.rawValue GeneralSettings.instance.runtimeSettings.barcodeFormatIds_2 = GeneralSettings.instance.runtimeSettings.barcodeFormatIds_2 & temp } break case 13: self.format_pharmaCodeCkBox.isSelected = !self.format_pharmaCodeCkBox.isSelected if(self.format_pharmaCodeCkBox.isSelected) { GeneralSettings.instance.runtimeSettings.barcodeFormatIds_2 = GeneralSettings.instance.runtimeSettings.barcodeFormatIds_2 | EnumBarcodeFormat2.PHARMACODE.rawValue } else { let temp = ~EnumBarcodeFormat2.PHARMACODE.rawValue GeneralSettings.instance.runtimeSettings.barcodeFormatIds_2 = GeneralSettings.instance.runtimeSettings.barcodeFormatIds_2 & temp } break default : break } } func pushONED() { self.performSegue(withIdentifier: "ShowONEDSettings", sender: nil) } func pushGS1DataBar() { self.performSegue(withIdentifier: "ShowGS1DataBarSettings", sender: nil) } func pushPostalCode() { self.performSegue(withIdentifier: "ShowPostalCodeSettings", sender: nil) } func setupBarcodeFormatPDF417(cell:UITableViewCell) { let ckBox = SettingsCommon.getCheckBox(cell: cell, rightMargin: 20) ckBox.isSelected = (GeneralSettings.instance.runtimeSettings!.barcodeFormatIds | EnumBarcodeFormat.PDF417.rawValue) == GeneralSettings.instance.runtimeSettings!.barcodeFormatIds self.format_pdf417CkBox = ckBox } func setupBarcodeFormatQRCODE(cell:UITableViewCell) { let ckBox = SettingsCommon.getCheckBox(cell: cell, rightMargin: 20) ckBox.isSelected = (GeneralSettings.instance.runtimeSettings!.barcodeFormatIds | EnumBarcodeFormat.QRCODE.rawValue) == GeneralSettings.instance.runtimeSettings!.barcodeFormatIds self.format_qrcodeCkBox = ckBox } func setupBarcodeFormatDATAMATRIX(cell:UITableViewCell) { let ckBox = SettingsCommon.getCheckBox(cell: cell, rightMargin: 20) ckBox.isSelected = (GeneralSettings.instance.runtimeSettings!.barcodeFormatIds | EnumBarcodeFormat.DATAMATRIX.rawValue) == GeneralSettings.instance.runtimeSettings!.barcodeFormatIds self.format_datamatrixCkBox = ckBox } func setupBarcodeFormatAZTEC(cell:UITableViewCell) { let ckBox = SettingsCommon.getCheckBox(cell: cell, rightMargin: 20) ckBox.isSelected = (GeneralSettings.instance.runtimeSettings!.barcodeFormatIds | EnumBarcodeFormat.AZTEC.rawValue) == GeneralSettings.instance.runtimeSettings!.barcodeFormatIds self.format_aztecCkBox = ckBox } func setupBarcodeFormatMAXICODE(cell:UITableViewCell) { let ckBox = SettingsCommon.getCheckBox(cell: cell, rightMargin: 20) ckBox.isSelected = (GeneralSettings.instance.runtimeSettings!.barcodeFormatIds | EnumBarcodeFormat.MAXICODE.rawValue) == GeneralSettings.instance.runtimeSettings!.barcodeFormatIds self.format_maxicodeCkBox = ckBox } func setupBarcodeFormatMICROQR(cell:UITableViewCell) { let ckBox = SettingsCommon.getCheckBox(cell: cell, rightMargin: 20) ckBox.isSelected = (GeneralSettings.instance.runtimeSettings!.barcodeFormatIds | EnumBarcodeFormat.MICROQR.rawValue) == GeneralSettings.instance.runtimeSettings!.barcodeFormatIds self.format_microqrCkBox = ckBox } func setupBarcodeFormatMICROPDF417(cell:UITableViewCell) { let ckBox = SettingsCommon.getCheckBox(cell: cell, rightMargin: 20) ckBox.isSelected = (GeneralSettings.instance.runtimeSettings!.barcodeFormatIds | EnumBarcodeFormat.MICROPDF417.rawValue) == GeneralSettings.instance.runtimeSettings!.barcodeFormatIds self.format_micropdf417CkBox = ckBox } func setupBarcodeFormatGS1COMPOSITE(cell:UITableViewCell) { let ckBox = SettingsCommon.getCheckBox(cell: cell, rightMargin: 20) ckBox.isSelected = (GeneralSettings.instance.runtimeSettings!.barcodeFormatIds | EnumBarcodeFormat.GS1COMPOSITE.rawValue) == GeneralSettings.instance.runtimeSettings!.barcodeFormatIds self.format_gs1compositeCkBox = ckBox } func setupBarcodeFormatPATCHCODE(cell:UITableViewCell) { let ckBox = SettingsCommon.getCheckBox(cell: cell, rightMargin: 20) ckBox.isSelected = (GeneralSettings.instance.runtimeSettings!.barcodeFormatIds | EnumBarcodeFormat.PATCHCODE.rawValue) == GeneralSettings.instance.runtimeSettings!.barcodeFormatIds self.format_patchcodeCkBox = ckBox } func setupBarcodeFormatDOTCODE(cell:UITableViewCell) { let ckBox = SettingsCommon.getCheckBox(cell: cell, rightMargin: 20) ckBox.isSelected = (GeneralSettings.instance.runtimeSettings!.barcodeFormatIds_2 | EnumBarcodeFormat2.DOTCODE.rawValue) == GeneralSettings.instance.runtimeSettings!.barcodeFormatIds_2 self.format_dotcodeCkBox = ckBox } func setupBarcodeFormatPharma(cell:UITableViewCell) { let ckBox = SettingsCommon.getCheckBox(cell: cell, rightMargin: 20) ckBox.isSelected = (GeneralSettings.instance.runtimeSettings!.barcodeFormatIds_2 | EnumBarcodeFormat2.PHARMACODE.rawValue) == GeneralSettings.instance.runtimeSettings!.barcodeFormatIds_2 self.format_pharmaCodeCkBox = ckBox } }
46.014706
203
0.67651
f4c8134dc749b848d56c541119268d36a06df916
383
// // EmojiMemoryGame+ThemeEditor.swift // a2 // // Created by Lor Worwag on 12/9/20. // Copyright © 2020 Lor Worwag. All rights reserved. // import Foundation extension EmojiMemoryGame { // func renameTheme(to newName: String) { // self. // } // // func addEmoji(_ emoji: String) { // self.theme.content.append(emoji) // } }
15.32
53
0.579634
22604a59222159e2f6126c4c6743428a747a67c1
13,139
// // ZLMainCollectionViewController.swift // Zhixuan Lai // // Created by Zhixuan Lai on 4/25/15. // Copyright (c) 2015 Zhixuan Lai. All rights reserved. // import UIKit import SwiftyJSON import TTTAttributedLabel import ReactiveUI import SVWebViewController class ZLMainCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, TTTAttributedLabelDelegate { private var images = [String: UIImage]() private let cellIdentifier = "cell", headerIdentifier = "header", footerIdentifier = "footer" private var sectionHeaderAttributedStrings: [NSAttributedString]? var markdown = Markdown() var config: JSON? { didSet { if let sections = config?["sections"].array { let mds = sections.map({json in json["md"].stringValue}) if let styles = config?["style"].array?.map({json in json.stringValue}), open = config?["open"].string, close = config?["close"].string { let style = join("", styles) sectionHeaderAttributedStrings = mds.map({md in let outputHtml: String = style+open+self.markdown.transform(md)+close return NSAttributedString(data: outputHtml.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes: nil, error: nil)! }) } collectionView?.reloadData() } } } override init(collectionViewLayout layout: UICollectionViewLayout) { super.init(collectionViewLayout: layout) var imgPaths = (NSBundle.mainBundle().pathsForResourcesOfType("png", inDirectory: "") as! Array<String>) + (NSBundle.mainBundle().pathsForResourcesOfType("jpg", inDirectory: "") as! Array<String>) for path in imgPaths { if let image = UIImage(contentsOfFile: path) { let fileName = path.lastPathComponent.stringByDeletingPathExtension images[fileName] = image } } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { super.loadView() if let configPath = NSBundle.mainBundle().pathForResource("config", ofType: "json"), configData = NSData(contentsOfFile: configPath) { config = JSON(data: configData) } } override func viewDidLoad() { super.viewDidLoad() title = "Zhixuan" navigationController?.setNavigationBarHidden(true, animated: false) updateToolbarItems() collectionView?.backgroundColor = UIColor.whiteColor() collectionView?.registerClass(ZLCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: cellIdentifier) collectionView?.registerClass(ZLSectionHeaderView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier) collectionView?.registerClass(ZLCollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footerIdentifier) // let remoteJSONURL = "https://www.dropbox.com/s/fdr1sg8ubf7g9td/config.json?dl=1" // if let data = NSData(contentsOfURL: NSURL(string: remoteJSONURL)!) { // config = JSON(data: data) // println("updated") // } } override func viewDidAppear(animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: animated) navigationController?.setToolbarHidden(false, animated: animated) } override func viewWillDisappear(animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: animated) navigationController?.setToolbarHidden(true, animated: animated) } // MARK: Toolbar var homeBarButtonItem = UIBarButtonItem(image: UIImage(named: "home-toolbar")!, style: .Plain, action: {item in}) var gamesBarButtonItem = UIBarButtonItem(image: UIImage(named: "swords-toolbar")!, style: .Plain, action: {item in}) var appsBarButtonItem = UIBarButtonItem(image: UIImage(named: "ipod-touch")!, style: .Plain, action: {item in}) var codeBarButtonItem = UIBarButtonItem(image: UIImage(named: "github-toolbar")!, style: .Plain, action: {item in}) var researchBarButtonItem = UIBarButtonItem(image: UIImage(named: "graduation-cap-toolbar")!, style: .Plain, action: {item in}) var currentSectionTitle = "Welcome" override func scrollViewDidScroll(scrollView: UIScrollView) { if let indexPaths = collectionView?.indexPathsForVisibleItems() as? [NSIndexPath], let firstSection = indexPaths.first?.section, section = getSection(firstSection), title = section["title"].string { if currentSectionTitle != title { currentSectionTitle = title updateToolbarItems() } } } func updateToolbarItems() { homeBarButtonItem.addAction({item in self.scrollToSectionWithTitle("Welcome")}) gamesBarButtonItem.addAction({item in self.scrollToSectionWithTitle("Games")}) appsBarButtonItem.addAction({item in self.scrollToSectionWithTitle("Apps")}) codeBarButtonItem.addAction({item in self.scrollToSectionWithTitle("Code")}) researchBarButtonItem.addAction({item in self.scrollToSectionWithTitle("Research")}) homeBarButtonItem.tintColor = currentSectionTitle == "Welcome" || currentSectionTitle == "Projects" ? view.tintColor : UIColor.grayColor() gamesBarButtonItem.tintColor = currentSectionTitle == "Games" ? view.tintColor : UIColor.grayColor() appsBarButtonItem.tintColor = currentSectionTitle == "Apps" ? view.tintColor : UIColor.grayColor() codeBarButtonItem.tintColor = currentSectionTitle == "Code" ? view.tintColor : UIColor.grayColor() researchBarButtonItem.tintColor = currentSectionTitle == "Research" ? view.tintColor : UIColor.grayColor() var fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, action: {item in}) var flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, action: {item in}) var items = [fixedSpace, homeBarButtonItem, flexibleSpace, gamesBarButtonItem, flexibleSpace, appsBarButtonItem, flexibleSpace, codeBarButtonItem, flexibleSpace, researchBarButtonItem, fixedSpace] toolbarItems = items } func scrollToSectionWithTitle(toTitle: String) { if let sections = getSections() { for sectionIdx in (0..<sections.count) { let section = sections[sectionIdx] if let title = section["title"].string { if title == toTitle { var attributes = collectionView?.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: sectionIdx)) var rect = attributes?.frame let headerSize = headerSizeForSection(sectionIdx) collectionView?.setContentOffset(CGPoint(x: 0, y: rect!.origin.y-headerSize.height-30), animated: true) } } } } } // MARK: - UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { if let numSections = getSections()?.count { return numSections } return 0 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let numProjects = getSection(section)?["projects"].array?.count { return numProjects } return 0 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! ZLCollectionViewCell if let project = projectForIndexPath(indexPath), titleString = project["title"].string { cell.title = titleString if let darkTitle = project["darkTitle"].bool { cell.darkTitle = darkTitle } else { cell.darkTitle = false } } cell.image = imageForIndexPath(indexPath) cell.clipsToBounds = true return cell } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { switch (kind) { case UICollectionElementKindSectionHeader: var view = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier, forIndexPath: indexPath) as! ZLSectionHeaderView if let attributedString = attributedStringForSection(indexPath.section) { view.attributedText = attributedString } view.label.delegate = self return view case UICollectionElementKindSectionFooter: var view = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionFooter, withReuseIdentifier: footerIdentifier, forIndexPath: indexPath) as! ZLCollectionReusableView return view default: break } return ZLCollectionReusableView(frame: CGRectZero) } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var size = imageForIndexPath(indexPath).size return size } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return headerSizeForSection(section) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return CGSize(width: 100, height: 20) } func headerSizeForSection(section: Int) -> CGSize { if let attributedString = attributedStringForSection(section) { var size = TTTAttributedLabel.sizeThatFitsAttributedString(attributedString, withConstraints: ZLSectionHeaderView.labelMaxSize, limitedToNumberOfLines: 0) return size } return CGSizeZero } // MARK: - UICollectionViewDelegate var webViewControllers = [String: SVWebViewController]() override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { collectionView.deselectItemAtIndexPath(indexPath, animated: true) if let project = projectForIndexPath(indexPath), urlString = project["url"].string { var webViewController = SVWebViewController(address: urlString) webViewController.title = project["title"].string navigationController?.pushViewController(webViewController, animated: true) } } // MARK: - TTTAttributedLabelDelegate func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) { let alertController = UIAlertController(title: url.absoluteString, message: "Open Link in Safari", preferredStyle: .ActionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in} alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in UIApplication.sharedApplication().openURL(url)} alertController.addAction(OKAction) self.presentViewController(alertController, animated: true, completion: nil) } // MARK: - () func getSections() -> [JSON]? { if let sections = config?["sections"].array { return sections } return nil } func getSection(section:Int) -> JSON? { if let project = getSections()?[section] { return project } return nil } func imageForIndexPath(indexPath:NSIndexPath) -> UIImage { if let key = projectForIndexPath(indexPath)?["img"].string, img = images[key] { return img } return UIImage(named: "placeholder")! } func projectForIndexPath(indexPath:NSIndexPath) -> JSON? { if let project = config?["sections"].array?[indexPath.section]["projects"].array?[indexPath.item] { return project } return nil } func attributedStringForSection(section:Int) -> NSAttributedString? { if let s = sectionHeaderAttributedStrings?[section] { return s } return nil } }
47.09319
213
0.6741
61c4fc216d6e88d27572f58d8368806f0f4f894e
8,040
// // WalletsService.swift // Lumenshine // // Created by Soneso GmbH on 12/12/2018. // Munich, Germany // web: https://soneso.com // email: [email protected] // Copyright © 2018 Soneso. All rights reserved. // import UIKit import stellarsdk public enum GetWalletsEnum { case success(response: [WalletsResponse]) case failure(error: ServiceError) } public enum ChangeWalletDataEnum { case success case failure(error: ServiceError) } public enum AddWalletEnum { case success case failure(error: ServiceError) } public enum SetWalletHomescreenEnum { case success case failure(error: ServiceError) } public typealias GetWalletsClosure = (_ response: GetWalletsEnum) -> (Void) public typealias ChangeWalletDataClosure = (_ response: ChangeWalletDataEnum) -> (Void) public typealias AddWalletClosure = (_ response: AddWalletEnum) -> (Void) public typealias SetWalletHomescreenClosure = (_ response: SetWalletHomescreenEnum) -> (Void) public class WalletsService: BaseService { private var walletsToRefresh = [String]() private var accountDetailsCache = NSCache<NSString, AnyObject>() private var accountDetailsCachingDuration = 5.0 //sec. private var userWalletsCache = [WalletsResponse]() private class AcDetailsCacheEntry { let date:Date let accountResponse:AccountResponse init(date:Date, accountResponse:AccountResponse) { self.date = date self.accountResponse = accountResponse } } var stellarSDK: StellarSDK { get { return Services.shared.stellarSdk } } override init(baseURL: String) { super.init(baseURL: baseURL) } open func addWalletToRefresh(accountId: String) { if !walletsToRefresh.contains(accountId) { self.walletsToRefresh.append(accountId) } } open func isWalletNeedsRefresh(accountId: String) -> Bool { return self.walletsToRefresh.contains(accountId) } open func removeFromWalletsToRefresh(accountId: String) { self.walletsToRefresh.removeAll { $0 == accountId } } open func getWallets(reload:Bool, response: @escaping GetWalletsClosure) { if !reload , self.userWalletsCache.count > 0 { response(.success(response: self.userWalletsCache)) return } GETRequestWithPath(path: "/portal/user/dashboard/get_user_wallets") { (result) -> (Void) in switch result { case .success(let data): do { let userWalletsResponse = try self.jsonDecoder.decode(Array<WalletsResponse>.self, from: data) self.userWalletsCache = userWalletsResponse response(.success(response: userWalletsResponse)) } catch { response(.failure(error: .parsingFailed(message: error.localizedDescription))) } case .failure(let error): response(.failure(error: error)) } } } func changeWalletData(request: ChangeWalletRequest, response: @escaping ChangeWalletDataClosure) { POSTRequestWithPath(path: "/portal/user/dashboard/change_wallet_data", parameters: request.toDictionary()) { (result) -> (Void) in DispatchQueue.main.async { switch result { case .success(_): response(.success) case .failure(let error): response(.failure(error: error)) } } } } func removeFederationAddress(walletId: Int, response: @escaping ChangeWalletDataClosure) { let params = ["id": walletId] POSTRequestWithPath(path: "/portal/user/dashboard/remove_wallet_federation_address", parameters: params) { (result) -> (Void) in DispatchQueue.main.async { switch result { case .success(_): response(.success) case .failure(let error): response(.failure(error: error)) } } } } func addWallet(publicKey: String, name: String, federationAddress: String? = "", showOnHomescreen: Bool, completion: @escaping AddWalletClosure) { var params = Dictionary<String, Any>() params["public_key"] = publicKey params["wallet_name"] = name params["federation_address"] = federationAddress params["show_on_homescreen"] = showOnHomescreen POSTRequestWithPath(path: "/portal/user/dashboard/add_wallet", parameters: params) { (result) -> (Void) in DispatchQueue.main.async { switch result { case .success(_): completion(.success) case .failure(let error): completion(.failure(error: error)) } } } } func setWalletHomescreen(walletID: Int, isVisible: Bool, completion: @escaping SetWalletHomescreenClosure) { var params = Dictionary<String, Any>() params["id"] = walletID params["visible"] = isVisible POSTRequestWithPath(path: "/portal/user/dashboard/wallet_set_homescreen", parameters: params) { (result) -> (Void) in DispatchQueue.main.async { switch result { case .success(_): completion(.success) case .failure(let error): completion(.failure(error: error)) } } } } open func removeCachedAccountDetails(accountId:String){ accountDetailsCache.removeObject(forKey: accountId as NSString) } open func removeAllCachedAccountDetails(){ accountDetailsCache.removeAllObjects() } open func formatAmount(amount: String) -> String { let currencyFormatter = NumberFormatter() currencyFormatter.usesGroupingSeparator = true currencyFormatter.minimumFractionDigits = 2 currencyFormatter.maximumFractionDigits = 5 currencyFormatter.numberStyle = .decimal currencyFormatter.locale = Locale.current var value = "0.00" if let coinUnit = CoinUnit(amount) { let numberAmount = NSNumber(value:coinUnit) if let formattedValue = currencyFormatter.string(from: numberAmount) { value = formattedValue } } return value } //open func mergeAccount(sourceSeed: String, destinationPK: String, response open func getAccountDetails(accountId: String, ignoreCachingDuration:Bool = false, response: @escaping AccountResponseClosure) { if let cachedObject = accountDetailsCache.object(forKey: accountId as NSString) { if let entry = cachedObject as? AcDetailsCacheEntry { let validEntryDate = Date().addingTimeInterval(-1.0 * accountDetailsCachingDuration) if ignoreCachingDuration || validEntryDate <= entry.date { print("CACHE: account details FOUND for \(accountId)") response(.success(details:entry.accountResponse)) return } } } stellarSDK.accounts.getAccountDetails(accountId: accountId) { (accountResponse) -> (Void) in print("CACHE: account details loaded for \(accountId)") switch accountResponse { case .success(details: let accountDetails): let newEntry = AcDetailsCacheEntry(date:Date(), accountResponse:accountDetails) self.accountDetailsCache.setObject(newEntry, forKey: accountId as NSString) response(.success(details:accountDetails)) case .failure(let error): response(.failure(error:error)) } } } }
36.053812
150
0.607338
ede128332e494dc996084f4fc7f0e08ce9be9853
598
// // VignetteFilter.swift // ParseStarterProject // // Created by Chris Budro on 8/13/15. // Copyright (c) 2015 Parse. All rights reserved. // import UIKit class VignetteFilter: Filter { var intensity: Float = 1.0 var radius: Float = 10.0 override var parameters: [NSObject: AnyObject]? { return [kCIInputIntensityKey: intensity, kCIInputRadiusKey: radius] } init() { super.init(filterName: "CIBloom") } override func hasParameters() -> Bool { return true } override func setFilterWithMultiplier(multiplier: Float) { intensity = multiplier } }
19.933333
71
0.67893
766ad0451b9b38c1c11fdd42992ff6cf96abfc9b
602
// // FaviconURLFinder.swift // NetNewsWire // // Created by Brent Simmons on 11/20/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Foundation import RSParser // The favicon URLs may be specified in the head section of the home page. struct FaviconURLFinder { static func findFaviconURLs(_ homePageURL: String, _ callback: @escaping ([String]?) -> Void) { guard let _ = URL(string: homePageURL) else { callback(nil) return } HTMLMetadataDownloader.downloadMetadata(for: homePageURL) { (htmlMetadata) in callback(htmlMetadata?.faviconLinks) } } }
20.758621
96
0.72093
f97f4c5c1c73f8f142800ce0546f3ab71fdaa1ea
17,000
// // GXWaterfallViewLayout.swift // GXWaterfallViewLayoutSmaple // // Created by Gin on 2021/1/16. // import UIKit @objc public protocol GXWaterfallViewLayoutDelegate: NSObjectProtocol { func size(layout: GXWaterfallViewLayout, indexPath: IndexPath, itemSize: CGFloat) -> CGFloat @objc optional func moveItem(at sourceIndexPath:IndexPath, toIndexPath:IndexPath) } public class GXWaterfallViewLayout: UICollectionViewLayout { public var numberOfColumns: Int = 3 public var lineSpacing: CGFloat = 0 public var interitemSpacing: CGFloat = 0 public var headerSize: CGFloat = 0 public var footerSize: CGFloat = 0 public var sectionInset: UIEdgeInsets = .zero public var scrollDirection: UICollectionView.ScrollDirection = .vertical public weak var delegate: GXWaterfallViewLayoutDelegate? public var shouldAnimations: Array<IndexPath> = [] private var cellLayoutInfo: Dictionary<IndexPath, UICollectionViewLayoutAttributes> = [:] private var headLayoutInfo: Dictionary<IndexPath, UICollectionViewLayoutAttributes> = [:] private var footLayoutInfo: Dictionary<IndexPath, UICollectionViewLayoutAttributes> = [:] private var maxScrollDirPositionForColumn: Dictionary<Int, CGFloat> = [:] private var startScrollDirPosition: CGFloat = 0 } public extension GXWaterfallViewLayout { override func prepare() { super.prepare() self.cellLayoutInfo.removeAll() self.headLayoutInfo.removeAll() self.footLayoutInfo.removeAll() self.maxScrollDirPositionForColumn.removeAll() switch self.scrollDirection { case .vertical: self.prepareLayoutAtScrollDirectionVertical() case .horizontal: self.prepareLayoutAtScrollDirectionHorizontal() @unknown default: fatalError("unknown scrollDirection.") } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var allAttributes: Array<UICollectionViewLayoutAttributes> = Array() for attributes in self.cellLayoutInfo.values { if rect.intersects(attributes.frame) { allAttributes.append(attributes) } } for attributes in self.headLayoutInfo.values { if rect.intersects(attributes.frame) { allAttributes.append(attributes) } } for attributes in self.footLayoutInfo.values { if rect.intersects(attributes.frame) { allAttributes.append(attributes) } } return allAttributes } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return self.cellLayoutInfo[indexPath] } override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if elementKind == UICollectionView.elementKindSectionHeader { return self.headLayoutInfo[indexPath] } else if elementKind == UICollectionView.elementKindSectionFooter { return self.footLayoutInfo[indexPath] } return nil } override var collectionViewContentSize: CGSize { guard self.collectionView != nil else { return .zero } let width = self.collectionView!.frame.width - self.collectionView!.contentInset.left - self.collectionView!.contentInset.right let height = self.collectionView!.frame.height - self.collectionView!.contentInset.top - self.collectionView!.contentInset.bottom switch self.scrollDirection { case .vertical: return CGSize(width: width, height: max(self.startScrollDirPosition, height)) case .horizontal: return CGSize(width: max(self.startScrollDirPosition, width), height: height) @unknown default: fatalError("unknown scrollDirection.") } } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { guard self.collectionView != nil else { return false } if self.collectionView!.bounds.size.equalTo(newBounds.size) { return true } return false } // 这部分updateAction的代码可作为参考,可以继承重写来做效果 override func finalizeCollectionViewUpdates() { self.shouldAnimations.removeAll() } override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) { super.prepare(forCollectionViewUpdates: updateItems) var indexPaths: Array<IndexPath> = [] for item in updateItems { switch item.updateAction { case .insert: if item.indexPathAfterUpdate != nil { indexPaths.append(item.indexPathAfterUpdate!) } case .delete: if item.indexPathBeforeUpdate != nil { indexPaths.append(item.indexPathBeforeUpdate!) } case .move, .reload: if item.indexPathBeforeUpdate != nil { indexPaths.append(item.indexPathBeforeUpdate!) } if item.indexPathAfterUpdate != nil { indexPaths.append(item.indexPathAfterUpdate!) } default: break } } self.shouldAnimations.append(contentsOf: indexPaths) } // 对应UICollectionViewUpdateItem 的indexPathBeforeUpdate 设置调用 override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let attributes = super.initialLayoutAttributesForAppearingItem(at: itemIndexPath) guard attributes != nil else { return nil } if self.shouldAnimations.contains(itemIndexPath) { attributes?.center = CGPoint(x: self.collectionView!.bounds.midX, y: self.collectionView!.bounds.midY) attributes?.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) attributes?.alpha = 0.1 self.shouldAnimations.removeAll { (indexPath) -> Bool in return itemIndexPath == indexPath } } return attributes } // 对应UICollectionViewUpdateItem 的indexPathAfterUpdate 设置调用 override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let attributes = super.initialLayoutAttributesForAppearingItem(at: itemIndexPath) guard attributes != nil else { return nil } if self.shouldAnimations.contains(itemIndexPath) { attributes?.center = CGPoint(x: self.collectionView!.bounds.midX, y: self.collectionView!.bounds.midY) attributes?.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) attributes?.alpha = 0.1 self.shouldAnimations.removeAll { (indexPath) -> Bool in return itemIndexPath == indexPath } } return attributes } override func invalidationContext(forInteractivelyMovingItems targetIndexPaths: [IndexPath], withTargetPosition targetPosition: CGPoint, previousIndexPaths: [IndexPath], previousPosition: CGPoint) -> UICollectionViewLayoutInvalidationContext { let context = super.invalidationContext(forInteractivelyMovingItems: targetIndexPaths, withTargetPosition: targetPosition, previousIndexPaths: previousIndexPaths, previousPosition: previousPosition) if self.delegate != nil { if self.delegate!.responds(to: #selector(self.delegate!.moveItem(at:toIndexPath:))) { self.delegate?.moveItem?(at: previousIndexPaths.first!, toIndexPath: targetIndexPaths.first!) } } return context } } fileprivate extension GXWaterfallViewLayout { func prepareLayoutAtScrollDirectionVertical() { guard self.collectionView?.dataSource != nil else { return } // CollectionView content width let contentWidth: CGFloat = self.collectionView!.frame.width - self.collectionView!.contentInset.left - self.collectionView!.contentInset.right // Section content width let sectionContentWidth: CGFloat = contentWidth - self.sectionInset.left - self.sectionInset.right // cell width let itemWidth: CGFloat = floor((sectionContentWidth - self.interitemSpacing*CGFloat(self.numberOfColumns - 1))/CGFloat(self.numberOfColumns)) // Start point y self.startScrollDirPosition = 0.0 // Section attributes let sectionCount: Int = self.collectionView!.numberOfSections let respondsSupplementary: Bool = self.collectionView!.responds(to: #selector(self.collectionView!.supplementaryView(forElementKind:at:))) for section in 0..<sectionCount { // Haders layout if self.headerSize > 0 && respondsSupplementary { let indexPath = IndexPath(row: 0, section: section) let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, with: indexPath) attributes.frame = CGRect(x: 0, y: self.startScrollDirPosition, width: contentWidth, height: self.headerSize) self.headLayoutInfo[indexPath] = attributes self.startScrollDirPosition += self.headerSize + self.sectionInset.top } else { self.startScrollDirPosition += self.sectionInset.top } // Set first section cells point y for row in 0..<self.numberOfColumns { self.maxScrollDirPositionForColumn[row] = self.startScrollDirPosition } // Cells layout let rowCount: Int = self.collectionView!.numberOfItems(inSection: section) for row in 0..<rowCount { let indexPath = IndexPath(row: row, section: section) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) // 计算出当前的cell加到哪一列(瀑布流是加载到最短的一列) var top: CGFloat = self.maxScrollDirPositionForColumn[0]! var currentRow: Int = 0 for i in 1..<self.numberOfColumns { let iTop: CGFloat = self.maxScrollDirPositionForColumn[i]! if iTop < top { top = iTop; currentRow = i } } let left = self.sectionInset.left + (self.interitemSpacing + itemWidth) * CGFloat(currentRow) let itemHeight: CGFloat = self.delegate?.size(layout: self, indexPath: indexPath, itemSize: itemWidth) ?? 0 attributes.frame = CGRect(x: left, y: top, width: itemWidth, height: itemHeight) self.cellLayoutInfo[indexPath] = attributes // 重新设置当前列的Y值(也就是当前列cell到下个cell的值) top += self.lineSpacing + itemHeight self.maxScrollDirPositionForColumn[currentRow] = top //当是section的最后一个cell,取出最后一列cell的底部X值,设置startScrollDirPosition(最长X的列)决定下个视图对象的起始X值 if row == (rowCount - 1) { var maxTop: CGFloat = self.maxScrollDirPositionForColumn[0]! for i in 1..<self.numberOfColumns { let iTop: CGFloat = self.maxScrollDirPositionForColumn[i]! if iTop > maxTop { maxTop = iTop } } // 由于是cell到下个cell的Y值,所以如果没有下一个cell就需要减去cell间距 self.startScrollDirPosition = maxTop - self.lineSpacing + self.sectionInset.bottom } } // Footers layout if self.footerSize > 0 && respondsSupplementary { let indexPath = IndexPath(row: 0, section: section) let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, with: indexPath) attributes.frame = CGRect(x: 0, y: self.startScrollDirPosition, width: contentWidth, height: self.footerSize) self.footLayoutInfo[indexPath] = attributes self.startScrollDirPosition += self.footerSize } } } func prepareLayoutAtScrollDirectionHorizontal() { guard self.collectionView?.dataSource != nil else { return } // CollectionView content height let contentHeight: CGFloat = self.collectionView!.frame.height - self.collectionView!.contentInset.top - self.collectionView!.contentInset.bottom // Section content height let sectionContentHeight: CGFloat = contentHeight - self.sectionInset.top - self.sectionInset.bottom // cell height let itemHeight: CGFloat = floor((sectionContentHeight - self.lineSpacing*CGFloat(self.numberOfColumns - 1))/CGFloat(self.numberOfColumns)) // Start point x self.startScrollDirPosition = 0.0 // Section attributes let sectionCount: Int = self.collectionView!.numberOfSections let respondsSupplementary: Bool = self.collectionView!.responds(to: #selector(self.collectionView!.supplementaryView(forElementKind:at:))) for section in 0..<sectionCount { // Haders layout if self.headerSize > 0 && respondsSupplementary { let indexPath = IndexPath(row: 0, section: section) let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, with: indexPath) attributes.frame = CGRect(x: self.startScrollDirPosition, y: 0, width: self.headerSize, height: contentHeight) self.headLayoutInfo[indexPath] = attributes self.startScrollDirPosition += self.headerSize + self.sectionInset.left } else { self.startScrollDirPosition += self.sectionInset.left } // Set first section cells point x for row in 0..<self.numberOfColumns { self.maxScrollDirPositionForColumn[row] = self.startScrollDirPosition } // Cells layout let rowCount: Int = self.collectionView!.numberOfItems(inSection: section) for row in 0..<rowCount { let indexPath = IndexPath(row: row, section: section) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) // 计算出当前的cell加到哪一列(瀑布流是加载到最短的一列) var left: CGFloat = self.maxScrollDirPositionForColumn[0]! var currentRow: Int = 0 for i in 1..<self.numberOfColumns { let iLeft: CGFloat = self.maxScrollDirPositionForColumn[i]! if iLeft < left { left = iLeft; currentRow = i } } let top = self.sectionInset.top + (self.lineSpacing + itemHeight) * CGFloat(currentRow) let itemWidth: CGFloat = self.delegate?.size(layout: self, indexPath: indexPath, itemSize: itemHeight) ?? 0 attributes.frame = CGRect(x: left, y: top, width: itemWidth, height: itemHeight) self.cellLayoutInfo[indexPath] = attributes // 重新设置当前列的x值(也就是当前列cell到下个cell的值) left += self.interitemSpacing + itemWidth self.maxScrollDirPositionForColumn[currentRow] = left //当是section的最后一个cell,取出最后一列cell的底部X值,设置startScrollDirPosition(最长Y的列)决定下个视图对象的起始Y值 if row == (rowCount - 1) { var maxLeft: CGFloat = self.maxScrollDirPositionForColumn[0]! for i in 1..<self.numberOfColumns { let iLeft: CGFloat = self.maxScrollDirPositionForColumn[i]! if iLeft > maxLeft { maxLeft = iLeft } } // 由于是cell到下个cell的X值,所以如果没有下一个cell就需要减去cell间距 self.startScrollDirPosition = maxLeft - self.interitemSpacing + self.sectionInset.right } } // Footers layout if self.footerSize > 0 && respondsSupplementary { let indexPath = IndexPath(row: 0, section: section) let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, with: indexPath) attributes.frame = CGRect(x: self.startScrollDirPosition, y: 0, width: self.footerSize, height: contentHeight) self.footLayoutInfo[indexPath] = attributes self.startScrollDirPosition += self.footerSize } } } }
49.275362
247
0.635588
69eaef14b6d33fd636cf2091a054f8d122cbc266
326
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { { } var b = 1 class A { { { } } class a { { } class b { class A { protocol A { { } class A { } { } protocol A { func a { } { { } } typealias e : a
9.314286
87
0.631902
db95f2f6b137e2250c3782d09d568b55bfcc13de
41,968
// // Copyright (c) 2018 Google Inc. // // 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 MLKit import UIKit /// Main view controller class. @objc(ViewController) class ViewController: UIViewController, UINavigationControllerDelegate { /// A string holding current results from detection. var resultsText = "" /// An overlay view that displays detection annotations. private lazy var annotationOverlayView: UIView = { precondition(isViewLoaded) let annotationOverlayView = UIView(frame: .zero) annotationOverlayView.translatesAutoresizingMaskIntoConstraints = false annotationOverlayView.clipsToBounds = true return annotationOverlayView }() /// An image picker for accessing the photo library or camera. var imagePicker = UIImagePickerController() // Image counter. var currentImage = 0 /// Initialized when one of the pose detector rows are chosen. Reset to `nil` when neither are. private var poseDetector: PoseDetector? = nil /// Initialized when a segmentation row is chosen. Reset to `nil` otherwise. private var segmenter: Segmenter? = nil /// The detector row with which detection was most recently run. Useful for inferring when to /// reset detector instances which use a conventional lifecyle paradigm. private var lastDetectorRow: DetectorPickerRow? // MARK: - IBOutlets @IBOutlet fileprivate weak var detectorPicker: UIPickerView! @IBOutlet fileprivate weak var imageView: UIImageView! @IBOutlet fileprivate weak var photoCameraButton: UIBarButtonItem! @IBOutlet fileprivate weak var videoCameraButton: UIBarButtonItem! @IBOutlet weak var detectButton: UIBarButtonItem! // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() imageView.image = UIImage(named: Constants.images[currentImage]) imageView.addSubview(annotationOverlayView) NSLayoutConstraint.activate([ annotationOverlayView.topAnchor.constraint(equalTo: imageView.topAnchor), annotationOverlayView.leadingAnchor.constraint(equalTo: imageView.leadingAnchor), annotationOverlayView.trailingAnchor.constraint(equalTo: imageView.trailingAnchor), annotationOverlayView.bottomAnchor.constraint(equalTo: imageView.bottomAnchor), ]) imagePicker.delegate = self imagePicker.sourceType = .photoLibrary detectorPicker.delegate = self detectorPicker.dataSource = self let isCameraAvailable = UIImagePickerController.isCameraDeviceAvailable(.front) || UIImagePickerController.isCameraDeviceAvailable(.rear) if isCameraAvailable { // `CameraViewController` uses `AVCaptureDevice.DiscoverySession` which is only supported for // iOS 10 or newer. if #available(iOS 10.0, *) { videoCameraButton.isEnabled = true } } else { photoCameraButton.isEnabled = false } let defaultRow = (DetectorPickerRow.rowsCount / 2) - 1 detectorPicker.selectRow(defaultRow, inComponent: 0, animated: false) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.navigationBar.isHidden = false } // MARK: - IBActions @IBAction func detect(_ sender: Any) { clearResults() let row = detectorPicker.selectedRow(inComponent: 0) if let rowIndex = DetectorPickerRow(rawValue: row) { resetManagedLifecycleDetectors(activeDetectorRow: rowIndex) let shouldEnableClassification = (rowIndex == .detectObjectsProminentWithClassifier) || (rowIndex == .detectObjectsMultipleWithClassifier) || (rowIndex == .detectObjectsCustomProminentWithClassifier) || (rowIndex == .detectObjectsCustomMultipleWithClassifier) let shouldEnableMultipleObjects = (rowIndex == .detectObjectsMultipleWithClassifier) || (rowIndex == .detectObjectsMultipleNoClassifier) || (rowIndex == .detectObjectsCustomMultipleWithClassifier) || (rowIndex == .detectObjectsCustomMultipleNoClassifier) switch rowIndex { case .detectFaceOnDevice: detectFaces(image: imageView.image) case .detectTextOnDevice: detectTextOnDevice(image: imageView.image) case .detectBarcodeOnDevice: detectBarcodes(image: imageView.image) case .detectImageLabelsOnDevice: detectLabels(image: imageView.image, shouldUseCustomModel: false) case .detectImageLabelsCustomOnDevice: detectLabels(image: imageView.image, shouldUseCustomModel: true) case .detectObjectsProminentNoClassifier, .detectObjectsProminentWithClassifier, .detectObjectsMultipleNoClassifier, .detectObjectsMultipleWithClassifier: let options = ObjectDetectorOptions() options.shouldEnableClassification = shouldEnableClassification options.shouldEnableMultipleObjects = shouldEnableMultipleObjects options.detectorMode = .singleImage detectObjectsOnDevice(in: imageView.image, options: options) case .detectObjectsCustomProminentNoClassifier, .detectObjectsCustomProminentWithClassifier, .detectObjectsCustomMultipleNoClassifier, .detectObjectsCustomMultipleWithClassifier: guard let localModelFilePath = Bundle.main.path( forResource: Constants.localModelFile.name, ofType: Constants.localModelFile.type ) else { print("Failed to find custom local model file.") return } let localModel = LocalModel(path: localModelFilePath) let options = CustomObjectDetectorOptions(localModel: localModel) options.shouldEnableClassification = shouldEnableClassification options.shouldEnableMultipleObjects = shouldEnableMultipleObjects options.detectorMode = .singleImage detectObjectsOnDevice(in: imageView.image, options: options) case .detectPose, .detectPoseAccurate: detectPose(image: imageView.image) case .detectSegmentationMaskSelfie: detectSegmentationMask(image: imageView.image) } } else { print("No such item at row \(row) in detector picker.") } } @IBAction func openPhotoLibrary(_ sender: Any) { imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true) } @IBAction func openCamera(_ sender: Any) { guard UIImagePickerController.isCameraDeviceAvailable(.front) || UIImagePickerController .isCameraDeviceAvailable(.rear) else { return } imagePicker.sourceType = .camera present(imagePicker, animated: true) } @IBAction func changeImage(_ sender: Any) { clearResults() currentImage = (currentImage + 1) % Constants.images.count imageView.image = UIImage(named: Constants.images[currentImage]) } @IBAction func downloadOrDeleteModel(_ sender: Any) { clearResults() } // MARK: - Private /// Removes the detection annotations from the annotation overlay view. private func removeDetectionAnnotations() { for annotationView in annotationOverlayView.subviews { annotationView.removeFromSuperview() } } /// Clears the results text view and removes any frames that are visible. private func clearResults() { removeDetectionAnnotations() self.resultsText = "" } private func showResults() { let resultsAlertController = UIAlertController( title: "Detection Results", message: nil, preferredStyle: .actionSheet ) resultsAlertController.addAction( UIAlertAction(title: "OK", style: .destructive) { _ in resultsAlertController.dismiss(animated: true, completion: nil) } ) resultsAlertController.message = resultsText resultsAlertController.popoverPresentationController?.barButtonItem = detectButton resultsAlertController.popoverPresentationController?.sourceView = self.view present(resultsAlertController, animated: true, completion: nil) print(resultsText) } /// Updates the image view with a scaled version of the given image. private func updateImageView(with image: UIImage) { let orientation = UIApplication.shared.statusBarOrientation var scaledImageWidth: CGFloat = 0.0 var scaledImageHeight: CGFloat = 0.0 switch orientation { case .portrait, .portraitUpsideDown, .unknown: scaledImageWidth = imageView.bounds.size.width scaledImageHeight = image.size.height * scaledImageWidth / image.size.width case .landscapeLeft, .landscapeRight: scaledImageWidth = image.size.width * scaledImageHeight / image.size.height scaledImageHeight = imageView.bounds.size.height @unknown default: fatalError() } weak var weakSelf = self DispatchQueue.global(qos: .userInitiated).async { // Scale image while maintaining aspect ratio so it displays better in the UIImageView. var scaledImage = image.scaledImage( with: CGSize(width: scaledImageWidth, height: scaledImageHeight) ) scaledImage = scaledImage ?? image guard let finalImage = scaledImage else { return } DispatchQueue.main.async { weakSelf?.imageView.image = finalImage } } } private func transformMatrix() -> CGAffineTransform { guard let image = imageView.image else { return CGAffineTransform() } let imageViewWidth = imageView.frame.size.width let imageViewHeight = imageView.frame.size.height let imageWidth = image.size.width let imageHeight = image.size.height let imageViewAspectRatio = imageViewWidth / imageViewHeight let imageAspectRatio = imageWidth / imageHeight let scale = (imageViewAspectRatio > imageAspectRatio) ? imageViewHeight / imageHeight : imageViewWidth / imageWidth // Image view's `contentMode` is `scaleAspectFit`, which scales the image to fit the size of the // image view by maintaining the aspect ratio. Multiple by `scale` to get image's original size. let scaledImageWidth = imageWidth * scale let scaledImageHeight = imageHeight * scale let xValue = (imageViewWidth - scaledImageWidth) / CGFloat(2.0) let yValue = (imageViewHeight - scaledImageHeight) / CGFloat(2.0) var transform = CGAffineTransform.identity.translatedBy(x: xValue, y: yValue) transform = transform.scaledBy(x: scale, y: scale) return transform } private func pointFrom(_ visionPoint: VisionPoint) -> CGPoint { return CGPoint(x: visionPoint.x, y: visionPoint.y) } private func addContours(forFace face: Face, transform: CGAffineTransform) { // Face if let faceContour = face.contour(ofType: .face) { for point in faceContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } // Eyebrows if let topLeftEyebrowContour = face.contour(ofType: .leftEyebrowTop) { for point in topLeftEyebrowContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } if let bottomLeftEyebrowContour = face.contour(ofType: .leftEyebrowBottom) { for point in bottomLeftEyebrowContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } if let topRightEyebrowContour = face.contour(ofType: .rightEyebrowTop) { for point in topRightEyebrowContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } if let bottomRightEyebrowContour = face.contour(ofType: .rightEyebrowBottom) { for point in bottomRightEyebrowContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } // Eyes if let leftEyeContour = face.contour(ofType: .leftEye) { for point in leftEyeContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius) } } if let rightEyeContour = face.contour(ofType: .rightEye) { for point in rightEyeContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } // Lips if let topUpperLipContour = face.contour(ofType: .upperLipTop) { for point in topUpperLipContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } if let bottomUpperLipContour = face.contour(ofType: .upperLipBottom) { for point in bottomUpperLipContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } if let topLowerLipContour = face.contour(ofType: .lowerLipTop) { for point in topLowerLipContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } if let bottomLowerLipContour = face.contour(ofType: .lowerLipBottom) { for point in bottomLowerLipContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } // Nose if let noseBridgeContour = face.contour(ofType: .noseBridge) { for point in noseBridgeContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } if let noseBottomContour = face.contour(ofType: .noseBottom) { for point in noseBottomContour.points { let transformedPoint = pointFrom(point).applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.smallDotRadius ) } } } private func addLandmarks(forFace face: Face, transform: CGAffineTransform) { // Mouth if let bottomMouthLandmark = face.landmark(ofType: .mouthBottom) { let point = pointFrom(bottomMouthLandmark.position) let transformedPoint = point.applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.red, radius: Constants.largeDotRadius ) } if let leftMouthLandmark = face.landmark(ofType: .mouthLeft) { let point = pointFrom(leftMouthLandmark.position) let transformedPoint = point.applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.red, radius: Constants.largeDotRadius ) } if let rightMouthLandmark = face.landmark(ofType: .mouthRight) { let point = pointFrom(rightMouthLandmark.position) let transformedPoint = point.applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.red, radius: Constants.largeDotRadius ) } // Nose if let noseBaseLandmark = face.landmark(ofType: .noseBase) { let point = pointFrom(noseBaseLandmark.position) let transformedPoint = point.applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.yellow, radius: Constants.largeDotRadius ) } // Eyes if let leftEyeLandmark = face.landmark(ofType: .leftEye) { let point = pointFrom(leftEyeLandmark.position) let transformedPoint = point.applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.cyan, radius: Constants.largeDotRadius ) } if let rightEyeLandmark = face.landmark(ofType: .rightEye) { let point = pointFrom(rightEyeLandmark.position) let transformedPoint = point.applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.cyan, radius: Constants.largeDotRadius ) } // Ears if let leftEarLandmark = face.landmark(ofType: .leftEar) { let point = pointFrom(leftEarLandmark.position) let transformedPoint = point.applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.purple, radius: Constants.largeDotRadius ) } if let rightEarLandmark = face.landmark(ofType: .rightEar) { let point = pointFrom(rightEarLandmark.position) let transformedPoint = point.applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.purple, radius: Constants.largeDotRadius ) } // Cheeks if let leftCheekLandmark = face.landmark(ofType: .leftCheek) { let point = pointFrom(leftCheekLandmark.position) let transformedPoint = point.applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.orange, radius: Constants.largeDotRadius ) } if let rightCheekLandmark = face.landmark(ofType: .rightCheek) { let point = pointFrom(rightCheekLandmark.position) let transformedPoint = point.applying(transform) UIUtilities.addCircle( atPoint: transformedPoint, to: annotationOverlayView, color: UIColor.orange, radius: Constants.largeDotRadius ) } } private func process(_ visionImage: VisionImage, with textRecognizer: TextRecognizer?) { weak var weakSelf = self textRecognizer?.process(visionImage) { text, error in guard let strongSelf = weakSelf else { print("Self is nil!") return } guard error == nil, let text = text else { let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage strongSelf.resultsText = "Text recognizer failed with error: \(errorString)" strongSelf.showResults() return } // Blocks. for block in text.blocks { let transformedRect = block.frame.applying(strongSelf.transformMatrix()) UIUtilities.addRectangle( transformedRect, to: strongSelf.annotationOverlayView, color: UIColor.purple ) // Lines. for line in block.lines { let transformedRect = line.frame.applying(strongSelf.transformMatrix()) UIUtilities.addRectangle( transformedRect, to: strongSelf.annotationOverlayView, color: UIColor.orange ) // Elements. for element in line.elements { let transformedRect = element.frame.applying(strongSelf.transformMatrix()) UIUtilities.addRectangle( transformedRect, to: strongSelf.annotationOverlayView, color: UIColor.green ) let label = UILabel(frame: transformedRect) label.text = element.text label.adjustsFontSizeToFitWidth = true strongSelf.annotationOverlayView.addSubview(label) } } } strongSelf.resultsText += "\(text.text)\n" strongSelf.showResults() } } } extension ViewController: UIPickerViewDataSource, UIPickerViewDelegate { // MARK: - UIPickerViewDataSource func numberOfComponents(in pickerView: UIPickerView) -> Int { return DetectorPickerRow.componentsCount } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return DetectorPickerRow.rowsCount } // MARK: - UIPickerViewDelegate func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int ) -> String? { return DetectorPickerRow(rawValue: row)?.description } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { clearResults() } } // MARK: - UIImagePickerControllerDelegate extension ViewController: UIImagePickerControllerDelegate { func imagePickerController( _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] ) { // Local variable inserted by Swift 4.2 migrator. let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) clearResults() if let pickedImage = info[ convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage { updateImageView(with: pickedImage) } dismiss(animated: true) } } /// Extension of ViewController for On-Device detection. extension ViewController { // MARK: - Vision On-Device Detection /// Detects faces on the specified image and draws a frame around the detected faces using /// On-Device face API. /// /// - Parameter image: The image. func detectFaces(image: UIImage?) { guard let image = image else { return } // Create a face detector with options. // [START config_face] let options = FaceDetectorOptions() options.landmarkMode = .all options.classificationMode = .all options.performanceMode = .accurate options.contourMode = .all // [END config_face] // [START init_face] let faceDetector = FaceDetector.faceDetector(options: options) // [END init_face] // Initialize a `VisionImage` object with the given `UIImage`. let visionImage = VisionImage(image: image) visionImage.orientation = image.imageOrientation // [START detect_faces] weak var weakSelf = self faceDetector.process(visionImage) { faces, error in guard let strongSelf = weakSelf else { print("Self is nil!") return } guard error == nil, let faces = faces, !faces.isEmpty else { // [START_EXCLUDE] let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage strongSelf.resultsText = "On-Device face detection failed with error: \(errorString)" strongSelf.showResults() // [END_EXCLUDE] return } // Faces detected // [START_EXCLUDE] faces.forEach { face in let transform = strongSelf.transformMatrix() let transformedRect = face.frame.applying(transform) UIUtilities.addRectangle( transformedRect, to: strongSelf.annotationOverlayView, color: UIColor.green ) strongSelf.addLandmarks(forFace: face, transform: transform) strongSelf.addContours(forFace: face, transform: transform) } strongSelf.resultsText = faces.map { face in let headEulerAngleX = face.hasHeadEulerAngleX ? face.headEulerAngleX.description : "NA" let headEulerAngleY = face.hasHeadEulerAngleY ? face.headEulerAngleY.description : "NA" let headEulerAngleZ = face.hasHeadEulerAngleZ ? face.headEulerAngleZ.description : "NA" let leftEyeOpenProbability = face.hasLeftEyeOpenProbability ? face.leftEyeOpenProbability.description : "NA" let rightEyeOpenProbability = face.hasRightEyeOpenProbability ? face.rightEyeOpenProbability.description : "NA" let smilingProbability = face.hasSmilingProbability ? face.smilingProbability.description : "NA" let output = """ Frame: \(face.frame) Head Euler Angle X: \(headEulerAngleX) Head Euler Angle Y: \(headEulerAngleY) Head Euler Angle Z: \(headEulerAngleZ) Left Eye Open Probability: \(leftEyeOpenProbability) Right Eye Open Probability: \(rightEyeOpenProbability) Smiling Probability: \(smilingProbability) """ return "\(output)" }.joined(separator: "\n") strongSelf.showResults() // [END_EXCLUDE] } // [END detect_faces] } func detectSegmentationMask(image: UIImage?) { guard let image = image else { return } // Initialize a `VisionImage` object with the given `UIImage`. let visionImage = VisionImage(image: image) visionImage.orientation = image.imageOrientation guard let segmenter = self.segmenter else { return } weak var weakSelf = self segmenter.process(visionImage) { mask, error in guard let strongSelf = weakSelf else { print("Self is nil!") return } guard error == nil, let mask = mask else { let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage strongSelf.resultsText = "Segmentation failed with error: \(errorString)" strongSelf.showResults() return } guard let imageBuffer = UIUtilities.createImageBuffer(from: image) else { let errorString = "Failed to create image buffer from UIImage" strongSelf.resultsText = "Segmentation failed with error: \(errorString)" strongSelf.showResults() return } UIUtilities.applySegmentationMask( mask: mask, to: imageBuffer, backgroundColor: UIColor.purple.withAlphaComponent(Constants.segmentationMaskAlpha), foregroundColor: nil) let maskedImage = UIUtilities.createUIImage(from: imageBuffer, orientation: .up) let imageView = UIImageView() imageView.frame = strongSelf.annotationOverlayView.bounds imageView.contentMode = .scaleAspectFit imageView.image = maskedImage strongSelf.annotationOverlayView.addSubview(imageView) strongSelf.resultsText = "Segmentation succeeded" strongSelf.showResults() } } /// Detects poses on the specified image and draw pose landmark points and line segments using /// the On-Device face API. /// /// - Parameter image: The image. func detectPose(image: UIImage?) { guard let image = image else { return } // Initialize a `VisionImage` object with the given `UIImage`. let visionImage = VisionImage(image: image) visionImage.orientation = image.imageOrientation if let poseDetector = self.poseDetector { poseDetector.process(visionImage) { poses, error in guard error == nil, let poses = poses, !poses.isEmpty else { let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage self.resultsText = "Pose detection failed with error: \(errorString)" self.showResults() return } let transform = self.transformMatrix() // Pose detected. Currently, only single person detection is supported. poses.forEach { pose in let poseOverlayView = UIUtilities.createPoseOverlayView( forPose: pose, inViewWithBounds: self.annotationOverlayView.bounds, lineWidth: Constants.lineWidth, dotRadius: Constants.smallDotRadius, positionTransformationClosure: { (position) -> CGPoint in return self.pointFrom(position).applying(transform) } ) self.annotationOverlayView.addSubview(poseOverlayView) self.resultsText = "Pose Detected" self.showResults() } } } } /// Detects barcodes on the specified image and draws a frame around the detected barcodes using /// On-Device barcode API. /// /// - Parameter image: The image. func detectBarcodes(image: UIImage?) { guard let image = image else { return } // Define the options for a barcode detector. // [START config_barcode] let format = BarcodeFormat.all let barcodeOptions = BarcodeScannerOptions(formats: format) // [END config_barcode] // Create a barcode scanner. // [START init_barcode] let barcodeScanner = BarcodeScanner.barcodeScanner(options: barcodeOptions) // [END init_barcode] // Initialize a `VisionImage` object with the given `UIImage`. let visionImage = VisionImage(image: image) visionImage.orientation = image.imageOrientation // [START detect_barcodes] weak var weakSelf = self barcodeScanner.process(visionImage) { features, error in guard let strongSelf = weakSelf else { print("Self is nil!") return } guard error == nil, let features = features, !features.isEmpty else { // [START_EXCLUDE] let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage strongSelf.resultsText = "On-Device barcode detection failed with error: \(errorString)" strongSelf.showResults() // [END_EXCLUDE] return } // [START_EXCLUDE] features.forEach { feature in let transformedRect = feature.frame.applying(strongSelf.transformMatrix()) UIUtilities.addRectangle( transformedRect, to: strongSelf.annotationOverlayView, color: UIColor.green ) } strongSelf.resultsText = features.map { feature in return "DisplayValue: \(feature.displayValue ?? ""), RawValue: " + "\(feature.rawValue ?? ""), Frame: \(feature.frame)" }.joined(separator: "\n") strongSelf.showResults() // [END_EXCLUDE] } // [END detect_barcodes] } /// Detects labels on the specified image using On-Device label API. /// /// - Parameter image: The image. /// - Parameter shouldUseCustomModel: Whether to use the custom image labeling model. func detectLabels(image: UIImage?, shouldUseCustomModel: Bool) { guard let image = image else { return } // [START config_label] var options: CommonImageLabelerOptions! if shouldUseCustomModel { guard let localModelFilePath = Bundle.main.path( forResource: Constants.localModelFile.name, ofType: Constants.localModelFile.type ) else { self.resultsText = "On-Device label detection failed because custom model was not found." self.showResults() return } let localModel = LocalModel(path: localModelFilePath) options = CustomImageLabelerOptions(localModel: localModel) } else { options = ImageLabelerOptions() } options.confidenceThreshold = NSNumber(floatLiteral: Constants.labelConfidenceThreshold) // [END config_label] // [START init_label] let onDeviceLabeler = ImageLabeler.imageLabeler(options: options) // [END init_label] // Initialize a `VisionImage` object with the given `UIImage`. let visionImage = VisionImage(image: image) visionImage.orientation = image.imageOrientation // [START detect_label] weak var weakSelf = self onDeviceLabeler.process(visionImage) { labels, error in guard let strongSelf = weakSelf else { print("Self is nil!") return } guard error == nil, let labels = labels, !labels.isEmpty else { // [START_EXCLUDE] let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage strongSelf.resultsText = "On-Device label detection failed with error: \(errorString)" strongSelf.showResults() // [END_EXCLUDE] return } // [START_EXCLUDE] strongSelf.resultsText = labels.map { label -> String in return "Label: \(label.text), Confidence: \(label.confidence), Index: \(label.index)" }.joined(separator: "\n") strongSelf.showResults() // [END_EXCLUDE] } // [END detect_label] } /// Detects text on the specified image and draws a frame around the recognized text using the /// On-Device text recognizer. /// /// - Parameter image: The image. func detectTextOnDevice(image: UIImage?) { guard let image = image else { return } // [START init_text] let onDeviceTextRecognizer = TextRecognizer.textRecognizer() // [END init_text] // Initialize a `VisionImage` object with the given `UIImage`. let visionImage = VisionImage(image: image) visionImage.orientation = image.imageOrientation self.resultsText += "Running On-Device Text Recognition...\n" process(visionImage, with: onDeviceTextRecognizer) } /// Detects objects on the specified image and draws a frame around them. /// /// - Parameter image: The image. /// - Parameter options: The options for object detector. private func detectObjectsOnDevice(in image: UIImage?, options: CommonObjectDetectorOptions) { guard let image = image else { return } // Initialize a `VisionImage` object with the given `UIImage`. let visionImage = VisionImage(image: image) visionImage.orientation = image.imageOrientation // [START init_object_detector] // Create an objects detector with options. let detector = ObjectDetector.objectDetector(options: options) // [END init_object_detector] // [START detect_object] weak var weakSelf = self detector.process(visionImage) { objects, error in guard let strongSelf = weakSelf else { print("Self is nil!") return } guard error == nil else { // [START_EXCLUDE] let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage strongSelf.resultsText = "Object detection failed with error: \(errorString)" strongSelf.showResults() // [END_EXCLUDE] return } guard let objects = objects, !objects.isEmpty else { // [START_EXCLUDE] strongSelf.resultsText = "On-Device object detector returned no results." strongSelf.showResults() // [END_EXCLUDE] return } objects.forEach { object in // [START_EXCLUDE] let transform = strongSelf.transformMatrix() let transformedRect = object.frame.applying(transform) UIUtilities.addRectangle( transformedRect, to: strongSelf.annotationOverlayView, color: .green ) // [END_EXCLUDE] } // [START_EXCLUDE] strongSelf.resultsText = objects.map { object in var description = "Frame: \(object.frame)\n" if let trackingID = object.trackingID { description += "Object ID: " + trackingID.stringValue + "\n" } description += object.labels.enumerated().map { (index, label) in "Label \(index): \(label.text), \(label.confidence), \(label.index)" }.joined(separator: "\n") return description }.joined(separator: "\n") strongSelf.showResults() // [END_EXCLUDE] } // [END detect_object] } /// Resets any detector instances which use a conventional lifecycle paradigm. This method should /// be invoked immediately prior to performing detection. This approach is advantageous to tearing /// down old detectors in the `UIPickerViewDelegate` method because that method isn't actually /// invoked in-sync with when the selected row changes and can result in tearing down the wrong /// detector in the event of a race condition. private func resetManagedLifecycleDetectors(activeDetectorRow: DetectorPickerRow) { if activeDetectorRow == self.lastDetectorRow { // Same row as before, no need to reset any detectors. return } // Clear the old detector, if applicable. switch self.lastDetectorRow { case .detectPose, .detectPoseAccurate: self.poseDetector = nil break case .detectSegmentationMaskSelfie: self.segmenter = nil break default: break } // Initialize the new detector, if applicable. switch activeDetectorRow { case .detectPose, .detectPoseAccurate: let options = activeDetectorRow == .detectPose ? PoseDetectorOptions() : AccuratePoseDetectorOptions() options.detectorMode = .singleImage self.poseDetector = PoseDetector.poseDetector(options: options) break case .detectSegmentationMaskSelfie: let options = SelfieSegmenterOptions() options.segmenterMode = .singleImage self.segmenter = Segmenter.segmenter(options: options) break default: break } self.lastDetectorRow = activeDetectorRow } } // MARK: - Enums private enum DetectorPickerRow: Int { case detectFaceOnDevice = 0 case detectTextOnDevice, detectBarcodeOnDevice, detectImageLabelsOnDevice, detectImageLabelsCustomOnDevice, detectObjectsProminentNoClassifier, detectObjectsProminentWithClassifier, detectObjectsMultipleNoClassifier, detectObjectsMultipleWithClassifier, detectObjectsCustomProminentNoClassifier, detectObjectsCustomProminentWithClassifier, detectObjectsCustomMultipleNoClassifier, detectObjectsCustomMultipleWithClassifier, detectPose, detectPoseAccurate, detectSegmentationMaskSelfie static let rowsCount = 16 static let componentsCount = 1 public var description: String { switch self { case .detectFaceOnDevice: return "Face Detection" case .detectTextOnDevice: return "Text Recognition" case .detectBarcodeOnDevice: return "Barcode Scanning" case .detectImageLabelsOnDevice: return "Image Labeling" case .detectImageLabelsCustomOnDevice: return "Image Labeling Custom" case .detectObjectsProminentNoClassifier: return "ODT, single, no labeling" case .detectObjectsProminentWithClassifier: return "ODT, single, labeling" case .detectObjectsMultipleNoClassifier: return "ODT, multiple, no labeling" case .detectObjectsMultipleWithClassifier: return "ODT, multiple, labeling" case .detectObjectsCustomProminentNoClassifier: return "ODT, custom, single, no labeling" case .detectObjectsCustomProminentWithClassifier: return "ODT, custom, single, labeling" case .detectObjectsCustomMultipleNoClassifier: return "ODT, custom, multiple, no labeling" case .detectObjectsCustomMultipleWithClassifier: return "ODT, custom, multiple, labeling" case .detectPose: return "Pose Detection" case .detectPoseAccurate: return "Pose Detection, accurate" case .detectSegmentationMaskSelfie: return "Selfie Segmentation" } } } private enum Constants { static let images = [ "grace_hopper.jpg", "barcode_128.png", "qr_code.jpg", "beach.jpg", "image_has_text.jpg", "liberty.jpg", "bird.jpg", ] static let detectionNoResultsMessage = "No results returned." static let failedToDetectObjectsMessage = "Failed to detect objects in image." static let localModelFile = (name: "bird", type: "tflite") static let labelConfidenceThreshold = 0.75 static let smallDotRadius: CGFloat = 5.0 static let largeDotRadius: CGFloat = 10.0 static let lineColor = UIColor.yellow.cgColor static let lineWidth: CGFloat = 3.0 static let fillColor = UIColor.clear.cgColor static let segmentationMaskAlpha: CGFloat = 0.5 } // Helper function inserted by Swift 4.2 migrator. private func convertFromUIImagePickerControllerInfoKeyDictionary( _ input: [UIImagePickerController.InfoKey: Any] ) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (key.rawValue, value) }) } // Helper function inserted by Swift 4.2 migrator. private func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue }
35.566102
100
0.686404
75f2691f8de7aafdc0414f7e35123764480d8ab5
1,338
// // This source file is part of the Apodini Xpense Example // // SPDX-FileCopyrightText: 2018-2021 Paul Schmiedmayer and project authors (see CONTRIBUTORS.md) <[email protected]> // // SPDX-License-Identifier: MIT // import SwiftUI import XpenseModel // MARK: - LoginTextFields /// The view that displays the `TextField` for the login screen struct LoginTextFields: View { /// The `LoginViewModel` that manages the content of the login screen @ObservedObject var viewModel: LoginViewModel var body: some View { VStack(spacing: 0) { TextField("Username", text: $viewModel.username) .textFieldStyle(LoginTextFieldStyle()) Spacer() .frame(height: 8) SecureField("Password", text: $viewModel.password) .textFieldStyle(LoginTextFieldStyle()) if viewModel.state == .signUp { Spacer() .frame(height: 8) SecureField("Repeat Password", text: $viewModel.passwordAgain) .textFieldStyle(LoginTextFieldStyle()) } } } } // MARK: - LoginTextFields Previews struct LoginTextFields_Previews: PreviewProvider { static var previews: some View { LoginTextFields(viewModel: LoginViewModel(MockModel())) } }
29.733333
123
0.630792
01e0cba926029888d4cda73c03813410c9ac021e
465
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class A<T where g: A : (n: b, AnyObject) { public var c, let h : N
42.272727
79
0.733333
e8dffaa8e38a21d95b78c56e0834c10247633b8b
7,865
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// @_implementationOnly import _RegexParser @_spi(RegexBuilder) import _StringProcessing @available(SwiftStdlib 5.7, *) extension Regex { public init<Content: RegexComponent>( @RegexComponentBuilder _ content: () -> Content ) where Content.RegexOutput == Output { self = content().regex } } // A convenience protocol for builtin regex components that are initialized with // a `DSLTree` node. @available(SwiftStdlib 5.7, *) internal protocol _BuiltinRegexComponent: RegexComponent { init(_ regex: Regex<RegexOutput>) } @available(SwiftStdlib 5.7, *) extension _BuiltinRegexComponent { init(node: DSLTree.Node) { self.init(Regex(node: node)) } } // MARK: - Primitive regex components @available(SwiftStdlib 5.7, *) extension String: RegexComponent { public typealias Output = Substring public var regex: Regex<Output> { .init(node: .quotedLiteral(self)) } } @available(SwiftStdlib 5.7, *) extension Substring: RegexComponent { public typealias Output = Substring public var regex: Regex<Output> { .init(node: .quotedLiteral(String(self))) } } @available(SwiftStdlib 5.7, *) extension Character: RegexComponent { public typealias Output = Substring public var regex: Regex<Output> { .init(node: .atom(.char(self))) } } @available(SwiftStdlib 5.7, *) extension UnicodeScalar: RegexComponent { public typealias Output = Substring public var regex: Regex<Output> { .init(node: .atom(.scalar(self))) } } // MARK: - Combinators // MARK: Concatenation // Note: Concatenation overloads are currently gyb'd. // TODO: Variadic generics // struct Concatenation<W0, C0..., R0: RegexComponent, W1, C1..., R1: RegexComponent> // where R0.Match == (W0, C0...), R1.Match == (W1, C1...) // { // typealias Match = (Substring, C0..., C1...) // let regex: Regex<Output> // init(_ first: R0, _ second: R1) { // regex = .init(concat(r0, r1)) // } // } // MARK: Quantification // Note: Quantifiers are currently gyb'd. extension DSLTree.Node { // Individual public API functions are in the generated Variadics.swift file. /// Generates a DSL tree node for a repeated range of the given node. @available(SwiftStdlib 5.7, *) static func repeating( _ range: Range<Int>, _ behavior: RegexRepetitionBehavior?, _ node: DSLTree.Node ) -> DSLTree.Node { // TODO: Throw these as errors assert(range.lowerBound >= 0, "Cannot specify a negative lower bound") assert(!range.isEmpty, "Cannot specify an empty range") let kind: DSLTree.QuantificationKind = behavior.map { .explicit($0.dslTreeKind) } ?? .default switch (range.lowerBound, range.upperBound) { case (0, Int.max): // 0... return .quantification(.zeroOrMore, kind, node) case (1, Int.max): // 1... return .quantification(.oneOrMore, kind, node) case _ where range.count == 1: // ..<1 or ...0 or any range with count == 1 // Note: `behavior` is ignored in this case return .quantification(.exactly(range.lowerBound), .default, node) case (0, _): // 0..<n or 0...n or ..<n or ...n return .quantification(.upToN(range.upperBound), kind, node) case (_, Int.max): // n... return .quantification(.nOrMore(range.lowerBound), kind, node) default: // any other range return .quantification(.range(range.lowerBound, range.upperBound), kind, node) } } } /// A regex component that matches exactly one occurrence of its underlying /// component. @available(SwiftStdlib 5.7, *) public struct One<Output>: RegexComponent { public var regex: Regex<Output> public init<Component: RegexComponent>( _ component: Component ) where Component.RegexOutput == Output { self.regex = component.regex } } @available(SwiftStdlib 5.7, *) public struct OneOrMore<Output>: _BuiltinRegexComponent { public var regex: Regex<Output> internal init(_ regex: Regex<Output>) { self.regex = regex } // Note: Public initializers and operators are currently gyb'd. See // Variadics.swift. } @available(SwiftStdlib 5.7, *) public struct ZeroOrMore<Output>: _BuiltinRegexComponent { public var regex: Regex<Output> internal init(_ regex: Regex<Output>) { self.regex = regex } // Note: Public initializers and operators are currently gyb'd. See // Variadics.swift. } @available(SwiftStdlib 5.7, *) public struct Optionally<Output>: _BuiltinRegexComponent { public var regex: Regex<Output> internal init(_ regex: Regex<Output>) { self.regex = regex } // Note: Public initializers and operators are currently gyb'd. See // Variadics.swift. } @available(SwiftStdlib 5.7, *) public struct Repeat<Output>: _BuiltinRegexComponent { public var regex: Regex<Output> internal init(_ regex: Regex<Output>) { self.regex = regex } // Note: Public initializers and operators are currently gyb'd. See // Variadics.swift. } // MARK: Alternation // TODO: Variadic generics // @resultBuilder // struct AlternationBuilder { // @_disfavoredOverload // func buildBlock<R: RegexComponent>(_ regex: R) -> R // func buildBlock< // R: RegexComponent, W0, C0... // >( // _ regex: R // ) -> R where R.Match == (W, C...) // } @available(SwiftStdlib 5.7, *) @resultBuilder public struct AlternationBuilder { @_disfavoredOverload public static func buildPartialBlock<R: RegexComponent>( first component: R ) -> ChoiceOf<R.RegexOutput> { .init(component.regex) } public static func buildExpression<R: RegexComponent>(_ regex: R) -> R { regex } public static func buildEither<R: RegexComponent>(first component: R) -> R { component } public static func buildEither<R: RegexComponent>(second component: R) -> R { component } } @available(SwiftStdlib 5.7, *) public struct ChoiceOf<Output>: _BuiltinRegexComponent { public var regex: Regex<Output> internal init(_ regex: Regex<Output>) { self.regex = regex } public init(@AlternationBuilder _ builder: () -> Self) { self = builder() } } // MARK: - Capture @available(SwiftStdlib 5.7, *) public struct Capture<Output>: _BuiltinRegexComponent { public var regex: Regex<Output> internal init(_ regex: Regex<Output>) { self.regex = regex } // Note: Public initializers are currently gyb'd. See Variadics.swift. } @available(SwiftStdlib 5.7, *) public struct TryCapture<Output>: _BuiltinRegexComponent { public var regex: Regex<Output> internal init(_ regex: Regex<Output>) { self.regex = regex } // Note: Public initializers are currently gyb'd. See Variadics.swift. } // MARK: - Groups /// An atomic group. /// /// This group opens a local backtracking scope which, upon successful exit, /// discards any remaining backtracking points from within the scope. @available(SwiftStdlib 5.7, *) public struct Local<Output>: _BuiltinRegexComponent { public var regex: Regex<Output> internal init(_ regex: Regex<Output>) { self.regex = regex } } // MARK: - Backreference @available(SwiftStdlib 5.7, *) /// A backreference. public struct Reference<Capture>: RegexComponent { let id = ReferenceID() public init(_ captureType: Capture.Type = Capture.self) {} public var regex: Regex<Capture> { .init(node: .atom(.symbolicReference(id))) } } @available(SwiftStdlib 5.7, *) extension Regex.Match { public subscript<Capture>(_ reference: Reference<Capture>) -> Capture { self[reference.id] } }
26.216667
97
0.676033
39b356a231d8c720d748eed5d095b14948f0b2a0
7,837
// // CharacterDetailViewController.swift // iMarvel // // Created by Ricardo Casanova on 17/12/2018. // Copyright © 2018 Wallapop. All rights reserved. // import UIKit class CharacterDetailViewController: BaseViewController { public var presenter: CharacterDetailPresenterDelegate? private let characterInformationView: CharacterInformationView = CharacterInformationView() private let customTitleView: CustomTitleView = CustomTitleView() private let optionsBarView: OptionsBarView = OptionsBarView() private let spinner: UIActivityIndicatorView = UIActivityIndicatorView(style: .white) private let comicsContainerView: UIView = UIView() private var comicsTableView: UITableView? private var dataSource: ComicsDataSource? private var totalComics: Int = 0 private var isLoadingNextPage: Bool = false private var allComicsLoaded: Bool = false override func viewDidLoad() { super.viewDidLoad() setupViews() configureNavigationBar() presenter?.viewDidLoad() } } // MARK: - Setup views extension CharacterDetailViewController { /** * SetupViews */ private func setupViews() { view.backgroundColor = .black() edgesForExtendedLayout = [] configureSubviews() addSubviews() } /** * ConfigureSubviews */ private func configureSubviews() { optionsBarView.backgroundColor = .yellow optionsBarView.options = ["Comics", "Series", "Stories", "Events"] optionsBarView.delegate = self comicsTableView = UITableView(frame: comicsContainerView.bounds, style: .plain) comicsTableView?.tableFooterView = UIView() comicsTableView?.estimatedRowHeight = 193.0 comicsTableView?.rowHeight = UITableView.automaticDimension comicsTableView?.invalidateIntrinsicContentSize() comicsTableView?.allowsSelection = true comicsTableView?.backgroundColor = .black() comicsTableView?.delegate = self registerCells() setupDatasource() } private func configureNavigationBar() { customTitleView.titleColor = .white() customTitleView.setTitle("iMarvel") customTitleView.subtitleColor = .white() navigationItem.titleView = customTitleView } /** * Register all the cells we need */ private func registerCells() { comicsTableView?.register(ComicTableViewCell.self, forCellReuseIdentifier: ComicTableViewCell.identifier) } /** * Setup datasource for the movies table view */ private func setupDatasource() { if let comicsTableView = comicsTableView { dataSource = ComicsDataSource() comicsTableView.dataSource = dataSource } } } // MARK: - Layout & constraints extension CharacterDetailViewController { /** * Internal struct for layout */ private struct Layout { struct Scroll { static let percentagePosition: Double = 75.0 } } /** * Internal struct for animation */ private struct Animation { static let animationDuration: TimeInterval = 0.25 } /** * Add subviews */ private func addSubviews() { view.addSubview(characterInformationView) view.addSubview(optionsBarView) view.addSubview(comicsContainerView) view.addConstraintsWithFormat("H:|[v0]|", views: characterInformationView) view.addConstraintsWithFormat("V:|[v0(>=0.0)]", views: characterInformationView) view.addConstraintsWithFormat("H:|[v0]|", views: optionsBarView) view.addConstraintsWithFormat("V:[v0][v1(\(optionsBarView.height))]", views: characterInformationView, optionsBarView) view.addConstraintsWithFormat("H:|[v0]|", views: comicsContainerView) view.addConstraintsWithFormat("V:[v0][v1]|", views: optionsBarView, comicsContainerView) if let comicsTableView = comicsTableView { comicsContainerView.addSubview(comicsTableView) comicsContainerView.addConstraintsWithFormat("H:|[v0]|", views: comicsTableView) comicsContainerView.addConstraintsWithFormat("V:|[v0]|", views: comicsTableView) } } /** * Scroll to top */ private func scrollToTop() { comicsTableView?.setContentOffset(.zero, animated: false) } } extension CharacterDetailViewController: OptionsBarViewDelegate { func optionSelectedAt(_ index: Int) { switch index { case 0: presenter?.optionSelected(.comics) case 1: presenter?.optionSelected(.series) case 2: presenter?.optionSelected(.stories) case 3: presenter?.optionSelected(.events) default: print("do nothing") } } } // MARK: - UITableViewDelegate extension CharacterDetailViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let lastSectionIndex = tableView.numberOfSections - 1 let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1 if indexPath.section == lastSectionIndex && indexPath.row == lastRowIndex { spinner.startAnimating() spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: tableView.bounds.width, height: CGFloat(44)) comicsTableView?.tableFooterView = allComicsLoaded ? UIView() : spinner comicsTableView?.tableFooterView?.isHidden = allComicsLoaded } // Get the position for a percentage of the scrolling // In this case we got the positions for the 75% let position = Int(((Layout.Scroll.percentagePosition * Double(totalComics - 1)) / 100.0)) // if we're not loading a next page && we´re in the 75% position if !self.isLoadingNextPage && indexPath.item >= position { // Change the value -> We're loading the next page self.isLoadingNextPage = true optionsBarView.isUserInteractionEnabled = allComicsLoaded // Call the presenter presenter?.loadNextPage() } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { presenter?.comicSelectedAt(indexPath.row) } } extension CharacterDetailViewController: CharacterDetailViewInjection { func showProgress(_ show: Bool, status: String) { showLoader(show, status: status) } func showProgress(_ show: Bool) { showLoader(show) } func loadCharacter(_ characterDetail: CharactersListViewModel) { characterInformationView.bindWithViewModel(characterDetail) } func loadComics(_ viewModels: [ComicViewModel], copyright: String?, fromBeginning: Bool, allComicsLoaded: Bool) { self.allComicsLoaded = allComicsLoaded // Are we loading the characters from the beginning? -> scroll to top if fromBeginning { scrollToTop() } customTitleView.setSubtitle(copyright) optionsBarView.isUserInteractionEnabled = true isLoadingNextPage = false totalComics = viewModels.count dataSource?.comics = viewModels comicsTableView?.tableFooterView = UIView() comicsTableView?.reloadData() } func showMessageWith(title: String, message: String, actionTitle: String) { showAlertWith(title: title, message: message, actionTitle: actionTitle) } }
31.987755
126
0.647824
5055fe86c867127a65e0ff651861e0988239eb44
1,964
// // FutureExtension.swift // Reactive iOS // // Created by Amine Bensalah on 24/09/2019. // import Foundation extension Future { @discardableResult public func done(on: DispatchQueue = DispatchQueue.global(), _ onSuccess: @escaping SuccessCompletion) -> Future { return Future(operation: { resolver in self.execute(completion: { (result) in switch result { case .success(let value): on.async { onSuccess(value) } case .failure: break } resolver(result) }) }) } @discardableResult public func `catch`(on: DispatchQueue = DispatchQueue.global(), _ onFailure: @escaping FailureCompletion) -> Future { return Future(operation: { resolver in self.execute(completion: { (result) in switch result { case .success: break case .failure(let failure): on.async { onFailure(failure) } } resolver(result) }) }) } /** Chain two depending futures providing a function that gets the erro of this future as parameter and then creates new one - Parameters: - transform: function that will generate a new `Future` by passing the value of this Future - value: the value of this Future - Returns: New chained Future */ public func whenFailure<F: Error>(_ transform: @escaping (_ failure: E) -> Future<T,F>) -> Future<T,F> { return Future<T,F>(operation: { completion in self.execute(onSuccess: { value in completion(.success(value)) }, onFailure: { error in transform(error).execute(completion: completion) }) }) } }
29.757576
121
0.527495
18203549d52d6f34b5ade7721812ba5a6906182a
4,314
// // Line.swift // LineChart // // Created by András Samu on 2019. 08. 30.. // Copyright © 2019. András Samu. All rights reserved. // import SwiftUI public struct Line: View { @ObservedObject var data: ChartData @Binding var frame: CGRect @Binding var touchLocation: CGPoint @Binding var showIndicator: Bool @Binding var minDataValue: Double? @Binding var maxDataValue: Double? @State private var showFull: Bool = false @State var showBackground: Bool = true var gradient: GradientColor = GradientColor(start: Colors.GradientPurple, end: Colors.GradientNeonBlue) var index:Int = 0 let padding:CGFloat = 30 var curvedLines: Bool = false var stepWidth: CGFloat { if data.points.count < 2 { return 0 } return frame.size.width / CGFloat(data.points.count-1) } var stepHeight: CGFloat { var min: Double? var max: Double? let points = self.data.onlyPoints() if minDataValue != nil && maxDataValue != nil { min = minDataValue! max = maxDataValue! }else if let minPoint = points.min(), let maxPoint = points.max(), minPoint != maxPoint { min = minPoint max = maxPoint }else { return 0 } if let min = min, let max = max, min != max { if (min <= 0){ return (frame.size.height-padding) / CGFloat(max - min) }else{ return (frame.size.height-padding) / CGFloat(max - min) } } return 0 } var path: Path { let points = self.data.onlyPoints() return curvedLines ? Path.quadCurvedPathWithPoints(points: points, step: CGPoint(x: stepWidth, y: stepHeight), globalOffset: minDataValue) : Path.linePathWithPoints(points: points, step: CGPoint(x: stepWidth, y: stepHeight)) } var closedPath: Path { let points = self.data.onlyPoints() return curvedLines ? Path.quadClosedCurvedPathWithPoints(points: points, step: CGPoint(x: stepWidth, y: stepHeight), globalOffset: minDataValue) : Path.closedLinePathWithPoints(points: points, step: CGPoint(x: stepWidth, y: stepHeight)) } public var body: some View { ZStack { if(self.showFull && self.showBackground){ self.closedPath .fill(LinearGradient(gradient: Gradient(colors: [Colors.GradientUpperBlue, .white]), startPoint: .bottom, endPoint: .top)) .rotationEffect(.degrees(180), anchor: .center) .rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0)) .transition(.opacity) .animation(.easeIn(duration: 1.6)) } self.path .trim(from: 0, to: self.showFull ? 1:0) .stroke(LinearGradient(gradient: gradient.getGradient(), startPoint: .leading, endPoint: .trailing) ,style: StrokeStyle(lineWidth: 3, lineJoin: .round)) .rotationEffect(.degrees(180), anchor: .center) .rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0)) .animation(Animation.easeOut(duration: 1.2).delay(Double(self.index)*0.4)) .onAppear { self.showFull = true } .onDisappear { self.showFull = false } if(self.showIndicator) { IndicatorPoint() .position(self.getClosestPointOnPath(touchLocation: self.touchLocation)) .rotationEffect(.degrees(180), anchor: .center) .rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0)) } } } func getClosestPointOnPath(touchLocation: CGPoint) -> CGPoint { let closest = self.path.point(to: touchLocation.x) return closest } } struct Line_Previews: PreviewProvider { static var previews: some View { GeometryReader{ geometry in Line(data: ChartData(points: [12,-230,10,54]), frame: .constant(geometry.frame(in: .local)), touchLocation: .constant(CGPoint(x: 100, y: 12)), showIndicator: .constant(true), minDataValue: .constant(nil), maxDataValue: .constant(nil)) }.frame(width: 320, height: 160) } }
40.698113
246
0.589244
906723a1cd80b1673f4e784b4a386157a04fa3da
3,476
// Copyright 2017-present the Material Components for iOS 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 UIKit import MaterialComponents.MaterialButtons import MaterialComponentsBeta.MaterialButtons_Theming import MaterialComponentsBeta.MaterialContainerScheme class ButtonsDynamicTypeViewController: UIViewController { class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Buttons", "Buttons (DynamicType)"], "primaryDemo": false, "presentable": false, ] } var containerScheme = MDCContainerScheme() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.9, alpha:1.0) let titleColor = UIColor.white let backgroundColor = UIColor(white: 0.1, alpha: 1.0) let flatButtonStatic = MDCButton() flatButtonStatic.applyContainedTheme(withScheme: containerScheme) flatButtonStatic.setTitleColor(titleColor, for: .normal) flatButtonStatic.setBackgroundColor(backgroundColor, for: .normal) flatButtonStatic.setTitle("Static", for: UIControlState()) flatButtonStatic.sizeToFit() flatButtonStatic.translatesAutoresizingMaskIntoConstraints = false flatButtonStatic.addTarget(self, action: #selector(tap), for: .touchUpInside) view.addSubview(flatButtonStatic) let flatButtonDynamic = MDCButton() flatButtonDynamic.applyContainedTheme(withScheme: containerScheme) flatButtonDynamic.setTitleColor(titleColor, for: .normal) flatButtonDynamic.setBackgroundColor(backgroundColor, for: .normal) flatButtonDynamic.setTitle("Dynamic", for: UIControlState()) flatButtonDynamic.sizeToFit() flatButtonDynamic.translatesAutoresizingMaskIntoConstraints = false flatButtonDynamic.addTarget(self, action: #selector(tap), for: .touchUpInside) flatButtonDynamic.mdc_adjustsFontForContentSizeCategory = true view.addSubview(flatButtonDynamic) let views = [ "flatStatic": flatButtonStatic, "flatDynamic": flatButtonDynamic ] centerView(view: flatButtonDynamic, onView: self.view) view.addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "V:[flatStatic]-40-[flatDynamic]", options: .alignAllCenterX, metrics: nil, views: views)) } // MARK: Private func centerView(view: UIView, onView: UIView) { onView.addConstraint(NSLayoutConstraint( item: view, attribute: .centerX, relatedBy: .equal, toItem: onView, attribute: .centerX, multiplier: 1.0, constant: 0.0)) onView.addConstraint(NSLayoutConstraint( item: view, attribute: .centerY, relatedBy: .equal, toItem: onView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) } @objc func tap(_ sender: Any) { print("\(type(of: sender)) was tapped.") } }
34.078431
89
0.709436
fce852059555689c8adf05098aaeebc0a5189034
4,074
// File created from SimpleUserProfileExample // $ createScreen.sh Room/UserSuggestion UserSuggestion // // Copyright 2021 New Vector Ltd // // 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 XCTest import Combine @testable import RiotSwiftUI @available(iOS 14.0, *) class UserSuggestionServiceTests: XCTestCase { var service: UserSuggestionService? override func setUp() { service = UserSuggestionService(roomMemberProvider: self, shouldDebounce: false) } func testAlice() { service?.processTextMessage("@Al") assert(service?.items.value.first?.displayName == "Alice") service?.processTextMessage("@al") assert(service?.items.value.first?.displayName == "Alice") service?.processTextMessage("@ice") assert(service?.items.value.first?.displayName == "Alice") service?.processTextMessage("@Alice") assert(service?.items.value.first?.displayName == "Alice") service?.processTextMessage("@alice:matrix.org") assert(service?.items.value.first?.displayName == "Alice") } func testBob() { service?.processTextMessage("@ob") assert(service?.items.value.first?.displayName == "Bob") service?.processTextMessage("@ob:") assert(service?.items.value.first?.displayName == "Bob") service?.processTextMessage("@b:matrix") assert(service?.items.value.first?.displayName == "Bob") } func testBoth() { service?.processTextMessage("@:matrix") assert(service?.items.value.first?.displayName == "Alice") assert(service?.items.value.last?.displayName == "Bob") service?.processTextMessage("@.org") assert(service?.items.value.first?.displayName == "Alice") assert(service?.items.value.last?.displayName == "Bob") } func testEmptyResult() { service?.processTextMessage("Lorem ipsum idolor") assert(service?.items.value.count == 0) service?.processTextMessage("@") assert(service?.items.value.count == 0) service?.processTextMessage("@@") assert(service?.items.value.count == 0) service?.processTextMessage("[email protected]") assert(service?.items.value.count == 0) } func testStuff() { service?.processTextMessage("@@") assert(service?.items.value.count == 0) } func testWhitespaces() { service?.processTextMessage("") assert(service?.items.value.count == 0) service?.processTextMessage(" ") assert(service?.items.value.count == 0) service?.processTextMessage("\n") assert(service?.items.value.count == 0) service?.processTextMessage(" \n ") assert(service?.items.value.count == 0) service?.processTextMessage("@A ") assert(service?.items.value.count == 0) service?.processTextMessage(" @A ") assert(service?.items.value.count == 0) } } @available(iOS 14.0, *) extension UserSuggestionServiceTests: RoomMembersProviderProtocol { func fetchMembers(_ members: @escaping ([RoomMembersProviderMember]) -> Void) { let users = [("Alice", "@alice:matrix.org"), ("Bob", "@bob:matrix.org")] members(users.map({ user in RoomMembersProviderMember(userId: user.1, displayName: user.0, avatarUrl: "") })) } }
33.121951
89
0.622975
7a5cfd617f36728e0fb373604b5dd5387edef3d3
793
// Copyright (C) 2018 Andrew Lord // // 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 protocol Clock { func dateTimeNow() -> Date } class SystemClock { } // MARK: - Clock extension SystemClock: Clock { func dateTimeNow() -> Date { return Date() } }
26.433333
118
0.715006
64f5d822860a7afd2413770ea678f7accfc997bd
1,264
// // Tip_CalculatorUITests.swift // Tip CalculatorUITests // // Created by Raghav Nyati on 8/14/17. // Copyright © 2017 Raghav Nyati. All rights reserved. // import XCTest class Tip_CalculatorUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.162162
182
0.66693
751336eb465b44a2927d94828f50076c3f66bb3d
6,083
// // ViewController.swift // SimpleWebmPlayer // // Created by Alessandro Maroso on 25/02/2018. // Copyright © 2018 membersheep. All rights reserved. // import UIKit // TODO: Allow to open an url directly from a dialog // TODO: Show instructions in the background. Hide when a media is loaded. class ViewController: UIViewController, VLCMediaPlayerDelegate { let movieView = UIView() let leftLabel = UILabel() let rightLabel = UILabel() let progressSlider = UISlider() let mediaPlayer = VLCMediaPlayer() init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) self.movieView.frame = UIScreen.screens[0].bounds let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.movieViewTapped(_:))) self.movieView.addGestureRecognizer(tapGesture) self.view.addSubview(self.movieView) self.movieView.translatesAutoresizingMaskIntoConstraints = false self.movieView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true self.movieView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.movieView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true self.movieView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true self.progressSlider.tintColor = .white self.view.addSubview(self.progressSlider) self.progressSlider.translatesAutoresizingMaskIntoConstraints = false self.progressSlider.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true self.progressSlider.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true self.progressSlider.addTarget(self, action: #selector(ViewController.sliderTouchBegan), for: .touchDown) self.progressSlider.addTarget(self, action: #selector(ViewController.sliderMoved), for: .valueChanged) self.progressSlider.addTarget(self, action: #selector(ViewController.sliderTouchEnded), for: .touchUpInside) self.leftLabel.textColor = .white self.leftLabel.text = "00:00" self.view.addSubview(self.leftLabel) self.leftLabel.translatesAutoresizingMaskIntoConstraints = false self.leftLabel.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 16).isActive = true self.leftLabel.centerYAnchor.constraint(equalTo: self.progressSlider.centerYAnchor).isActive = true self.leftLabel.rightAnchor.constraint(equalTo: self.progressSlider.leftAnchor, constant: 16).isActive = true self.rightLabel.textColor = .white self.rightLabel.text = "00:00" self.view.addSubview(self.rightLabel) self.rightLabel.translatesAutoresizingMaskIntoConstraints = false self.rightLabel.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -16).isActive = true self.rightLabel.centerYAnchor.constraint(equalTo: self.progressSlider.centerYAnchor).isActive = true self.rightLabel.leftAnchor.constraint(equalTo: self.progressSlider.rightAnchor, constant: 16).isActive = true } func openFile(with url: URL) { let media = VLCMedia(url: url) self.mediaPlayer.media = media self.mediaPlayer.delegate = self self.mediaPlayer.drawable = self.movieView self.mediaPlayer.play() } func updateLabels(for time: Int32) { let minutes = time / 1000 / 60 let seconds = time / 1000 % 60 let totalMinutes = (self.mediaPlayer.time.intValue - self.mediaPlayer.remainingTime.intValue) / 1000 / 60 let totalSeconds = (self.mediaPlayer.time.intValue - self.mediaPlayer.remainingTime.intValue) / 1000 % 60 DispatchQueue.main.async { self.leftLabel.text = "\(String(format:"%02d", minutes)):\(String(format:"%02d", seconds))" self.rightLabel.text = "\(String(format:"%02d", totalMinutes)):\(String(format:"%02d", totalSeconds))" } } @objc func rotated() { let orientation = UIDevice.current.orientation if (UIDeviceOrientationIsLandscape(orientation)) { print("Switched to landscape") } else if(UIDeviceOrientationIsPortrait(orientation)) { print("Switched to portrait") } } func mediaPlayerTimeChanged(_ aNotification: Notification!) { let totalTime = self.mediaPlayer.time.intValue - self.mediaPlayer.remainingTime.intValue DispatchQueue.main.async { self.progressSlider.setValue(Float(self.mediaPlayer.time.intValue)/Float(totalTime), animated: false) } self.updateLabels(for: self.mediaPlayer.time.intValue) } func mediaPlayerStateChanged(_ aNotification: Notification!) { if self.mediaPlayer.state == .ended { self.mediaPlayer.stop() self.mediaPlayer.play() } } @objc func sliderTouchBegan() { self.mediaPlayer.pause() } @objc func sliderMoved() { let totalTime = self.mediaPlayer.time.intValue - self.mediaPlayer.remainingTime.intValue let targetTime = self.progressSlider.value * Float(totalTime) self.mediaPlayer.time = VLCTime(int: Int32(targetTime)) self.updateLabels(for: Int32(targetTime)) } @objc func sliderTouchEnded() { self.mediaPlayer.play() } @objc func movieViewTapped(_ sender: UITapGestureRecognizer) { if self.mediaPlayer.isPlaying == true { self.mediaPlayer.pause() print("Paused") } else { self.mediaPlayer.play() print("Playing") } } }
43.141844
166
0.685681
d9b40799856435d9d4e9cb3f66256e7a9c245d54
682
// // SecondSecondConfigurator.swift // BumbleBee // // Created by Jieyi on 01/06/2018. // Copyright © 2018 SmashKs All rights reserved. // import UIKit class SecondModuleConfigurator: ViperInjector { func configureModuleForViewInput<UIViewController>(viewInput: UIViewController) { if let viewController = viewInput as? SecondViewController { configure(viewController: viewController) } } private func configure(viewController: SecondViewController) { // MARK: - Data Manager let presenter = viperProvider.resolve(SecondPresenter.self, argument: viewController)! viewController.presenter = presenter } }
26.230769
94
0.711144
7265494b2ada5009f0b83ef210e2d6aabc8fe616
508
// // ViewController.swift // MZCach // // Created by Zulqurnain24 on 12/30/2019. // Copyright (c) 2019 Zulqurnain24. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.32
80
0.673228
265143e6b61ea34652744571b6e50e4746c53827
12,558
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator. // DO NOT EDIT. #if compiler(>=5.5) && canImport(_Concurrency) import SotoCore // MARK: Paginators @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension LexModelBuildingService { /// Returns a list of aliases for a specified Amazon Lex bot. This operation requires permissions for the lex:GetBotAliases action. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func getBotAliasesPaginator( _ input: GetBotAliasesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<GetBotAliasesRequest, GetBotAliasesResponse> { return .init( input: input, command: getBotAliases, inputKey: \GetBotAliasesRequest.nextToken, outputKey: \GetBotAliasesResponse.nextToken, logger: logger, on: eventLoop ) } /// Returns a list of all of the channels associated with the specified bot. The GetBotChannelAssociations operation requires permissions for the lex:GetBotChannelAssociations action. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func getBotChannelAssociationsPaginator( _ input: GetBotChannelAssociationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<GetBotChannelAssociationsRequest, GetBotChannelAssociationsResponse> { return .init( input: input, command: getBotChannelAssociations, inputKey: \GetBotChannelAssociationsRequest.nextToken, outputKey: \GetBotChannelAssociationsResponse.nextToken, logger: logger, on: eventLoop ) } /// Gets information about all of the versions of a bot. The GetBotVersions operation returns a BotMetadata object for each version of a bot. For example, if a bot has three numbered versions, the GetBotVersions operation returns four BotMetadata objects in the response, one for each numbered version and one for the $LATEST version. The GetBotVersions operation always returns at least one version, the $LATEST version. This operation requires permissions for the lex:GetBotVersions action. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func getBotVersionsPaginator( _ input: GetBotVersionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<GetBotVersionsRequest, GetBotVersionsResponse> { return .init( input: input, command: getBotVersions, inputKey: \GetBotVersionsRequest.nextToken, outputKey: \GetBotVersionsResponse.nextToken, logger: logger, on: eventLoop ) } /// Returns bot information as follows: If you provide the nameContains field, the response includes information for the $LATEST version of all bots whose name contains the specified string. If you don't specify the nameContains field, the operation returns information about the $LATEST version of all of your bots. This operation requires permission for the lex:GetBots action. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func getBotsPaginator( _ input: GetBotsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<GetBotsRequest, GetBotsResponse> { return .init( input: input, command: getBots, inputKey: \GetBotsRequest.nextToken, outputKey: \GetBotsResponse.nextToken, logger: logger, on: eventLoop ) } /// Gets a list of built-in intents that meet the specified criteria. This operation requires permission for the lex:GetBuiltinIntents action. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func getBuiltinIntentsPaginator( _ input: GetBuiltinIntentsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<GetBuiltinIntentsRequest, GetBuiltinIntentsResponse> { return .init( input: input, command: getBuiltinIntents, inputKey: \GetBuiltinIntentsRequest.nextToken, outputKey: \GetBuiltinIntentsResponse.nextToken, logger: logger, on: eventLoop ) } /// Gets a list of built-in slot types that meet the specified criteria. For a list of built-in slot types, see Slot Type Reference in the Alexa Skills Kit. /// This operation requires permission for the lex:GetBuiltInSlotTypes action. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func getBuiltinSlotTypesPaginator( _ input: GetBuiltinSlotTypesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<GetBuiltinSlotTypesRequest, GetBuiltinSlotTypesResponse> { return .init( input: input, command: getBuiltinSlotTypes, inputKey: \GetBuiltinSlotTypesRequest.nextToken, outputKey: \GetBuiltinSlotTypesResponse.nextToken, logger: logger, on: eventLoop ) } /// Gets information about all of the versions of an intent. The GetIntentVersions operation returns an IntentMetadata object for each version of an intent. For example, if an intent has three numbered versions, the GetIntentVersions operation returns four IntentMetadata objects in the response, one for each numbered version and one for the $LATEST version. The GetIntentVersions operation always returns at least one version, the $LATEST version. This operation requires permissions for the lex:GetIntentVersions action. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func getIntentVersionsPaginator( _ input: GetIntentVersionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<GetIntentVersionsRequest, GetIntentVersionsResponse> { return .init( input: input, command: getIntentVersions, inputKey: \GetIntentVersionsRequest.nextToken, outputKey: \GetIntentVersionsResponse.nextToken, logger: logger, on: eventLoop ) } /// Returns intent information as follows: If you specify the nameContains field, returns the $LATEST version of all intents that contain the specified string. If you don't specify the nameContains field, returns information about the $LATEST version of all intents. The operation requires permission for the lex:GetIntents action. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func getIntentsPaginator( _ input: GetIntentsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<GetIntentsRequest, GetIntentsResponse> { return .init( input: input, command: getIntents, inputKey: \GetIntentsRequest.nextToken, outputKey: \GetIntentsResponse.nextToken, logger: logger, on: eventLoop ) } /// Gets a list of migrations between Amazon Lex V1 and Amazon Lex V2. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func getMigrationsPaginator( _ input: GetMigrationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<GetMigrationsRequest, GetMigrationsResponse> { return .init( input: input, command: getMigrations, inputKey: \GetMigrationsRequest.nextToken, outputKey: \GetMigrationsResponse.nextToken, logger: logger, on: eventLoop ) } /// Gets information about all versions of a slot type. The GetSlotTypeVersions operation returns a SlotTypeMetadata object for each version of a slot type. For example, if a slot type has three numbered versions, the GetSlotTypeVersions operation returns four SlotTypeMetadata objects in the response, one for each numbered version and one for the $LATEST version. The GetSlotTypeVersions operation always returns at least one version, the $LATEST version. This operation requires permissions for the lex:GetSlotTypeVersions action. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func getSlotTypeVersionsPaginator( _ input: GetSlotTypeVersionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<GetSlotTypeVersionsRequest, GetSlotTypeVersionsResponse> { return .init( input: input, command: getSlotTypeVersions, inputKey: \GetSlotTypeVersionsRequest.nextToken, outputKey: \GetSlotTypeVersionsResponse.nextToken, logger: logger, on: eventLoop ) } /// Returns slot type information as follows: If you specify the nameContains field, returns the $LATEST version of all slot types that contain the specified string. If you don't specify the nameContains field, returns information about the $LATEST version of all slot types. The operation requires permission for the lex:GetSlotTypes action. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func getSlotTypesPaginator( _ input: GetSlotTypesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<GetSlotTypesRequest, GetSlotTypesResponse> { return .init( input: input, command: getSlotTypes, inputKey: \GetSlotTypesRequest.nextToken, outputKey: \GetSlotTypesResponse.nextToken, logger: logger, on: eventLoop ) } } #endif // compiler(>=5.5) && canImport(_Concurrency)
46.339483
539
0.666109
0a9611da52131209387a477f476dd958fdbc4c77
1,027
// // StrategyPatternDemoTests.swift // StrategyPatternDemoTests // // Created by ZHOU DENGFENG on 19/12/16. // Copyright © 2016 ZHOU DENGFENG DEREK. All rights reserved. // import XCTest @testable import StrategyPatternDemo class StrategyPatternDemoTests: 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 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.756757
111
0.651412
db87e06e097cde7bcbec188c9926307859853d90
7,233
// // SBAActiveTask+CardioChallenge.swift // BridgeAppSDK // // Copyright © 2017 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchUXFactory public enum BridgeCardioChallengeStepIdentifier: String { case instruction case heartRisk case workoutInstruction1 case workoutInstruction2 case breathingBefore case tiredBefore case walkInstruction case countdown case fitnessWalk = "fitness.walk" case heartRateBefore = "heartRate.before" case heartRateAfter = "heartRate.after" case heartRateBeforeCameraInstruction = "heartRate.before.cameraInstruction" case heartRateAfterCameraInstruction = "heartRate.after.cameraInstruction" case heartRateBeforeCountdown = "heartRate.before.countdown" case heartRateAfterCountdown = "heartRate.after.countdown" case outdoorInstruction = "outdoor.instruction" case breathingAfter case tiredAfter case surveyAfter } extension SBAActiveTask { /** Build a custom version of the Cardio Challenge Task. */ public func createBridgeCardioChallenge(options: ORKPredefinedTaskOption, factory: SBASurveyFactory) -> ORKOrderedTask? { // If not iOS 10, then use the default let task = self.createDefaultORKActiveTask(options) guard #available(iOS 10.0, *), let orderedTask = task else { return task } var steps: [ORKStep] = [] var conclusionStep: ORKStep? // Include all the inner steps in the workout so that they are included in the same progress // Also, replace images and steps as required to match designs let workoutSteps = orderedTask.steps.mapAndFilter ({ (step) -> [ORKStep]? in // Filter out the steps that aren't considered part of the workout (and included in the count) let cardioIdentifier = BridgeCardioChallengeStepIdentifier(rawValue: step.identifier) if cardioIdentifier == .instruction { steps.insert(step, at: 0) return nil } else if cardioIdentifier == .heartRisk { steps.insert(replaceCardioStepIfNeeded(step), at: 1) return nil } else if step is ORKCompletionStep { conclusionStep = step return nil } else if let permissionStep = step as? SBAPermissionsStep { for (idx, _) in permissionStep.permissionTypes.enumerated() { steps.append(SBASinglePermissionStep(permissionsStep: permissionStep, index: idx)) } return nil } if let workout = step as? ORKWorkoutStep { return workout.steps.map({ replaceCardioStepIfNeeded($0) }) } else { return [replaceCardioStepIfNeeded(step)] } }).flatMap({ $0 }) let workoutTask = ORKOrderedTask(identifier: "workout", steps: workoutSteps) let workoutStep = ORKWorkoutStep(identifier: workoutTask.identifier, pageTask: workoutTask, relativeDistanceOnly: !SBAInfoManager.shared.currentParticipant.isTestUser, options: []) // Do not use the consolidated recordings // TODO: syoung 07/19/2017 Refactor SBAArchiveResult to only archive the results that are included in the // schema for a given activity. workoutStep.recorderConfigurations = [] steps.append(workoutStep) if conclusionStep != nil { steps.append(conclusionStep!) } return SBANavigableOrderedTask(identifier: orderedTask.identifier, steps: steps) } public func replaceCardioStepIfNeeded(_ step:ORKStep) -> ORKStep { guard let identifier = BridgeCardioChallengeStepIdentifier(rawValue: step.identifier) else { return step } switch(identifier) { case .heartRisk, .workoutInstruction1, .workoutInstruction2: return replaceInstructionStep(step, imageNamed: step.identifier) case .walkInstruction: let instructionStep = SBAInstructionBelowImageStep(identifier: step.identifier) instructionStep.title = step.title instructionStep.text = step.text instructionStep.image = SBAResourceFinder.shared.image(forResource: "phoneinpocketIllustration") return instructionStep case .breathingBefore, .breathingAfter: return SBAMoodScaleStep(step: step, images: nil) case .tiredBefore, .tiredAfter: return SBAMoodScaleStep(step: step, images: nil) default: return step } } public func replaceInstructionStep(_ step: ORKStep, imageNamed: String?) -> SBAInstructionStep { let instructionStep = SBAInstructionStep(identifier: step.identifier) instructionStep.title = step.title instructionStep.text = step.text if let detail = (step as? ORKInstructionStep)?.detailText { let popAction = SBAPopUpLearnMoreAction(identifier: step.identifier) popAction.learnMoreText = detail instructionStep.learnMoreAction = popAction } if imageNamed != nil { instructionStep.image = SBAResourceFinder.shared.image(forResource: imageNamed!) } return instructionStep } }
43.053571
125
0.663763
e6d3fdd2abb8ecb6a791d274a1ce7a3b678f9031
658
/* See LICENSE folder for this sample’s licensing information. Abstract: A simple class that represents an entry from the `Streams.plist` file in the main application bundle. */ import Foundation class Stream: Codable { // MARK: Types enum CodingKeys: String, CodingKey { case name = "name" case playlistURL = "playlist_url" } // MARK: Properties /// The name of the stream. let name: String /// The URL pointing to the HLS stream. let playlistURL: String } extension Stream: Equatable { static func ==(lhs: Stream, rhs: Stream) -> Bool { return (lhs.name == rhs.name) && (lhs.playlistURL == rhs.playlistURL) } }
19.939394
102
0.680851
2f3c93acc528372d89f393e1811fb75f590022f9
1,443
// // PostCollectionViewCell.swift // fakestagram // // Created by LuisE on 10/18/19. // Copyright © 2019 3zcurdia. All rights reserved. // import UIKit class PostCollectionViewCell: UICollectionViewCell { let miLikeService = LikeService() static let identifier: String = "PostCell" public var post: Post? { didSet { updateView() } } @IBOutlet weak var authorView: AuthorView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var likeCounter: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var likeBttn: UIButton! @IBOutlet weak var commentBttn: UIButton! func reset() { self.imageView.image = nil self.likeCounter.text = "" self.titleLabel.text = "" } func updateView() { reset() guard let post = self.post else { return } self.authorView.author = post.author self.titleLabel.text = post.title self.likeCounter.text = post.likesCountText() post.load { [unowned self] img in self.imageView.image = img } } @IBAction func Like(_ sender: Any) { miLikeService.call(idFoto: post?.id){ idFoto in print("Se dio un like") } } @IBAction func showComents(_ sender: Any) { print("prueba comentarios") } }
22.2
55
0.580735
71f08c94159263da6108716dcf37b75ec4c0e31c
2,056
/* * Copyright (C) 2019-2020 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ import heresdk import UIKit final class ViewController: UIViewController { @IBOutlet private var mapView: MapView! private var cameraExample: CameraExample! private var isMapSceneLoaded = false override func viewDidLoad() { super.viewDidLoad() // Load the map scene using a map style to render the map with. mapView.mapScene.loadScene(mapScheme: .normalDay, completion: onLoadScene) } private func onLoadScene(mapError: MapError?) { guard mapError == nil else { print("Error: Map scene not loaded, \(String(describing: mapError))") return } // Start the example. cameraExample = CameraExample(viewController: self, mapView: mapView) isMapSceneLoaded = true } @IBAction func onRotateButtonClicked(_ sender: Any) { if isMapSceneLoaded { cameraExample.onRotateButtonClicked() } } @IBAction func onTiltButtonClicked(_ sender: Any) { if isMapSceneLoaded { cameraExample.onTiltButtonClicked() } } @IBAction func onMoveToXYButtonClicked(_ sender: Any) { if isMapSceneLoaded { cameraExample.onMoveToXYButtonClicked() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() mapView.handleLowMemory() } }
29.371429
82
0.674611
16f49ef675ab72977dffc2fafef677eb6ca87475
22,109
// // SolitaireView.swift // Solitaire // // Created by Wayne Cochran on 4/5/16. // Copyright © 2016 Wayne Cochran. All rights reserved. // import UIKit let CARDASPECT : CGFloat = 150.0/215.0 let FAN_OFFSET : CGFloat = 0.15 class SolitaireView: UIView { var stockLayer : CALayer! var wasteLayer : CALayer! var foundationLayers : [CALayer]! var tableauLayers : [CALayer]! var topZPosition : CGFloat = 0 var cardToLayerDictionary : [Card : CardLayer]! var draggingCardLayer : CardLayer? = nil // card layer dragged (nil => no drag) var draggingFan : [Card]? = nil // fan of cards dragged var touchStartPoint : CGPoint = CGPoint.zero var touchStartLayerPosition : CGPoint = CGPoint.zero lazy var solitaire : Solitaire! = { // reference to model in app delegate let appDelegate = UIApplication.shared.delegate as! AppDelegate return appDelegate.solitaire }() let numberOfCardsToDeal = 3 override func awakeFromNib() { self.layer.name = "background" stockLayer = CALayer() stockLayer.name = "stock" stockLayer.backgroundColor = UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 0.3).cgColor self.layer.addSublayer(stockLayer) wasteLayer = CALayer() wasteLayer.name = "waste" wasteLayer.backgroundColor = UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 0.3).cgColor self.layer.addSublayer(wasteLayer) let foundationColor = UIColor(red: 0.0, green: 0.0, blue: 0.5, alpha: 0.3) foundationLayers = [] for i in 0 ..< 4 { let foundationLayer = CALayer(); foundationLayer.name = "foundation \(i)" foundationLayer.backgroundColor = foundationColor.cgColor self.layer.addSublayer(foundationLayer) foundationLayers.append(foundationLayer) } let tableauColor = UIColor(red: 0.0, green: 0.0, blue: 0.5, alpha: 0.3) tableauLayers = [] for i in 0 ..< 7 { let tableauLayer = CALayer(); tableauLayer.name = "tableau \(i)" tableauLayer.backgroundColor = tableauColor.cgColor self.layer.addSublayer(tableauLayer) tableauLayers.append(tableauLayer) } let deck = Card.deck() cardToLayerDictionary = [:] for card in deck { let cardLayer = CardLayer(card: card) cardLayer.name = "card" self.layer.addSublayer(cardLayer) cardToLayerDictionary[card] = cardLayer } becomeFirstResponder() // for shake -> triggers undo } override var canBecomeFirstResponder : Bool { return true // for shake -> triggers undo } func layoutTableAndCards() { let width = bounds.size.width let height = bounds.size.height let portrait = width < height let horzMargin = portrait ? 0.0325*width : 0.03125*width let vertMargin = portrait ? 0.026*height : 0.039*height let cardSpacing = portrait ? 0.0195*width : 0.026*width let tableauSpacing = portrait ? 0.0417*height : 0.026*height let cardWidth = (width - 2*horzMargin - 6*cardSpacing)/7 let cardHeight = cardWidth / CARDASPECT stockLayer.frame = CGRect(x: horzMargin, y: vertMargin, width: cardWidth, height: cardHeight) wasteLayer.frame = CGRect(x: horzMargin + cardSpacing + cardWidth, y: vertMargin, width: cardWidth, height: cardHeight) var x = width - horzMargin - cardWidth for i in (0...3).reversed() { foundationLayers[i].frame = CGRect(x: x, y: vertMargin, width: cardWidth, height: cardHeight) x -= cardSpacing + cardWidth } x = horzMargin let y = vertMargin + cardHeight + tableauSpacing for i in 0 ..< 7 { tableauLayers[i].frame = CGRect(x: x, y: y, width: cardWidth, height: cardHeight) x += cardSpacing + cardWidth } layoutCards() } func layoutCards() { self.isUserInteractionEnabled = false var z : CGFloat = 1.0 let stock = solitaire.stock for card in stock { let cardLayer = cardToLayerDictionary[card]! cardLayer.frame = stockLayer.frame cardLayer.faceUp = solitaire.isCardFaceUp(card) cardLayer.zPosition = z z = z + 1 } let waste = solitaire.waste for card in waste { let cardLayer = cardToLayerDictionary[card]! cardLayer.frame = wasteLayer.frame cardLayer.faceUp = solitaire.isCardFaceUp(card) cardLayer.zPosition = z z = z + 1 } for i in 0 ..< 4 { let foundation = solitaire.foundation[i] for card in foundation { let cardLayer = cardToLayerDictionary[card]! cardLayer.frame = foundationLayers[i].frame cardLayer.faceUp = solitaire.isCardFaceUp(card) cardLayer.zPosition = z z = z + 1 } } let cardSize = stockLayer.bounds.size let fanOffset = FAN_OFFSET * cardSize.height for i in 0 ..< 7 { let tableau = solitaire.tableau[i] let tableauOrigin = tableauLayers[i].frame.origin var j : CGFloat = 0 for card in tableau { let cardLayer = cardToLayerDictionary[card]! cardLayer.frame = CGRect(x: tableauOrigin.x, y: tableauOrigin.y + j*fanOffset, width: cardSize.width, height: cardSize.height) cardLayer.faceUp = solitaire.isCardFaceUp(card) cardLayer.zPosition = z z = z + 1 j = j + 1 } } topZPosition = z self.isUserInteractionEnabled = true } override func layoutSublayers(of layer: CALayer) { draggingCardLayer = nil // deactivate any dragging layoutTableAndCards() } func collectAllCardsInStock() { self.isUserInteractionEnabled = false var z : CGFloat = 1 for card in cardToLayerDictionary.keys { let cardLayer = cardToLayerDictionary[card]! cardLayer.faceUp = false cardLayer.frame = stockLayer.frame cardLayer.zPosition = z z = z + 1 } draggingCardLayer = nil topZPosition = z self.isUserInteractionEnabled = true } // // Used to move a 'fan' of card from one tableau to another. // func moveCardsToPosition(_ cards: [Card], position : CGPoint, animate : Bool) { CATransaction.begin() CATransaction.setDisableActions(true) for card in cards { let cardLayer = cardToLayerDictionary[card]! cardLayer.zPosition = topZPosition topZPosition = topZPosition + 1 } CATransaction.commit() if !animate { CATransaction.begin() CATransaction.setDisableActions(true) } var off : CGFloat = 0 for card in cards { let cardLayer = cardToLayerDictionary[card]! cardLayer.position = CGPoint(x: position.x, y: position.y + off) off += FAN_OFFSET*cardLayer.bounds.height } if !animate { CATransaction.commit() } } // // Used while user is dragging cards around. // Uses current 'draggingCardLayer' and 'draggingFan' variables. // z-positions should already be above all other card layers. // func dragCardsToPosition(_ position : CGPoint, animate : Bool) { if !animate { CATransaction.begin() CATransaction.setDisableActions(true) } draggingCardLayer!.position = position if let draggingFan = draggingFan { let off = FAN_OFFSET*draggingCardLayer!.bounds.size.height let n = draggingFan.count for i in 1 ..< n { let card = draggingFan[i] let cardLayer = cardToLayerDictionary[card]! cardLayer.position = CGPoint(x: position.x, y: position.y + CGFloat(i)*off) } } if !animate { CATransaction.commit() } } func moveCardLayerToTop(_ cardLayer : CardLayer) { CATransaction.begin() // do not animate z-position change CATransaction.setDisableActions(true) cardLayer.zPosition = topZPosition topZPosition = topZPosition + 1 CATransaction.commit() } func animateDeal( _ cardLayers : [CardLayer]) { var cardLayers = cardLayers if cardLayers.count > 0 { self.isUserInteractionEnabled = false let cardLayer = cardLayers[0] cardLayers.remove(at: 0) moveCardLayerToTop(cardLayer) CATransaction.begin() CATransaction.setCompletionBlock { self.animateDeal(cardLayers) } CATransaction.setAnimationDuration(0.25) cardLayer.faceUp = true cardLayer.position = wasteLayer.position CATransaction.commit() } else { self.isUserInteractionEnabled = true } } func multiCardDeal() { let cards = solitaire.dealCards(numberOfCardsToDeal) undoManager?.registerUndo(withTarget: self, handler: { me in me.undoMultiCard(cards) }) undoManager?.setActionName("deal cards") var cardLayers : [CardLayer] = [] for c in cards { let clayer = cardToLayerDictionary[c]! cardLayers.append(clayer) } animateDeal(cardLayers) } func undoMultiCard(_ cards : [Card]) { undoManager?.registerUndo(withTarget: self, handler: { me in me.multiCardDeal() }) undoManager?.setActionName("deal cards") self.solitaire.undoDealCards(cards.count) self.layoutCards() } func oneCardDeal() { undoManager?.registerUndo(withTarget: self, handler: {me in me.undoOneCardDeal() }) undoManager?.setActionName("deal card") let card = solitaire.stock.last! let cardLayer = cardToLayerDictionary[card]! moveCardLayerToTop(cardLayer) cardLayer.position = wasteLayer.position cardLayer.faceUp = true solitaire.didDealCard() } func undoOneCardDeal() { undoManager?.registerUndo(withTarget: self, handler: {me in me.oneCardDeal() }) undoManager?.setActionName("deal card") self.solitaire.undoDealCard() self.layoutCards() } func flipCard(_ card : Card, faceUp up : Bool) { undoManager?.registerUndo(withTarget: self, handler: {me in me.flipCard(card, faceUp: !up) }) undoManager?.setActionName("flip card") let cardLayer = cardToLayerDictionary[card] cardLayer!.faceUp = up up ? solitaire.didFlipCard(card) : solitaire.undoFlipCard(card) } func collectWasteCardsIntoStock() { undoManager?.registerUndo(withTarget: self, handler: {me in me.undoCollectWasteCardsIntoStock() }) undoManager?.setActionName("collect waste cards") solitaire.collectWasteCardsIntoStock() var z : CGFloat = 1 self.isUserInteractionEnabled = false for card in solitaire.stock { let cardLayer = cardToLayerDictionary[card]! cardLayer.faceUp = false cardLayer.frame = stockLayer.frame cardLayer.zPosition = z z = z + 1 } self.isUserInteractionEnabled = true } func undoCollectWasteCardsIntoStock() { undoManager?.registerUndo(withTarget: self, handler: {me in me.collectWasteCardsIntoStock() }) undoManager?.setActionName("collect waste cards") solitaire.undoCollectWasteCardsIntoStock() layoutCards() } func dropCard(_ card : Card, onFoundation i : Int) { let cardLayer = cardToLayerDictionary[card]! moveCardLayerToTop(cardLayer) cardLayer.position = foundationLayers[i].position let cardStack = solitaire.didDropCard(card, onFoundation: i) undoManager?.registerUndo(withTarget: self, handler: {me in me.undoDropCard(card, fromStack: cardStack, onFoundation: i) }) undoManager?.setActionName("drop card on foundation") } func undoDropCard(_ card: Card, fromStack source: CardStack, onFoundation i : Int) { solitaire.undoDidDropCard(card, fromStack: source, onFoundation: i) layoutCards() undoManager?.registerUndo(withTarget: self, handler: { me in me.dropCard(card, onFoundation: i) }) undoManager?.setActionName("drop card on foundation") } func dropCard(_ card : Card, onTableau i : Int) { let cardLayer = cardToLayerDictionary[card]! let stackCount = solitaire.tableau[i].count let cardHeight = cardLayer.bounds.height let fanOffset = FAN_OFFSET*cardHeight moveCardLayerToTop(cardLayer) cardLayer.position = CGPoint(x: tableauLayers[i].position.x, y: tableauLayers[i].position.y + CGFloat(stackCount)*fanOffset) let cardStack = solitaire.didDropCard(card, onTableau: i) undoManager?.registerUndo(withTarget: self, handler: {me in me.undoDropCard(card, fromStack: cardStack, onTableau: i) }) undoManager?.setActionName("drop card on tableau") } func undoDropCard(_ card: Card, fromStack source: CardStack, onTableau i : Int) { solitaire.undoDidDropCard(card, fromStack: source, onTableau: i) layoutCards() undoManager?.registerUndo(withTarget: self, handler: { me in me.dropCard(card, onTableau: i) }) undoManager?.setActionName("drop card on tableau") } func dropFan(_ cards : [Card], onTableau i : Int) { let card = cards.first! let cardLayer = cardToLayerDictionary[card]! let stackCount = solitaire.tableau[i].count let cardHeight = cardLayer.bounds.height let fanOffset = FAN_OFFSET*cardHeight let position = CGPoint(x: tableauLayers[i].position.x, y: tableauLayers[i].position.y + CGFloat(stackCount)*fanOffset) moveCardsToPosition(cards, position: position, animate: true) let cardStack = solitaire.didDropFan(cards, onTableau: i) undoManager?.registerUndo(withTarget: self, handler: { me in me.undoDropFan(cards, fromStack: cardStack, onTableau: i) }) undoManager?.setActionName("drag fan") } func undoDropFan(_ cards : [Card], fromStack source: CardStack, onTableau i : Int) { solitaire.undoDidDropFan(cards, fromStack: source, onTableau: i) layoutCards() undoManager?.registerUndo(withTarget: self, handler: { me in me.dropFan(cards, onTableau: i) // XXX redo blow up }) undoManager?.setActionName("drag fan") } // // Note: the point passed to hitTest: is in the coordinate system of // self.layer.superlayer // http://goo.gl/FIzjZD // override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first! let touchPoint = touch.location(in: self) let hitTestPoint = self.layer.convert(touchPoint, to: self.layer.superlayer) let layer = self.layer.hitTest(hitTestPoint) if let layer = layer { if layer.name == "card" { let cardLayer = layer as! CardLayer let card = cardLayer.card if solitaire.isCardFaceUp(card) { touchStartPoint = touchPoint touchStartLayerPosition = cardLayer.position CATransaction.begin() // do not animate z-position change CATransaction.setDisableActions(true) cardLayer.zPosition = topZPosition topZPosition = topZPosition + 1 draggingFan = solitaire.fanBeginningWithCard(card) if let draggingFan = draggingFan { for i in 1 ..< draggingFan.count { let card = draggingFan[i] let clayer = cardToLayerDictionary[card]! clayer.zPosition = topZPosition topZPosition = topZPosition + 1 } } CATransaction.commit() if touch.tapCount > 1 { if draggingFan == nil || draggingFan!.count <= 1 { for i in 0 ..< 4 { if solitaire.canDropCard(card, onFoundation: i) { dropCard(card, onFoundation: i) break; } } } return } draggingCardLayer = cardLayer } else if solitaire.canFlipCard(card) { flipCard(card, faceUp: true) } else if solitaire.stock.last == card { if numberOfCardsToDeal > 1 { multiCardDeal() } else { oneCardDeal() } } } else if (layer.name == "stock") { collectWasteCardsIntoStock() } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if draggingCardLayer != nil { let touch = touches.first! let p = touch.location(in: self) let delta = CGPoint(x: p.x - touchStartPoint.x, y: p.y - touchStartPoint.y) let position = CGPoint(x: touchStartLayerPosition.x + delta.x, y: touchStartLayerPosition.y + delta.y) dragCardsToPosition(position, animate: false) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { if draggingCardLayer != nil { dragCardsToPosition(touchStartLayerPosition, animate: true) draggingCardLayer = nil } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if let dragLayer = draggingCardLayer { let numCards = draggingFan == nil ? 1 : draggingFan!.count if numCards == 1 { // drop on foundation or tableau // // Drop card on foundation? // for i in 0 ..< 4 { if dragLayer.frame.intersects(foundationLayers[i].frame) && solitaire.canDropCard(dragLayer.card, onFoundation: i) { dropCard(dragLayer.card, onFoundation: i) draggingCardLayer = nil return // done } } // // Drop card on tableau? // for i in 0 ..< 7 { let topCard = solitaire.tableau[i].isEmpty ? nil : solitaire.tableau[i].last var targetFrame : CGRect if let topCard = topCard { let topCardLayer = cardToLayerDictionary[topCard]! targetFrame = topCardLayer.frame } else { targetFrame = tableauLayers[i].frame } if dragLayer.frame.intersects(targetFrame) && solitaire.canDropCard(dragLayer.card, onTableau: i) { if topCard != nil { let cardSize = targetFrame.size let fanOffset = FAN_OFFSET*cardSize.height targetFrame.origin.y += fanOffset } dropCard(dragLayer.card, onTableau: i) draggingCardLayer = nil return // done } } } // end numCards == 1 // // Drop fan of cards on tableau? // if let fan = draggingFan { for i in 0 ..< 7 { let topCard = solitaire.tableau[i].isEmpty ? nil : solitaire.tableau[i].last var topCardLayer : CardLayer? = nil var targetFrame : CGRect if let topCard = topCard { topCardLayer = cardToLayerDictionary[topCard] targetFrame = topCardLayer!.frame } else { targetFrame = tableauLayers[i].frame } if dragLayer.frame.intersects(targetFrame) && solitaire.canDropFan(fan, onTableau: i) { dropFan(fan, onTableau: i) draggingCardLayer = nil return // done } } } // // Didn't drop any cards ... move 'em back to original position // dragCardsToPosition(touchStartLayerPosition, animate: true) draggingCardLayer = nil } } }
37.157983
142
0.551947
8ffca2a8c06d859fd091f521a1d05b266fc5f068
2,229
// // LoginViewController.swift // Flounderr // // Created by Ha Nuel Lee on 3/17/16. // Copyright © 2016 Flounderr. All rights reserved. // import UIKit import Parse class LoginViewController: UIViewController { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var signUpWithGoogleButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onLogin(sender: AnyObject) { PFUser.logInWithUsernameInBackground(usernameTextField.text!, password: passwordTextField.text!) { (user: PFUser?, error: NSError?) -> Void in if user != nil { print("Yay! successful logging in!") self.performSegueWithIdentifier("loginSegue", sender: nil) } else { print(error?.localizedDescription ) } } } @IBAction func onSignUp(sender: AnyObject) { let newUser = PFUser() newUser.username = usernameTextField.text newUser.password = passwordTextField.text newUser.signUpInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in if success { print("Yay! user was created.") self.performSegueWithIdentifier("loginSegue", sender: nil) } else { print(error?.localizedDescription) } } } @IBAction func onSignUpWithGoogle(sender: AnyObject) { } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
31.394366
150
0.633468
fe1335d625e3ce0448754e52e5631b1e43582331
3,071
// // APIDecoder.swift // LastMile // // Copyright (c) 2018 Josh Elkins // // 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 protocol APIDecoder: class { var node: JSONNode? { get } var codingKey: CodingKey { get } var codingPath: [CodingKey] { get } var key: APICodingKey { get } var path: [APICodingKey] { get } var errors: [APIDecodeError] { get set } subscript(key: String) -> APIDecoder { get } subscript(index: Int) -> APIDecoder { get } subscript(codingKey: CodingKey) -> APIDecoder { get } func superDecoder() -> APIDecoder func errorHoldingDecoder() -> APIDecoder func decodeRequired<DecodedType: APIDecodable>(_ type: DecodedType.Type, min: Int?, max: Int?, countsAreMandatory: Bool) -> DecodedType! func decodeOptional<DecodedType: APIDecodable>(_ type: DecodedType.Type, min: Int?, max: Int?, countsAreMandatory: Bool) -> DecodedType? func decodeRequired<DecodedType: Decodable>(swiftDecodable type: DecodedType.Type) -> DecodedType! func decodeOptional<DecodedType: Decodable>(swiftDecodable type: DecodedType.Type) -> DecodedType? var isJSONNull: Bool { get } func recordError(_ error: APIDecodeError) var succeeded: Bool { get set } var options: [String: Any] { get } } public extension APIDecoder { func decodeRequired<DecodedType: APIDecodable>(_ type: DecodedType.Type, min: Int? = nil, max: Int? = nil, countsAreMandatory: Bool = false) -> DecodedType! { return decodeRequired(type, min: min, max: max, countsAreMandatory: countsAreMandatory) } func decodeOptional<DecodedType: APIDecodable>(_ type: DecodedType.Type, min: Int? = nil, max: Int? = nil, countsAreMandatory: Bool = false) -> DecodedType? { return decodeOptional(type, min: min, max: max, countsAreMandatory: countsAreMandatory) } } public enum APIDecodeOptions { public static let rootNodeNameKey = "APIDecodeOptions.rootNodeNameKey" public static let rawDataKey = "APIDecodeOptions.rawDataKey" }
45.835821
162
0.727125
9c96656b9337bc0d0171c5e30a154efb8372eddb
1,787
//: [Previous](@previous) import Foundation //: Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? //: Let's assume the string is not sorted do { final class Solution1 { /* 0(n) worst case scenario juste storing each word in a dictionnary with a count When a count reach 2, break an return false */ func isUnique(_ input: String) -> Bool { if input.isEmpty { return false } var charMap: [Character: Int] = [:] for char in input { if (charMap[char] != nil) { return false } charMap[char] = 1 } return true } } Solution1().isUnique("Hello world") // false Solution1().isUnique("One") // true } //: Given two strings, write a method to decide if one is a permutation of the other /* First condition of a permutation match is char match for both of the string Let's store the char count of each string and compare them later */ do { final class Solution { func checkPermutation(_ input1: String, _ input2: String) -> Bool { if input1.count != input2.count { return false } var charMap1: [Character: Int] = [:] for char in input1 { if charMap1[char] != nil { charMap1[char] = charMap1[char]! + 1 } else { charMap1[char] = 1 } } var charMap2: [Character: Int] = [:] for char in input2 { if charMap2[char] != nil { charMap2[char] = charMap2[char]! + 1 } else { charMap2[char] = 1 } } if charMap1 == charMap2 { return true } return false } } let l = Solution().checkPermutation("hello", "ollhe") } //: [Next](@next)
24.819444
140
0.586458
29b34c11d50cdfcf2c1a6965fd74cbff0404fdc5
1,721
import Foo // REQUIRES: objc_interop // Perform 8 concurrent cursor infos, which is often enough to cause // contention. We disable printing the requests to minimize delay. // RUN: %sourcekitd-test -req=interface-gen-open -module Foo -- \ // RUN: -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %clang-importer-sdk \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 | FileCheck %s -check-prefix=CHECK-FOO // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions
63.740741
103
0.721092
9be5398f516d67c1018e52a0a00f45179702988a
1,125
// // DetailCell.swift // CleanArchitecture // // Created by Su Ho V. on 4/7/19. // Copyright © 2019 mlsuho. All rights reserved. // import UIKit final class DetailCell: TableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var detailLabel: UILabel! var viewModel: DetailCellViewModel! { didSet { guard viewModel != nil else { return } self.bind(self.viewModel) } } override func setupUI() { super.setupUI() setupContent() setupTexts() } private func bind(_ viewModel: DetailCellViewModel) { titleLabel.text = viewModel.title detailLabel.text = viewModel.detail } } // MARK: - UI extension DetailCell { private func setupContent() { backgroundColor = App.Theme.current.package.detailCellBackground contentView.backgroundColor = App.Theme.current.package.detailCellBackground } private func setupTexts() { titleLabel.textColor = App.Theme.current.package.detailCellText detailLabel.textColor = App.Theme.current.package.detailCellText } }
25
84
0.659556
efdf0fcf6c5ba1ea3617ad9f09979d84d0196a63
2,580
import Foundation func _panic(msg : String) { print(msg) exit(-1) } class BitInputStream { var buffer : UInt16 = 0 var pos : Int = 0 var bitsInBuffer : UInt16 = 0 var eof : Bool = false var bytes : [UInt8] = [UInt8]() var len : Int = 0 init(inputFile: String) { if let data = NSData(contentsOfFile: inputFile) { bytes = [UInt8](repeating: 0, count: data.length) data.getBytes(&bytes, length: data.length) len = data.length } fillBuffer() } func readBool() -> Bool { if eof { _panic(msg: "can't read bool from input stream") } bitsInBuffer -= 1 let bit = ((buffer >> bitsInBuffer) & 1) == 1 if bitsInBuffer == 0 { fillBuffer() } return bit } func readChar() -> UInt8 { if eof { _panic(msg: "reading from empty input stream") } var x = buffer if bitsInBuffer == 8 { fillBuffer() } else { x = x << (8 - bitsInBuffer) let temp = bitsInBuffer fillBuffer() bitsInBuffer = temp x |= buffer >> bitsInBuffer } return UInt8(x & 0xFF) } func readInt() -> UInt32 { var x = UInt32(readChar()) x = (x << 8) | UInt32(readChar()) x = (x << 8) | UInt32(readChar()) x = (x << 8) | UInt32(readChar()) return x } func fillBuffer() { if pos == len { eof = true } else { buffer = UInt16(bytes[pos]) bitsInBuffer = 8 pos += 1 } } func getBytes() -> [UInt8] { return bytes } } class BitOutputStream { var out : Data var buffer : UInt16 = 0 var bitsInBuffer : UInt16 = 0 var output : String init(outputFile: String) { out = Data() output = outputFile } func writeBitc(bit: Character) { if bit == "0" { writeBit(bit: 0) } else if bit == "1" { writeBit(bit: 1) } else { _panic(msg: "argument must be '0' or '1'") } } func writeBit(bit: UInt16) { if bit != 0 && bit != 1 { _panic(msg: "argument must be 0 or 1") } buffer = (buffer << 1) | bit bitsInBuffer += 1 if bitsInBuffer == 8 { clearBuffer() } } func writeByte(byte: UInt16) { for i in 0..<8 { let bit = (byte >> (8 - i - 1)) & 1 writeBit(bit: bit) } } func writeInt(i: UInt32) { writeByte(byte: UInt16((i >> 24) & 0xFF)) writeByte(byte: UInt16((i >> 16) & 0xFF)) writeByte(byte: UInt16((i >> 8) & 0xFF)) writeByte(byte: UInt16((i >> 0) & 0xFF)) } func clearBuffer() { if bitsInBuffer == 0 { return } if bitsInBuffer > 0 { buffer = buffer << (8 - bitsInBuffer) } out.append(UInt8(buffer)) buffer = 0 bitsInBuffer = 0 } func close() { let nsdata = NSData(data: out) nsdata.write(toFile: output, atomically: true) } }
18.169014
52
0.588372
9027d65b1a13e455f226b18e39d89469e89f68eb
2,082
// // SuanUtils.swift // Suan // // Created by David Hu on 2018/6/10. // Copyright © 2018 DavidHu. All rights reserved. // import Foundation import UIKit /* Usage: let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF) let color2 = UIColor(rgb: 0xFFFFFF) use alpha: let semitransparentBlack = UIColor(rgb: 0x000000).withAlphaComponent(0.5) let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0.5) let color2 = UIColor(rgb: 0xFFFFFF, a: 0.5) */ extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(hex: Int) { self.init( red: (hex >> 16) & 0xFF, green: (hex >> 8) & 0xFF, blue: hex & 0xFF ) } convenience init(red: Int, green: Int, blue: Int, a: Int = 0xFF) { self.init( red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(a) / 255.0 ) } // let's suppose alpha is the first component (ARGB) convenience init(ahex: Int) { self.init( red: (ahex >> 16) & 0xFF, green: (ahex >> 8) & 0xFF, blue: ahex & 0xFF, a: (ahex >> 24) & 0xFF ) } class var suanYellow: UIColor { return UIColor.init(hex: 0xD9A84E) } class var suanLightBrown: UIColor { return UIColor.init(hex: 0xD9A84E) } class var suanGreyBrown: UIColor { return UIColor.init(hex: 0xD9A84E) } class var suanBrown: UIColor { return UIColor.init(hex: 0xD9A84E) } class var suanheavyBrown: UIColor { return UIColor.init(hex: 0xD9A84E) } }
26.025
116
0.548511
2fc736f8c24c361a1c7eacd02d38641071b9f75f
3,030
// // KeyboardObserving.swift // Desk360 // // Created by samet on 18.05.2019. // import Foundation /// Conform to `KeyboardObserving` protocol in view controllers to observe keyboard events and pass them to a `KeyboardHandling` view. public protocol KeyboardObserving: AnyObject { /// Called right before the keyboard is presented. /// /// - Parameter notification: `KeyboardNotification` func keyboardWillShow(_ notification: KeyboardNotification?) /// Called right after the keyboard is presented. /// /// - Parameter notification: `KeyboardNotification` func keyboardDidShow(_ notification: KeyboardNotification?) /// Called right before the keyboard is hidden. /// /// - Parameter notification: `KeyboardNotification` func keyboardWillHide(_ notification: KeyboardNotification?) /// Called right after the keyboard is hidden. /// /// - Parameter notification: `KeyboardNotification` func keyboardDidHide(_ notification: KeyboardNotification?) /// Called right before the keyboard is about to change its frame. /// /// - Parameter notification: `KeyboardNotification` func keyboardWillChangeFrame(_ notification: KeyboardNotification?) /// Called right after the keyboard did changed its frame. /// /// - Parameter notification: `KeyboardNotification` func keyboardDidChangeFrame(_ notification: KeyboardNotification?) /// Start observing keyboard events sent from the OS. func registerForKeyboardEvents() } // MARK: - Default implementation for UIViewController. public extension KeyboardObserving where Self: UIViewController { func registerForKeyboardEvents() { _ = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { [weak self] notification in self?.keyboardWillShow(KeyboardNotification(notification: notification)) } _ = NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: nil) { [weak self] notification in self?.keyboardDidShow(KeyboardNotification(notification: notification)) } _ = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) { [weak self] notification in self?.keyboardWillHide(KeyboardNotification(notification: notification)) } _ = NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidHideNotification, object: nil, queue: nil) { [weak self] notification in self?.keyboardDidHide(KeyboardNotification(notification: notification)) } _ = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: nil) { [weak self] notification in self?.keyboardWillChangeFrame(KeyboardNotification(notification: notification)) } _ = NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidChangeFrameNotification, object: nil, queue: nil) { [weak self] notification in self?.keyboardDidChangeFrame(KeyboardNotification(notification: notification)) } } }
38.846154
157
0.783498
719ddc4735a5e9ecf4b088a432c59c5a025eaad6
1,834
// // AppDelegate.swift // HitTest // // Created by Nicolás Miari on 2020/04/28. // Copyright © 2020 Nicolás Miari. 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. } 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. } }
43.666667
285
0.753544
2311ff7013e18db976d8aa8841502f229c6db07f
1,261
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "SnapshotTesting-Nimble", platforms: [ .iOS(.v11), .tvOS(.v11), .macOS(.v10_10), ], products: [ .library( name: "SnapshotTesting-Nimble", targets: [ "SnapshotTesting-Nimble", "SnapshotTesting-Nimble-ObjC", ] ), ], dependencies: [ .package(url: "https://github.com/pointfreeco/swift-snapshot-testing.git", from: "1.8.1"), .package(url: "https://github.com/Quick/Nimble.git", .upToNextMajor(from: "9.0.0")), ], targets: [ .target( name: "SnapshotTesting-Nimble", dependencies: [ "SnapshotTesting", "Nimble", ], path: "SnapshotTesting-Nimble/Classes" ), .target( name: "SnapshotTesting-Nimble-ObjC", dependencies: [ "SnapshotTesting-Nimble", ], path: "SnapshotTesting-Nimble/Objc-Classes", cSettings: [ .headerSearchPath("SnapshotTesting-Nimble/Objc-Classes"), ] ), ] )
26.270833
82
0.483743
e2ac1be8ff6bbb895003824178456b48cdad4e08
1,869
// // SearchArticlesViewAdapter.swift // PaginationNewsApp // // Created by Shinzan Takata on 2021/01/03. // import Combine import UIKit import PaginationNews import PaginationNewsiOS private enum EmptyReason { case noKeyword case noData var message: String { switch self { case .noKeyword: return SearchArticlesPresenter.noKeywordMessage case .noData: return SearchArticlesPresenter.noMatchedDataMessage } } } final class SearchArticlesViewAdapter: ContentView { private weak var controller: SearchArticlesViewController? private let imageLoader: (Article) -> AnyPublisher<Data, Error> private typealias PresentationAdapter = ImageDataPresentationAdapter<WeakReference<ArticleCellController>> init(controller: SearchArticlesViewController, imageLoader: @escaping (Article) -> AnyPublisher<Data, Error>) { self.controller = controller self.imageLoader = imageLoader controller.displayEmpty(EmptyReason.noKeyword.message) } func display(_ viewModel: SearchArticlesViewModel) { guard let controller = controller else { return } let controllers = viewModel.articles.map(map) controller.display(controllers) if controllers.isEmpty { let reason: EmptyReason = viewModel.keyword.isEmpty ? .noKeyword : .noData controller.displayEmpty(reason.message) } } private struct NoImageError: Error {} func map(_ model: Article) -> CellController { let adapter = PresentationAdapter(loader: { self.imageLoader(model) }) let view = ArticleCellController(viewModel: ArticlePresenter.map(model), delegate: adapter) adapter.presenter = Presenter( contentView: WeakReference(view), loadingView: WeakReference(view), errorView: WeakReference(view), mapper: UIImage.tryMap) return CellController(id: UUID(), dataSource: view, delegate: view, dataSourcePrefetching: view) } }
29.203125
112
0.761905
381f61fc20f92df8971724450b94cff64f1f5550
20,316
// // DBSurveyTableViewController.swift // Survey // // Created by Wesley Scheper on 05/12/15. // Copyright © 2015 Wesley Scheper. All rights reserved. // import UIKit import ResearchKit class DBSurveyTableViewController: UITableViewController, ORKTaskViewControllerDelegate { let DBSurveyTableViewControllerCellMorningSurvey = 0 let DBSurveyTableViewControllerCellEveningSurvey = 1 let DBSurveyTypeIdentifier = "type" let DBSurveyDateAndTimeIdentifier = "created" let DBSurveyWeightIdentifier = "weight" let DBSurveyBodyWeightIdentifier = "body_weight_kg" let DBSurveyBodyFatIdentifier = "body_fat_percent" let DBSurveyMoodIdentifier = "mood" let DBSurveyHeartIdentifier = "heart" let DBSurveyHeartRateIdentifier = "heart_rate_bpm" let DBSurveyBloodPressureSystolicIdentifier = "blood_pressure_systolic_mmhg" let DBSurveyBloodPressureDiastrolicIdentifier = "blood_pressure_diastolic_mmhg" let DBSurveyAlcoholIdentifier = "alcohol" let DBSurveyAlcoholConsumptionIdentifier = "alcohol_consumption" let DBSurveyActivityIdentifier = "activity" let DBSurveyStepCountIdentifier = "step_count" let DBSurveyWorkoutIdentifier = "workout" let DBSurveySleepIdentifier = "sleep" let DBSurveySleepStartIdentifier = "sleep_start" let DBSurveySleepEndIdentifier = "sleep_end" let DBSurveySleepHoursIdentifier = "sleep_hours" let DBSurveySleepScoreIdentifier = "sleep_score" let DBSurveyStressIdentifier = "stress" let DBSurveyWaitIdentifier = "wait" let DBSurveyFrontBodyImageIdentifier = "front_body_image" let DBSurveySideBodyImageIdentifier = "side_body_image" let DBSurveyBackBodyImageIdentifier = "back_body_image" let DBSurveyAppVersion = "app_version" let DBSurveyAPIURL = "http://10.2.1.1:5984/health_data/" var selectedSurvey: String = "" override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var steps: Array<ORKStep> = Array() if indexPath.row == DBSurveyTableViewControllerCellMorningSurvey { selectedSurvey = "morning" steps = [moodStep(), stressStep(), sleepStep(), bodyWeightAndFatPercentageStep()] } else if indexPath.row == DBSurveyTableViewControllerCellEveningSurvey { selectedSurvey = "morning" steps = [moodStep(), stressStep(), alcoholConsumptionStep(), activityStep(), bloodPressureAndHeartRateStep()] } let task = ORKOrderedTask(identifier: "task", steps: steps) let taskViewController = ORKTaskViewController(task: task, taskRunUUID: nil) taskViewController.delegate = self taskViewController.outputDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! presentViewController(taskViewController, animated: true, completion: nil) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } // MARK: ORTaskViewController Delegate func taskViewController(taskViewController: ORKTaskViewController, didFinishWithReason reason: ORKTaskViewControllerFinishReason, error: NSError?) { if reason == .Completed { var results = resultsFromTaskViewController(taskViewController.result) results[DBSurveyDateAndTimeIdentifier] = NSDate().dateString() results[DBSurveyTypeIdentifier] = self.selectedSurvey results[DBSurveyAppVersion] = "1.1" // @TODO include hash from the collected values, so we can ensure the data has not been edited print(results) // Send results let requestURL = NSURL(string: DBSurveyAPIURL + NSUUID().UUIDString)! let request = NSMutableURLRequest(URL: requestURL) request.HTTPMethod = "PUT" request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(results, options: NSJSONWritingOptions.PrettyPrinted) request.setValue("application/json", forHTTPHeaderField: "Content-Type") let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in let alert = UIAlertController(title: (error != nil ? "Failed" : "Success"), message: (error != nil ? "Could not transmit survey" : "Survey successfully transmitted"), preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) }) }) task.resume() } // Then, dismiss the task view controller. dismissViewControllerAnimated(true, completion: nil) } // MARK: Helper Methods // Creates an Dictionary with the results of the survey // @TODO: refactor this to a more abstract approach func resultsFromTaskViewController(taskResult: ORKTaskResult) -> Dictionary<String, String>{ var results: Dictionary<String, String> = Dictionary<String, String>() for result in taskResult.results! { if result.identifier == DBSurveyMoodIdentifier { let stepResult = result as! ORKStepResult let choiceQuestionResult = stepResult.results?.first as! ORKChoiceQuestionResult results[DBSurveyMoodIdentifier] = choiceQuestionResult.choiceAnswers?.first as? String } else if result.identifier == DBSurveyStressIdentifier { let stepResult = result as! ORKStepResult let choiceQuestionResult = stepResult.results?.first as! ORKChoiceQuestionResult results[DBSurveyStressIdentifier] = choiceQuestionResult.choiceAnswers?.first as? String } else if result.identifier == DBSurveyWeightIdentifier { let stepResult = result as! ORKStepResult for stepSubResult in stepResult.results! { if stepSubResult.identifier == DBSurveyBodyWeightIdentifier { let numericQuestionResult = stepSubResult as! ORKNumericQuestionResult results[DBSurveyBodyWeightIdentifier] = numericQuestionResult.answer != nil ? String(numericQuestionResult.answer!) : nil } else if stepSubResult.identifier == DBSurveyBodyFatIdentifier { let numericQuestionResult = stepSubResult as! ORKNumericQuestionResult results[DBSurveyBodyFatIdentifier] = numericQuestionResult.answer != nil ? String(numericQuestionResult.answer!) : nil } } } else if result.identifier == DBSurveyAlcoholIdentifier { let stepResult = result as! ORKStepResult let booleanQuestionResult = stepResult.results?.first as! ORKBooleanQuestionResult results[DBSurveyAlcoholConsumptionIdentifier] = booleanQuestionResult.answer != nil ? String(booleanQuestionResult.answer!) : nil } else if result.identifier == DBSurveyHeartIdentifier { let stepResult = result as! ORKStepResult for stepSubResult in stepResult.results! { if stepSubResult.identifier == DBSurveyHeartRateIdentifier { let numericQuestionResult = stepSubResult as! ORKNumericQuestionResult results[DBSurveyHeartRateIdentifier] = numericQuestionResult.answer != nil ? String(numericQuestionResult.answer!) : nil } else if stepSubResult.identifier == DBSurveyBloodPressureSystolicIdentifier { let numericQuestionResult = stepSubResult as! ORKNumericQuestionResult results[DBSurveyBloodPressureSystolicIdentifier] = numericQuestionResult.answer != nil ? String(numericQuestionResult.answer!) : nil } else if stepSubResult.identifier == DBSurveyBloodPressureDiastrolicIdentifier { let numericQuestionResult = stepSubResult as! ORKNumericQuestionResult results[DBSurveyBloodPressureDiastrolicIdentifier] = numericQuestionResult.answer != nil ? String(numericQuestionResult.answer!) : nil } } } else if result.identifier == DBSurveyActivityIdentifier { let stepResult = result as! ORKStepResult for stepSubResult in stepResult.results! { if stepSubResult.identifier == DBSurveyStepCountIdentifier { let numericQuestionResult = stepSubResult as! ORKNumericQuestionResult results[DBSurveyStepCountIdentifier] = numericQuestionResult.answer != nil ? String(numericQuestionResult.answer!) : nil } else if stepSubResult.identifier == DBSurveyWorkoutIdentifier { let booleanQuestionResult = stepSubResult as! ORKBooleanQuestionResult results[DBSurveyWorkoutIdentifier] = booleanQuestionResult.answer != nil ? String(booleanQuestionResult.answer!) : nil } } } else if result.identifier == DBSurveySleepIdentifier { let stepResult = result as! ORKStepResult for stepSubResult in stepResult.results! { if stepSubResult.identifier == DBSurveySleepStartIdentifier { let timeOfDayQuestionResult = stepSubResult as! ORKTimeOfDayQuestionResult let dateTimeComponents = timeOfDayQuestionResult.answer as? NSDateComponents results[DBSurveySleepStartIdentifier] = dateTimeComponents != nil ? dateTimeComponents!.simpleDateString() : nil } else if stepSubResult.identifier == DBSurveySleepEndIdentifier { let timeOfDayQuestionResult = stepSubResult as! ORKTimeOfDayQuestionResult let dateTimeComponents = timeOfDayQuestionResult.answer as? NSDateComponents results[DBSurveySleepEndIdentifier] = dateTimeComponents != nil ? dateTimeComponents!.simpleDateString() : nil } else if stepSubResult.identifier == DBSurveySleepHoursIdentifier { let numericQuestionResult = stepSubResult as! ORKNumericQuestionResult results[DBSurveySleepHoursIdentifier] = numericQuestionResult.answer != nil ? String(numericQuestionResult.answer!) : nil } else if stepSubResult.identifier == DBSurveySleepScoreIdentifier { let numericQuestionResult = stepSubResult as! ORKNumericQuestionResult results[DBSurveySleepScoreIdentifier] = numericQuestionResult.answer != nil ? String(numericQuestionResult.answer!) : nil } } } } return results } // MARK: Reusable components // Mood question func moodStep() -> ORKQuestionStep { let imageChoiceAwesome = ORKImageChoice(normalImage: UIImage(named: "grinning-face"), selectedImage: UIImage(named: "grinning-face"), text: "Awesome", value: "awesome") let imageChoiceOk = ORKImageChoice(normalImage: UIImage(named: "grimacing-face"), selectedImage: UIImage(named: "grimacing-face"), text: "Ok", value: "ok") let imageChoiceBad = ORKImageChoice(normalImage: UIImage(named: "expressionless-face"), selectedImage: UIImage(named: "expressionless-face"), text: "Bad", value: "bad") let imageChoiceTerrible = ORKImageChoice(normalImage: UIImage(named: "helpless-face"), selectedImage: UIImage(named: "helpless-face"), text: "Terrible", value: "terrible") let moodImages = ORKImageChoiceAnswerFormat(imageChoices: [imageChoiceAwesome, imageChoiceOk, imageChoiceBad, imageChoiceTerrible]) let moodStep = ORKQuestionStep(identifier: DBSurveyMoodIdentifier, title: "How do you feel?", answer: moodImages) return moodStep } // Stress question func stressStep() -> ORKQuestionStep { let imageChoiceNoStress = ORKImageChoice(normalImage: UIImage(named: "grinning-face"), selectedImage: UIImage(named: "grinning-face"), text: "No stress", value: "no_stress") let imageChoiceLittleStressed = ORKImageChoice(normalImage: UIImage(named: "grimacing-face"), selectedImage: UIImage(named: "grimacing-face"), text: "A little stressed", value: "little_stress") let imageChoiceStressed = ORKImageChoice(normalImage: UIImage(named: "expressionless-face"), selectedImage: UIImage(named: "expressionless-face"), text: "Stressed", value: "stressed") let imageChoiceReallyStressed = ORKImageChoice(normalImage: UIImage(named: "helpless-face"), selectedImage: UIImage(named: "helpless-face"), text: "Really stressed", value: "really_stressed") let stressImages = ORKImageChoiceAnswerFormat(imageChoices: [imageChoiceNoStress, imageChoiceLittleStressed, imageChoiceStressed, imageChoiceReallyStressed]) let stressStep = ORKQuestionStep(identifier: DBSurveyStressIdentifier, title: "How stressed do you feel?", answer: stressImages) return stressStep } // Returns a form with questions for body weight and body fat percentage steps. func bodyWeightAndFatPercentageStep() -> ORKFormStep { let step = ORKFormStep(identifier: DBSurveyWeightIdentifier, title: "Weight and Fat Percentage", text: "") let bodyWeight = ORKFormItem(identifier: DBSurveyBodyWeightIdentifier, text: "Weight", answerFormat: ORKHealthKitQuantityTypeAnswerFormat(quantityType: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!, unit: HKUnit.gramUnitWithMetricPrefix(HKMetricPrefix.Kilo), style: ORKNumericAnswerStyle.Decimal)) let bodyFat = ORKFormItem(identifier: DBSurveyBodyFatIdentifier, text: "Body Fat Percentage", answerFormat: ORKHealthKitQuantityTypeAnswerFormat(quantityType: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyFatPercentage)!, unit: HKUnit.percentUnit(), style: ORKNumericAnswerStyle.Decimal)) var stepItems: Array<ORKFormItem> = Array() stepItems.append(bodyWeight) stepItems.append(bodyFat) step.formItems = stepItems return step } // Returns a form with questions for blood pressure and heart rate func bloodPressureAndHeartRateStep() -> ORKFormStep { let step = ORKFormStep(identifier: DBSurveyHeartIdentifier, title: "Blood Pressure and Heart Rate", text: "") let heartRate = ORKFormItem(identifier: DBSurveyHeartRateIdentifier, text: "Heart Rate", answerFormat: ORKHealthKitQuantityTypeAnswerFormat(quantityType: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!, unit: HKUnit.countUnit().unitDividedByUnit(HKUnit.minuteUnit()), style: ORKNumericAnswerStyle.Integer)) let bloodPressureSection = ORKFormItem(sectionTitle: "Blood Pressure") let bloodPressureSystolic = ORKFormItem(identifier: DBSurveyBloodPressureSystolicIdentifier, text: "Systolic", answerFormat: ORKHealthKitQuantityTypeAnswerFormat(quantityType: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureSystolic)!, unit: HKUnit.millimeterOfMercuryUnit(), style: ORKNumericAnswerStyle.Integer)) let bloodPressureDiastolic = ORKFormItem(identifier: DBSurveyBloodPressureDiastrolicIdentifier, text: "Diastolic", answerFormat: ORKHealthKitQuantityTypeAnswerFormat(quantityType: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureDiastolic)!, unit: HKUnit.millimeterOfMercuryUnit(), style: ORKNumericAnswerStyle.Integer)) step.formItems = [heartRate, bloodPressureSection, bloodPressureSystolic, bloodPressureDiastolic] return step } // Boolean question about alcohol consumption func alcoholConsumptionStep() -> ORKFormStep { let step = ORKFormStep(identifier: DBSurveyAlcoholIdentifier, title: "Did you drink alcohol today?", text: "") let alcoholConsumption = ORKFormItem(identifier: DBSurveyAlcoholConsumptionIdentifier, text: "", answerFormat: ORKBooleanAnswerFormat()) step.formItems = [alcoholConsumption] return step } // Questions about how many steps were taken and whether a workout was done today func activityStep() -> ORKFormStep { let step = ORKFormStep(identifier: DBSurveyActivityIdentifier, title: "How active have you been today?", text: "") let stepCount = ORKFormItem(identifier: DBSurveyStepCountIdentifier, text: "Steps", answerFormat: ORKNumericAnswerFormat(style: ORKNumericAnswerStyle.Integer)) let workout = ORKFormItem(identifier: DBSurveyWorkoutIdentifier, text: "Workout", answerFormat: ORKBooleanAnswerFormat()) step.formItems = [stepCount, workout] return step } // Questions about when the user went to sleep, woke up, how many hours of sleep, and sleep score func sleepStep() -> ORKFormStep { let step = ORKFormStep(identifier: DBSurveySleepIdentifier, title: "How was your sleep last night?", text: "") let sleepStart = ORKFormItem(identifier: DBSurveySleepStartIdentifier, text: "Start", answerFormat: ORKTimeOfDayAnswerFormat()) let sleepEnd = ORKFormItem(identifier: DBSurveySleepEndIdentifier, text: "End", answerFormat: ORKTimeOfDayAnswerFormat()) let sleepHours = ORKFormItem(identifier: DBSurveySleepHoursIdentifier, text: "Hours", answerFormat: ORKNumericAnswerFormat(style: .Decimal)) sleepHours let sleepScore = ORKFormItem(identifier: DBSurveySleepScoreIdentifier, text: "Sleep Score", answerFormat: ORKNumericAnswerFormat(style: .Integer)) step.formItems = [sleepStart, sleepEnd, sleepHours, sleepScore] return step } // Step for taking a picture of the front body func frontBodyImageCaptureStep() -> ORKImageCaptureStep { let step = ORKImageCaptureStep(identifier: DBSurveyFrontBodyImageIdentifier) step.title = "Front Body" return step } // Step for taking a picture of the side body func sideBodyImageCaptureStep() -> ORKImageCaptureStep { let step = ORKImageCaptureStep(identifier: DBSurveySideBodyImageIdentifier) step.title = "Side Body" return step } // Step for taking a picture of the back body func backBodyImageCaptureStep() -> ORKImageCaptureStep { let step = ORKImageCaptureStep(identifier: DBSurveyBackBodyImageIdentifier) step.title = "Back Body" return step } }
58.54755
357
0.675724
e0fd6ecffee33d295a2083a01527c4c5f717e01a
404
import Foundation import TestsCommon @testable import TripKit class KvvProviderTests: TripKitProviderTestCase, TripKitProviderTestsDelegate { override var delegate: TripKitProviderTestsDelegate! { return self } var networkId: NetworkId { return .KVV } func initProvider(from authorizationData: AuthorizationData) -> NetworkProvider { return KvvProvider() } }
25.25
85
0.740099
d72c4feba8390a1ce7fdd685d6d60b14e3bd98f6
1,579
// main.swift // // 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- import Cocoa func main() { var num = 22 var str = "Hello world" //% self.expect("po num", substrs = ['22']) var arr = [1,2,3,4] var nsarr = NSMutableArray(array: arr) //% self.expect("po str", substrs = ['Hello world']) var clr = NSColor.red //% self.expect("po arr", substrs = ['1','2','3','4']) //% self.expect("po nsarr", substrs = ['1','2','3','4']) var nsobject = NSObject() //% self.expect("po clr", substrs = ['1 0 0 1']) # may change depending on OS/platform var any: Any = 1234 //% self.expect("po nsobject", substrs = ['<NSObject: 0x']) # may change depending on OS/platform //% self.expect("script lldb.frame.FindVariable('nsobject').GetObjectDescription()", substrs = ['<NSObject: 0x']) # may change depending on OS/platform var anyobject: AnyObject = 1234 as NSNumber //% self.expect("po any", substrs = ['1234']) var notification = Notification(name: Notification.Name(rawValue: "JustANotification"), object: nil) print("yay I am done!") //% self.expect("po notification", substrs=['JustANotification']) //% self.expect("po notification", matching=False, substrs=['super']) } main()
50.935484
153
0.639012
0a238d81f16bbf5c232d8f4bc89c04767b69183c
1,791
import Foundation /// `@Jsonable` is handy to decode data into JSON object structure using dictionary of `Swift`. @propertyWrapper public struct Jsonable: Codable { public var wrappedValue: Any public init(wrappedValue: Any) { self.wrappedValue = wrappedValue } public init(from decoder: Decoder) throws { if let container = try? decoder.singleValueContainer(), let value = try? container.decode(Anyable<DefaultOptions>.self).wrappedValue { self.wrappedValue = value return } if var container = try? decoder.unkeyedContainer() { var elements: [Any] = [] while !container.isAtEnd { if let value = try? container.decode(Jsonable.self).wrappedValue { elements.append(value) } } self.wrappedValue = elements return } if let container = try? decoder.container(keyedBy: AnyCodingKey.self), let value = try? container.decode([String: Any].self) { self.wrappedValue = value return } self.wrappedValue = NSNull() } public func encode(to encoder: Encoder) throws { if let any = wrappedValue as? AnyCodable { try any.encode(to: encoder) return } if let array = wrappedValue as? [Any] { var container = encoder.unkeyedContainer() try container.encode(array) return } if let dict = wrappedValue as? [String: Any] { var container = encoder.container(keyedBy: AnyCodingKey.self) try container.encode(dict) return } var container = encoder.singleValueContainer() try container.encodeNil() } }
35.82
142
0.588498
919210ef3024e115944562ac31ffcc28ae21237d
4,397
public class SingleComponentGaussianBlur: TwoStageOperation { public var blurRadiusInPixels:Float { didSet { let (sigma, downsamplingFactor) = sigmaAndDownsamplingForBlurRadius(blurRadiusInPixels, limit:8.0, override:overrideDownsamplingOptimization) sharedImageProcessingContext.runOperationAsynchronously { self.downsamplingFactor = downsamplingFactor let pixelRadius = pixelRadiusForBlurSigma(Double(sigma)) self.shader = crashOnShaderCompileFailure("GaussianBlur"){try sharedImageProcessingContext.programForVertexShader(vertexShaderForOptimizedGaussianBlurOfRadius(pixelRadius, sigma:Double(sigma)), fragmentShader:fragmentShaderForOptimizedSingleComponentGaussianBlurOfRadius(pixelRadius, sigma:Double(sigma)))} } } } public init() { blurRadiusInPixels = 2.0 let pixelRadius = pixelRadiusForBlurSigma(Double(blurRadiusInPixels)) let initialShader = crashOnShaderCompileFailure("GaussianBlur"){try sharedImageProcessingContext.programForVertexShader(vertexShaderForOptimizedGaussianBlurOfRadius(pixelRadius, sigma:2.0), fragmentShader:fragmentShaderForOptimizedSingleComponentGaussianBlurOfRadius(pixelRadius, sigma:2.0))} super.init(shader:initialShader, numberOfInputs:1) } } func fragmentShaderForOptimizedSingleComponentGaussianBlurOfRadius(_ radius:UInt, sigma:Double) -> String { guard (radius > 0) else { return PassthroughFragmentShader } let standardWeights = standardGaussianWeightsForRadius(radius, sigma:sigma) let numberOfOptimizedOffsets = min(radius / 2 + (radius % 2), 7) let trueNumberOfOptimizedOffsets = radius / 2 + (radius % 2) #if GLES var shaderString = "uniform sampler2D inputImageTexture;\n uniform highp float texelWidth;\n uniform highp float texelHeight;\n \n varying highp vec2 blurCoordinates[\(1 + (numberOfOptimizedOffsets * 2))];\n \n void main()\n {\n lowp float sum = 0.0;\n" #else var shaderString = "uniform sampler2D inputImageTexture;\n uniform float texelWidth;\n uniform float texelHeight;\n \n varying vec2 blurCoordinates[\(1 + (numberOfOptimizedOffsets * 2))];\n \n void main()\n {\n float sum = 0.0;\n" #endif // Inner texture loop shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[0]).r * \(standardWeights[0]);\n" for currentBlurCoordinateIndex in 0..<numberOfOptimizedOffsets { let firstWeight = standardWeights[Int(currentBlurCoordinateIndex * 2 + 1)] let secondWeight = standardWeights[Int(currentBlurCoordinateIndex * 2 + 2)] let optimizedWeight = firstWeight + secondWeight shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[\((currentBlurCoordinateIndex * 2) + 1)]).r * \(optimizedWeight);\n" shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[\((currentBlurCoordinateIndex * 2) + 2)]).r * \(optimizedWeight);\n" } // If the number of required samples exceeds the amount we can pass in via varyings, we have to do dependent texture reads in the fragment shader if (trueNumberOfOptimizedOffsets > numberOfOptimizedOffsets) { #if GLES shaderString += "highp vec2 singleStepOffset = vec2(texelWidth, texelHeight);\n" #else shaderString += "vec2 singleStepOffset = vec2(texelWidth, texelHeight);\n" #endif } for currentOverlowTextureRead in numberOfOptimizedOffsets..<trueNumberOfOptimizedOffsets { let firstWeight = standardWeights[Int(currentOverlowTextureRead * 2 + 1)]; let secondWeight = standardWeights[Int(currentOverlowTextureRead * 2 + 2)]; let optimizedWeight = firstWeight + secondWeight let optimizedOffset = (firstWeight * (Double(currentOverlowTextureRead) * 2.0 + 1.0) + secondWeight * (Double(currentOverlowTextureRead) * 2.0 + 2.0)) / optimizedWeight shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[0] + singleStepOffset * \(optimizedOffset)).r * \(optimizedWeight);\n" shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[0] - singleStepOffset * \(optimizedOffset)).r * \(optimizedWeight);\n" } shaderString += "gl_FragColor = vec4(sum, sum, sum, 1.0);\n }\n" return shaderString }
61.929577
322
0.718444
504fc089c9381d60fd16454505ba8ec3dbf17401
1,079
import Foundation import IrohaCrypto import SoraKeystore import SubstrateSdk final class EthereumSigner { let keystore: KeystoreProtocol let metaId: String let accountId: AccountId? let publicKeyData: Data init(keystore: KeystoreProtocol, ethereumAccountResponse: MetaEthereumAccountResponse) { self.keystore = keystore metaId = ethereumAccountResponse.metaId accountId = ethereumAccountResponse.isChainAccount ? ethereumAccountResponse.address : nil publicKeyData = ethereumAccountResponse.publicKey } func sign(hashedData: Data) throws -> IRSignatureProtocol { let tag = KeystoreTagV2.ethereumSecretKeyTagForMetaId(metaId, accountId: accountId) let secretKey = try keystore.fetchKey(for: tag) let keypairFactory = EcdsaKeypairFactory() let privateKey = try keypairFactory .createKeypairFromSeed(secretKey.miniSeed, chaincodeList: []) .privateKey() let signer = SECSigner(privateKey: privateKey) return try signer.sign(hashedData) } }
31.735294
98
0.725672
f51247f07c533cc1b396ad3dd352cf5e67a3126b
951
// // WeiboTests.swift // WeiboTests // // Created by 顾春华 on 2017/12/22. // Copyright © 2017年 leslie. All rights reserved. // import XCTest @testable import Weibo class WeiboTests: 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 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. } } }
25.702703
111
0.626709
dbd72192bc6ed1c5c98c581e839d608c72540b3d
571
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation public struct API { /// Whether to discard any errors when decoding optional properties public static var safeOptionalDecoding = false /// Whether to remove invalid elements instead of throwing when decoding arrays public static var safeArrayDecoding = false /// Used to encode Dates when uses as string params public static var dateEncodingFormatter = DateFormatter(formatString: "yyyy-MM-dd'T'HH:mm:ssZZZZZ") public static let version = "0.0.1" }
27.190476
103
0.737303
fb7b2401ac466ad1e04373a0d39e0f55addf6300
533
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // ImageReferenceProtocol is public protocol ImageReferenceProtocol : Codable { var publisher: String? { get set } var offer: String? { get set } var sku: String? { get set } var version: String? { get set } var virtualMachineImageId: String? { get set } }
38.071429
96
0.697936
265303bd87ca1c22ffabbf6e26f3c3ae7406970f
24,358
// // FlattenSpec.swift // ReactiveCocoa // // Created by Oleg Shnitko on 1/22/16. // Copyright © 2016 GitHub. All rights reserved. // import Result import Nimble import Quick import ReactiveCocoa private extension SignalType { typealias Pipe = (signal: Signal<Value, Error>, observer: Observer<Value, Error>) } private typealias Pipe = Signal<SignalProducer<Int, TestError>, TestError>.Pipe class FlattenSpec: QuickSpec { override func spec() { func describeSignalFlattenDisposal(flattenStrategy: FlattenStrategy, name: String) { describe(name) { var pipe: Pipe! var disposable: Disposable? beforeEach { pipe = Signal.pipe() disposable = pipe.signal .flatten(flattenStrategy) .observe { _ in } } afterEach { disposable?.dispose() } context("disposal") { var disposed = false beforeEach { disposed = false pipe.observer.sendNext(SignalProducer<Int, TestError> { _, disposable in disposable += ActionDisposable { disposed = true } }) } it("should dispose inner signals when outer signal interrupted") { pipe.observer.sendInterrupted() expect(disposed) == true } it("should dispose inner signals when outer signal failed") { pipe.observer.sendFailed(.Default) expect(disposed) == true } it("should not dispose inner signals when outer signal completed") { pipe.observer.sendCompleted() expect(disposed) == false } } } } context("Signal") { describeSignalFlattenDisposal(.Latest, name: "switchToLatest") describeSignalFlattenDisposal(.Merge, name: "merge") describeSignalFlattenDisposal(.Concat, name: "concat") } func describeSignalProducerFlattenDisposal(flattenStrategy: FlattenStrategy, name: String) { describe(name) { it("disposes original signal when result signal interrupted") { var disposed = false let disposable = SignalProducer<SignalProducer<(), NoError>, NoError> { _, disposable in disposable += ActionDisposable { disposed = true } } .flatten(flattenStrategy) .start() disposable.dispose() expect(disposed) == true } } } context("SignalProducer") { describeSignalProducerFlattenDisposal(.Latest, name: "switchToLatest") describeSignalProducerFlattenDisposal(.Merge, name: "merge") describeSignalProducerFlattenDisposal(.Concat, name: "concat") } describe("Signal.flatten()") { it("works with TestError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = Signal<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = Signal<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = Signal<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = Signal<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = Signal<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = Signal<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = Signal<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = Signal<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with SequenceType as a value") { let (signal, innerObserver) = Signal<[Int], NoError>.pipe() let sequence = [1, 2, 3] var observedValues = [Int]() signal .flatten(.Concat) .observeNext { value in observedValues.append(value) } innerObserver.sendNext(sequence) expect(observedValues) == sequence } } describe("SignalProducer.flatten()") { it("works with TestError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = SignalProducer<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = SignalProducer<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = SignalProducer<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = SignalProducer<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = SignalProducer<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = SignalProducer<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = SignalProducer<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = SignalProducer<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with SequenceType as a value") { let sequence = [1, 2, 3] var observedValues = [Int]() let producer = SignalProducer<[Int], NoError>(value: sequence) producer .flatten(.Latest) .startWithNext { value in observedValues.append(value) } expect(observedValues) == sequence } } describe("Signal.flatMap()") { it("works with TestError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = Signal<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = Signal<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = Signal<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = Signal<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = Signal<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = Signal<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = Signal<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = Signal<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } } describe("SignalProducer.flatMap()") { it("works with TestError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = SignalProducer<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = SignalProducer<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = SignalProducer<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = SignalProducer<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = SignalProducer<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = SignalProducer<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = SignalProducer<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = SignalProducer<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .assumeNoErrors() .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } } describe("Signal.merge()") { it("should emit values from all signals") { let (signal1, observer1) = Signal<Int, NoError>.pipe() let (signal2, observer2) = Signal<Int, NoError>.pipe() let mergedSignals = Signal.merge([signal1, signal2]) var lastValue: Int? mergedSignals.observeNext { lastValue = $0 } expect(lastValue).to(beNil()) observer1.sendNext(1) expect(lastValue) == 1 observer2.sendNext(2) expect(lastValue) == 2 observer1.sendNext(3) expect(lastValue) == 3 } it("should not stop when one signal completes") { let (signal1, observer1) = Signal<Int, NoError>.pipe() let (signal2, observer2) = Signal<Int, NoError>.pipe() let mergedSignals = Signal.merge([signal1, signal2]) var lastValue: Int? mergedSignals.observeNext { lastValue = $0 } expect(lastValue).to(beNil()) observer1.sendNext(1) expect(lastValue) == 1 observer1.sendCompleted() expect(lastValue) == 1 observer2.sendNext(2) expect(lastValue) == 2 } it("should complete when all signals complete") { let (signal1, observer1) = Signal<Int, NoError>.pipe() let (signal2, observer2) = Signal<Int, NoError>.pipe() let mergedSignals = Signal.merge([signal1, signal2]) var completed = false mergedSignals.observeCompleted { completed = true } expect(completed) == false observer1.sendNext(1) expect(completed) == false observer1.sendCompleted() expect(completed) == false observer2.sendCompleted() expect(completed) == true } } describe("SignalProducer.merge()") { it("should emit values from all producers") { let (signal1, observer1) = SignalProducer<Int, NoError>.pipe() let (signal2, observer2) = SignalProducer<Int, NoError>.pipe() let mergedSignals = SignalProducer.merge([signal1, signal2]) var lastValue: Int? mergedSignals.startWithNext { lastValue = $0 } expect(lastValue).to(beNil()) observer1.sendNext(1) expect(lastValue) == 1 observer2.sendNext(2) expect(lastValue) == 2 observer1.sendNext(3) expect(lastValue) == 3 } it("should not stop when one producer completes") { let (signal1, observer1) = SignalProducer<Int, NoError>.pipe() let (signal2, observer2) = SignalProducer<Int, NoError>.pipe() let mergedSignals = SignalProducer.merge([signal1, signal2]) var lastValue: Int? mergedSignals.startWithNext { lastValue = $0 } expect(lastValue).to(beNil()) observer1.sendNext(1) expect(lastValue) == 1 observer1.sendCompleted() expect(lastValue) == 1 observer2.sendNext(2) expect(lastValue) == 2 } it("should complete when all producers complete") { let (signal1, observer1) = SignalProducer<Int, NoError>.pipe() let (signal2, observer2) = SignalProducer<Int, NoError>.pipe() let mergedSignals = SignalProducer.merge([signal1, signal2]) var completed = false mergedSignals.startWithCompleted { completed = true } expect(completed) == false observer1.sendNext(1) expect(completed) == false observer1.sendCompleted() expect(completed) == false observer2.sendCompleted() expect(completed) == true } } describe("SignalProducer.prefix()") { it("should emit initial value") { let (signal, observer) = SignalProducer<Int, NoError>.pipe() let mergedSignals = signal.prefix(value: 0) var lastValue: Int? mergedSignals.startWithNext { lastValue = $0 } expect(lastValue) == 0 observer.sendNext(1) expect(lastValue) == 1 observer.sendNext(2) expect(lastValue) == 2 observer.sendNext(3) expect(lastValue) == 3 } it("should emit initial value") { let (signal, observer) = SignalProducer<Int, NoError>.pipe() let mergedSignals = signal.prefix(SignalProducer(value: 0)) var lastValue: Int? mergedSignals.startWithNext { lastValue = $0 } expect(lastValue) == 0 observer.sendNext(1) expect(lastValue) == 1 observer.sendNext(2) expect(lastValue) == 2 observer.sendNext(3) expect(lastValue) == 3 } } describe("SignalProducer.concat(value:)") { it("should emit final value") { let (signal, observer) = SignalProducer<Int, NoError>.pipe() let mergedSignals = signal.concat(value: 4) var lastValue: Int? mergedSignals.startWithNext { lastValue = $0 } observer.sendNext(1) expect(lastValue) == 1 observer.sendNext(2) expect(lastValue) == 2 observer.sendNext(3) expect(lastValue) == 3 observer.sendCompleted() expect(lastValue) == 4 } } } }
25.267635
94
0.629198
164d89c861d8900e6bfba1aef548075fa0853e3f
1,020
// // SheetExperimentsView.swift // SwiftUIPrototype // // Created by Jon Shier on 9/16/19. // Copyright © 2019 Jon Shier. All rights reserved. // import SwiftUI struct SheetExperimentsView: View { @EnvironmentObject var appState: SheetState var body: some View { VStack { Button(action: { self.appState.needsCity = true }) { Text("Set City") } .sheet(isPresented: $appState.needsCity, onDismiss: { self.appState.needsCity = false }) { LoginView(city: self.$appState.city) } Button(action: { self.appState.needsState = true }) { Text("Set State") } .sheet(isPresented: $appState.needsState, onDismiss: { self.appState.needsState = false }) { LoginView(city: self.$appState.state) } } } } struct SheetExperimentsView_Previews: PreviewProvider { static var previews: some View { SheetExperimentsView() } }
27.567568
104
0.583333
79de9ee79e5c43038940cd3b9c9e3d9cbd0a63a5
8,980
// // PicguardSpec.swift // // Copyright (c) 2016 Netguru Sp. z o.o. All rights reserved. // Licensed under the MIT License. // import Nimble import Quick import Picguard final class PicguardSpec: QuickSpec { override func spec() { describe("Picguard") { var caughtRequest: AnnotationRequest? = nil var mockedResult: PicguardResult<AnnotationResponse>! = nil let picguard = Picguard(APIClient: MockAPIClient { request, completion in caughtRequest = request completion(mockedResult) }) afterEach { mockedResult = nil } context("when initialized with an API key") { let picguard = Picguard(APIKey: "foobar") it("should have a default API client") { expect(picguard.client.dynamicType == APIClient.self).to(beTruthy()) } it("should forward API key to API client") { let client = picguard.client as? APIClient expect(client?.APIKey).to(equal("foobar")) } } describe("unsafe content likelihood detection") { beforeEach { mockedResult = .Success(AnnotationResponse( faceAnnotations: nil, labelAnnotations: nil, landmarkAnnotations: nil, logoAnnotations: nil, textAnnotations: nil, safeSearchAnnotation: nil, imagePropertiesAnnotation: nil )) } it("should send a correct request") { picguard.detectUnsafeContentLikelihood(image: .URL(""), completion: { _ in }) let expectedRequest = try! AnnotationRequest(features: [.SafeSearch], image: .URL("")) expect(caughtRequest).toEventually(equal(expectedRequest)) } context("given a response containing safe search annotation") { let annotation = SafeSearchAnnotation( adultContentLikelihood: .Possible, spoofContentLikelihood: .Likely, medicalContentLikelihood: .VeryUnlikely, violentContentLikelihood: .Likely ) beforeEach { mockedResult = .Success(AnnotationResponse( faceAnnotations: nil, labelAnnotations: nil, landmarkAnnotations: nil, logoAnnotations: nil, textAnnotations: nil, safeSearchAnnotation: annotation, imagePropertiesAnnotation: nil )) } it("should calculate a correct positive likelihood") { var caughtResult: PicguardResult<Likelihood>! = nil picguard.detectUnsafeContentLikelihood(image: .URL(""), completion: { caughtResult = $0 }) expect(caughtResult).toEventually(beSuccessful(annotation.unsafeContentLikelihood)) } } context("given a response containing no safe search annotations") { beforeEach { mockedResult = .Success(AnnotationResponse( faceAnnotations: nil, labelAnnotations: nil, landmarkAnnotations: nil, logoAnnotations: nil, textAnnotations: nil, safeSearchAnnotation: nil, imagePropertiesAnnotation: nil )) } it("should calculate unknown likelihood") { var caughtResult: PicguardResult<Likelihood>! = nil picguard.detectUnsafeContentLikelihood(image: .URL(""), completion: { caughtResult = $0 }) expect(caughtResult).toEventually(beSuccessful(Likelihood.Unknown)) } } context("given an erroneus response") { beforeEach { mockedResult = .Error(AnnotationError(code: 0, message: "")) } it("should forward an erroneus response") { var caughtResult: PicguardResult<Likelihood>! = nil picguard.detectUnsafeContentLikelihood(image: .URL(""), completion: { caughtResult = $0 }) expect(caughtResult).toEventually(beErroneus()) } } } describe("face presence likelihood detection") { beforeEach { mockedResult = .Success(AnnotationResponse( faceAnnotations: nil, labelAnnotations: nil, landmarkAnnotations: nil, logoAnnotations: nil, textAnnotations: nil, safeSearchAnnotation: nil, imagePropertiesAnnotation: nil )) } it("should send a correct request") { picguard.detectFacePresenceLikelihood(image: .Base64String(""), completion: { _ in }) let expectedRequest = try! AnnotationRequest(features: [.Face(maxResults: 1)], image: .Base64String("")) expect(caughtRequest).toEventually(equal(expectedRequest)) } context("given a response containing face annotation") { let annotation = try! FaceAnnotation( boundingPolygon: BoundingPolygon(vertices: []), skinBoundingPolygon: BoundingPolygon(vertices: []), landmarks: [], rollAngle: 0, panAngle: 0, tiltAngle: 0, detectionConfidence: 0.75, landmarkingConfidence: 0.5, joyLikelihood: .Unknown, sorrowLikelihood: .Unknown, angerLikelihood: .Unknown, surpriseLikelihood: .Unknown, underExposedLikelihood: .Unknown, blurredLikelihood: .Unknown, headwearLikelihood: .Unknown ) beforeEach { mockedResult = .Success(AnnotationResponse( faceAnnotations: [annotation], labelAnnotations: nil, landmarkAnnotations: nil, logoAnnotations: nil, textAnnotations: nil, safeSearchAnnotation: nil, imagePropertiesAnnotation: nil )) } it("should calculate a correct positive likelihood") { var caughtResult: PicguardResult<Likelihood>! = nil picguard.detectFacePresenceLikelihood(image: .Base64String(""), completion: { caughtResult = $0 }) expect(caughtResult).toEventually(beSuccessful(try! Likelihood(score: annotation.detectionConfidence))) } } context("given a response containing no face annotations") { beforeEach { mockedResult = .Success(AnnotationResponse( faceAnnotations: [], labelAnnotations: nil, landmarkAnnotations: nil, logoAnnotations: nil, textAnnotations: nil, safeSearchAnnotation: nil, imagePropertiesAnnotation: nil )) } it("should calculate unknown likelihood") { var caughtResult: PicguardResult<Likelihood>! = nil picguard.detectFacePresenceLikelihood(image: .Base64String(""), completion: { caughtResult = $0 }) expect(caughtResult).toEventually(beSuccessful(Likelihood.Unknown)) } } context("given an erroneus response") { beforeEach { mockedResult = .Error(AnnotationError(code: 0, message: "")) } it("should forward an erroneus response") { var caughtResult: PicguardResult<Likelihood>! = nil picguard.detectFacePresenceLikelihood(image: .Base64String(""), completion: { caughtResult = $0 }) expect(caughtResult).toEventually(beErroneus()) } } } describe("raw annotation") { beforeEach { mockedResult = .Success(AnnotationResponse( faceAnnotations: nil, labelAnnotations: nil, landmarkAnnotations: nil, logoAnnotations: nil, textAnnotations: nil, safeSearchAnnotation: nil, imagePropertiesAnnotation: nil )) } it("should send a correct request") { picguard.annotate(image: .Base64String(""), features: [.Label(maxResults: 1)], completion: { _ in }) let expectedRequest = try! AnnotationRequest(features: [.Label(maxResults: 1)], image: .Base64String("")) expect(caughtRequest).toEventually(equal(expectedRequest)) } context("given a successful response") { let response = AnnotationResponse( faceAnnotations: nil, labelAnnotations: nil, landmarkAnnotations: nil, logoAnnotations: nil, textAnnotations: nil, safeSearchAnnotation: nil, imagePropertiesAnnotation: nil ) beforeEach { mockedResult = .Success(response) } it("should calculate a correct positive likelihood") { var caughtResult: PicguardResult<AnnotationResponse>! = nil picguard.annotate(image: .Base64String(""), features: [.Landmark(maxResults: 1)], completion: { caughtResult = $0 }) expect(caughtResult).toEventually(beSuccessful(response)) } } context("given an erroneus response") { beforeEach { mockedResult = .Error(AnnotationError(code: 0, message: "")) } it("should forward an erroneus response") { var caughtResult: PicguardResult<AnnotationResponse>! = nil picguard.annotate(image: .Base64String(""), features: [.Text], completion: { caughtResult = $0 }) expect(caughtResult).toEventually(beErroneus()) } } } } } } // MARK: - private final class MockAPIClient: APIClientType { private typealias PerformRequestClosureType = (AnnotationRequest, (PicguardResult<AnnotationResponse>) -> Void) -> Void private let performRequestClosure: PerformRequestClosureType private init(_ performRequestClosure: PerformRequestClosureType) { self.performRequestClosure = performRequestClosure } private func perform(request request: AnnotationRequest, completion: (PicguardResult<AnnotationResponse>) -> Void) { performRequestClosure(request, completion) } }
28.690096
122
0.677728
085835f668d5c7a2c911abee0bc6d4c02dbd0dee
10,886
// // TabViewRootController.swift // TabView // // Created by Ian McDowell on 2/6/18. // Copyright © 2018 Ian McDowell. All rights reserved. // import UIKit /// Represents the state of a tab view container. /// Access the value of this using the `state` property. public enum TabViewContainerState { /// There is a single tab view controller visible case single /// The container is split horizontally, with a secondary tab view controller on the right. case split } /// Internal protocol that the TabViewContainerViewController conforms to, /// so other objects and reference it without knowing its generic type. internal protocol TabViewContainer: class { /// Get the current state of the container var state: TabViewContainerState { get set } /// Get the primary tab view controller var primary: TabViewController { get } /// Get the secondary tab view controller, if there is one var secondary: TabViewController? { get } /// When a tab collection view starts dragging in either side, the container is alerted. /// This is done so the container can potentially enable a drop area to enter split view. func dragStateChanged(in tabViewController: TabViewController, to newDragState: Bool) /// Sets the inset of the stack view. This is done by the drop target when the user is hovering /// over the right side. var contentViewRightInset: CGFloat { get set } } /// A tab view container view controller manages the display of tab view controllers. /// It can be in various states, as noted by its `state` property. /// It's not required that you embed a tab view controller in a container, but if you want /// the ability to go into split view, this is the suggested class to use. open class TabViewContainerViewController<TabViewType: TabViewController>: UIViewController { /// The current state of the container. Set this to manually change states. public var state: TabViewContainerState { didSet { switch state { case .single: secondaryTabViewController = nil setOverrideTraitCollection(nil, forChild: primaryTabViewController) case .split: let secondaryVC = TabViewType.init(theme: self.theme) // Override trait collection to be always compact horizontally, while in split mode let overriddenTraitCollection = UITraitCollection.init(traitsFrom: [ self.traitCollection, UITraitCollection.init(horizontalSizeClass: .compact) ]) setOverrideTraitCollection(overriddenTraitCollection, forChild: primaryTabViewController) setOverrideTraitCollection(overriddenTraitCollection, forChild: secondaryVC) self.secondaryTabViewController = secondaryVC } } } /// Current theme. When set, will propagate to current tab view controllers. public var theme: TabViewTheme { didSet { applyTheme(theme) } } /// A view displayed underneath the stack view, which has a background color set to the theme's border color. /// This is a relatively hacky way to display a separator when in split state. private let backgroundView: UIView /// Stack view containing visible tab view controllers. private let stackView: UIStackView /// The primary tab view controller in the container. This view controller will always be visible, /// no matter the state. public let primaryTabViewController: TabViewType /// The secondary tab view controller in the container. Is visible if the container is in split view. public private(set) var secondaryTabViewController: TabViewType? { didSet { oldValue?.view.removeFromSuperview() oldValue?.removeFromParent() if let newValue = secondaryTabViewController { newValue.container = self addChild(newValue) stackView.addArrangedSubview(newValue.view) newValue.didMove(toParent: self) } } } /// Constraint governing the trailing position of the stack view. /// This is adjusted when using drag and drop, to make a drop area /// visible to enter split mode. private var stackViewRightConstraint: NSLayoutConstraint? /// A UIView that is used for drag and drop. private let dropView = TabViewContainerDropView() /// Create a new tab view container view controller with the given theme /// This creates a tab view controller of the given type. /// The container starts in the `single` style. public init(theme: TabViewTheme) { self.state = .single self.theme = theme self.primaryTabViewController = TabViewType.init(theme: theme) self.secondaryTabViewController = nil self.stackView = UIStackView() self.backgroundView = UIView() super.init(nibName: nil, bundle: nil) dropView.container = self primaryTabViewController.container = self addChild(primaryTabViewController) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() backgroundView.frame = stackView.bounds backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] stackView.addSubview(backgroundView) // Stack view fills frame stackView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(stackView) let trailingConstraint = stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0) self.stackViewRightConstraint = trailingConstraint NSLayoutConstraint.activate([ trailingConstraint, stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor), stackView.topAnchor.constraint(equalTo: view.topAnchor), stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) stackView.distribution = .fillEqually stackView.axis = .horizontal stackView.alignment = .fill stackView.spacing = 0.5 stackView.insertArrangedSubview(primaryTabViewController.view, at: 0) primaryTabViewController.didMove(toParent: self) applyTheme(theme) } private func applyTheme(_ theme: TabViewTheme) { view.backgroundColor = theme.barTintColor backgroundView.backgroundColor = theme.separatorColor setNeedsStatusBarAppearanceUpdate() primaryTabViewController.theme = theme secondaryTabViewController?.theme = theme } open override var preferredStatusBarStyle: UIStatusBarStyle { return theme.statusBarStyle } } /// This transparent view is displayed on the trailing side of the container, only when a drag and drop session is active. /// It is the droppable region that a tab can be dropped into. class TabViewContainerDropView: UIView, UIDropInteractionDelegate { /// Reference to the container view controller weak var container: TabViewContainer? init() { super.init(frame: .zero) let dropInteraction = UIDropInteraction(delegate: self) addInteraction(dropInteraction) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Only handle tabs public func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool { guard let localSession = session.localDragSession, let localObject = localSession.items.first?.localObject else { return false } let canHandle = localObject is UIViewController return canHandle } // When the finger enters our view, move the stack view away func dropInteraction(_ interaction: UIDropInteraction, sessionDidEnter session: UIDropSession) { container?.contentViewRightInset = 140 } // When finger leaves, reset stack view. func dropInteraction(_ interaction: UIDropInteraction, sessionDidExit session: UIDropSession) { container?.contentViewRightInset = 0 } func dropInteraction(_ interaction: UIDropInteraction, sessionDidEnd session: UIDropSession) { container?.contentViewRightInset = 0 } func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal { return UIDropProposal.init(operation: .move) } func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) { guard let container = self.container, let dragItem = session.localDragSession?.items.first, let viewController = dragItem.localObject as? UIViewController else { return } // Move the dropped view controller into a new secondary tab view controller. container.contentViewRightInset = 0 container.state = .split container.primary.closeTab(viewController) container.secondary?.viewControllers = [viewController] } } /// Conform to the TabViewContainer protocol, which other objects (such as TabViewContainerDropView and TabViewController) talk to. extension TabViewContainerViewController: TabViewContainer { var contentViewRightInset: CGFloat { get { return -(stackViewRightConstraint?.constant ?? 0) } set { stackViewRightConstraint?.constant = -newValue UIView.animate(withDuration: 0.2) { self.view.layoutIfNeeded() } } } var primary: TabViewController { return primaryTabViewController } var secondary: TabViewController? { return secondaryTabViewController } func dragStateChanged(in tabViewController: TabViewController, to newDragState: Bool) { // If the given tab is the primary, there is no secondary, and started dragging, then show the drop view. // Otherwise, remove the drop view. if shouldEnableDropView && newDragState == true && state == .single && tabViewController == primaryTabViewController { dropView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(dropView) NSLayoutConstraint.activate([ dropView.trailingAnchor.constraint(equalTo: view.trailingAnchor), dropView.topAnchor.constraint(equalTo: view.topAnchor), dropView.bottomAnchor.constraint(equalTo: view.bottomAnchor), dropView.widthAnchor.constraint(equalToConstant: 100) ]) } else { dropView.removeFromSuperview() } } private var shouldEnableDropView: Bool { return self.traitCollection.horizontalSizeClass == .regular } }
40.468401
136
0.692816
38c7e9d4e6408468fd3093be90abec342f60f831
2,085
// // AppDelegate.swift // iOS Example // // Created by Louis D'hauwe on 25/05/2018. // Copyright © 2018 Silver Fox. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: 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:. } }
44.361702
279
0.788489
8a6c83582c3e0ce53798f8d3f204362b32a15ce0
2,806
// // ProgressView.swift // SwiftUICustom // // Created by Jack Rosen on 6/30/21. // import Foundation public struct ProgressView<Label: View, CurrentValueLabel: View>: View { let progress: Float? let label: Label let currentValueLabel: CurrentValueLabel public init(@ViewBuilder label: () -> Label) where CurrentValueLabel == EmptyView { self.progress = nil self.currentValueLabel = EmptyView() self.label = label() } public init() where Label == EmptyView, CurrentValueLabel == EmptyView { self = ProgressView(label: { EmptyView() }) } public init<V>(value: V?, total: V = 1.0) where Label == EmptyView, CurrentValueLabel == EmptyView, V : BinaryFloatingPoint { self = ProgressView(value: value, total: total, label: { EmptyView() }, currentValueLabel: { EmptyView() }) } public init<V>(value: V?, total: V = 1.0, @ViewBuilder label: () -> Label, @ViewBuilder currentValueLabel: () -> CurrentValueLabel) where V : BinaryFloatingPoint { self.label = label() self.currentValueLabel = currentValueLabel() self.progress = value.map { $0 / total }.map(Float.init) } public var body: VStack<TupleView<(Label, ConditionalContent<UIProgressRepresentable, ActivityIndicator>, CurrentValueLabel)>> { VStack { self.label if let progress = progress { UIProgressRepresentable(progress: progress) } else { ActivityIndicator() } self.currentValueLabel } } public func _makeSequence(currentNode: DOMNode) -> _ViewSequence { return _ViewSequence(count: 1, viewGetter: {_, node in (_BuildingBlockRepresentable(buildingBlock: self), node)}) } } public struct ActivityIndicator: UIViewRepresentable { public typealias UIViewType = UIActivityIndicatorView public func makeUIView(context: Context) -> UIActivityIndicatorView { let indicator = UIActivityIndicatorView(style: .gray) indicator.translatesAutoresizingMaskIntoConstraints = false return indicator } public func updateUIView(_ view: UIActivityIndicatorView, context: Context) { // Do nothing } } public struct UIProgressRepresentable: UIViewRepresentable { public typealias UIViewType = UIProgressView let progress: Float public func makeUIView(context: Context) -> UIProgressView { let progressView = UIProgressView(progressViewStyle: .bar) progressView.translatesAutoresizingMaskIntoConstraints = false progressView.progress = progress return progressView } public func updateUIView(_ view: UIProgressView, context: Context) { view.progress = progress } }
35.075
167
0.66536
f475626b80c9e7d396b220967b17fecdfa923869
2,174
// // AppDelegate.swift // DagoComponents // // Created by douwebos on 09/29/2021. // Copyright (c) 2021 douwebos. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: 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 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:. } }
46.255319
285
0.75483
3930481774c050c41ef6aa74078dc0666432111b
1,429
// // ExcerciseCatsUITests.swift // ExcerciseCatsUITests // // Created by Jim Campagno on 2/21/21. // import XCTest class ExcerciseCatsUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
33.232558
182
0.659202