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
8990c877c39ecb92efb16ec64dbd01c1e0557c9c
809
// // ChangeVariableBolusPumpEvent.swift // RileyLink // // Created by Pete Schwamb on 3/8/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public struct ChangeVariableBolusPumpEvent: TimestampedPumpEvent { public let length: Int public let rawData: Data public let timestamp: DateComponents public init?(availableData: Data, pumpModel: PumpModel) { length = 7 guard length <= availableData.count else { return nil } rawData = availableData.subdata(in: 0..<length) timestamp = DateComponents(pumpEventData: availableData, offset: 2) } public var dictionaryRepresentation: [String: Any] { return [ "_type": "ChangeVariableBolus", ] } }
23.794118
75
0.634116
72a71388ce950b58407b250f0ee4c4af895dfff5
409
// // Enum+Additions.swift // Pods // // Created by Dennis Pashkov on 10/3/16. // // extension Enum { public override var hash: Int { return Int(self.rawValue) } public override func isEqual(_ object: Any?) -> Bool { guard let otherObject = object as? Enum else { return false } return self.rawValue == otherObject.rawValue } }
17.782609
69
0.564792
d567e1cc0afc54c9cd88fda290f2e989d3929be6
214
// // Product+CoreDataClass.swift // Persistencia // // Created by Henrique Matheus Alves Pereira on 13/04/21. // // import Foundation import CoreData @objc(Product) public class Product: NSManagedObject { }
13.375
58
0.724299
1420ad187555af72dd9455454a8df1c572451f10
781
import UIKit class AnimationButtonViewController: UIViewController { private var leftButtons: [UIButton] = [UIButton(),UIButton(),UIButton(),UIButton(),UIButton()] private var rightButtons: [UIButton] = [UIButton(),UIButton(),UIButton(),UIButton(),UIButton()] override func viewDidLoad() { super.viewDidLoad() } private func round(){ for button in leftButtons { button.layer.cornerRadius = button.frame.width / 2 } for button in rightButtons { button.layer.cornerRadius = button.frame.width / 2 } } private func colorSet(){ for button in leftButtons { button.layer.cornerRadius = button.frame.width / 2 } for button in rightButtons { button.layer.cornerRadius = button.frame.width / 2 } } }
25.193548
97
0.670935
e8ff8f3a555d077e4d7e0d0d4c2ff63d14947a25
671
// // XParser.swift // Bookbinder // // Created by Stone Zhang on 5/1/19. // Copyright © 2019 Stone Zhang. All rights reserved. // import Foundation public enum XPath { case opf case dc case ncx case container public var namespace: [String: String] { switch self { case .opf: return ["opf": "http://www.idpf.org/2007/opf"] case .dc: return ["dc": "http://purl.org/dc/elements/1.1/"] case .ncx: return ["ncx": "http://www.daisy.org/z3986/2005/ncx/"] case .container: return ["container": "urn:oasis:names:tc:opendocument:xmlns:container"] } } }
22.366667
83
0.561848
50044f0da55877667850a5b4ff498024fdaa3468
4,656
// // IoCTests.swift // IoCTests // // Created by Ondrej Pisin on 21/08/2020. // Copyright © 2020 Ondrej Pisin. All rights reserved. // import XCTest @testable import LightIoC class IoCReferencesTests: XCTestCase { @Dependency private var typeService: TypeService @Dependency private var lazySingletonService: LazySingletonService @Dependency private var singletonService: SingletonService @Dependency private var notReferencedService: NotReferencedService override func setUpWithError() throws { IoC.register(module: ReferenceTestModule()) } override func tearDownWithError() throws { IoCInternal.clean() } func testReferencesForRegisterSingletonAreEaqual() { let s1 = (typeService as? Type)?.singleton let s2 = (typeService as? Type)?.singleton XCTAssertNotNil(s1) XCTAssertNotNil(s2) XCTAssertEqual(s1!.id, s2!.id) } func testReferencesForRegisterLazySingletonAreEaqual() { let l1 = (typeService as? Type)?.lazySingleton let l2 = (typeService as? Type)?.lazySingleton XCTAssertNotNil(l1) XCTAssertNotNil(l2) XCTAssertEqual(l1!.id, l2!.id) } func testReferencesForRegisterByTypeAreNotEaqual() { let t1 = typeService as? Type let t2 = typeService as? Type XCTAssertNotNil(t1) XCTAssertNotNil(t2) XCTAssertNotEqual(t1!.id, t2!.id) } func testLazySingletonNotInitializedEarly() { XCTAssertNil(_lazySingletonService.initialized) XCTAssertNotNil(lazySingletonService) XCTAssertTrue(_lazySingletonService.initialized ?? false) } func testCleanDoesCleanAllReferences() { IoCInternal.clean() XCTAssertTrue(IoCInternal.allKeys.count == 0) } func testValidationsucceedOnAlreadyRegisteredObjects() { XCTAssertTrue(IoCInternal.validate(type: ObjectIdentifier(SingletonService.self))) XCTAssertTrue(IoCInternal.validate(type: ObjectIdentifier(LazySingletonService.self))) XCTAssertTrue(IoCInternal.validate(type: ObjectIdentifier(TypeService.self))) } func testValidationFailsOnNotRegisteredObjects() { XCTAssertFalse(IoCInternal.validate(type: ObjectIdentifier(NotReferencedService.self))) } func testNotRegisteredTypeFailsToResolve() { do { let _ = try IoCInternal.resolve(NotReferencedService.self) } catch { print(error.localizedDescription) guard case IoCError.notRegistered(_) = error else { return XCTFail() } return } XCTFail() } func testNotRegisteredWrapperFailsToResolve() { do { let _ = try IoCInternal.resolve(_notReferencedService) } catch { print(error.localizedDescription) guard case IoCError.notRegistered(_) = error else { return XCTFail() } return } XCTFail() } func testNotRegisteredWrapperInnerValueFailsToResolve() { expectFatalError(expectedMessage: "IoC fatal error: \(IoCError.notRegistered(NotReferencedService.self).localizedDescription)") { let _ = self.notReferencedService } } func testThreadSafeResolve() { let dg = DispatchGroup() let exp = expectation(description: "\(#function)\(#line)") DispatchQueue.concurrentPerform(iterations: 10) { (index) in dg.enter() DispatchQueue.global().async { for _ in 0..<10000 { do { let _ = try IoCInternal.resolve(SingletonService.self) let _ = try IoCInternal.resolve(self._singletonService) let _ = try IoCInternal.resolve(LazySingletonService.self) let _ = try IoCInternal.resolve(self._lazySingletonService) let _ = try IoCInternal.resolve(TypeService.self) let _ = try IoCInternal.resolve(self._typeService) } catch { XCTFail(error.localizedDescription) } } dg.leave() } } dg.notify(queue: DispatchQueue.main) { exp.fulfill() } self.waitForExpectations(timeout: 30, handler: nil) } }
31.673469
137
0.59579
3976e904ff90c6e0f1eeeb4cb2d00d9bace8c57e
3,830
import Foundation struct Day19: Day { static func run(input: String) { let computer = IntCodeComputer(instructions: .parse(rawValue: input)) let beam = Beam(computer: computer) print("The number of tracted areas for Day 19-1 is \(beam.count(for: 50))") let point = beam.fitSquare(of: 100) print("Closest point of beam to fit the square for Day 19-2 is \(point) ; (Answer: \(point.x * 10_000 + point.y))") } struct Beam { let computer: IntCodeComputer func count(for size: Int) -> Int { var count = 0 var pos = Vector2D.zero var firstColumn: Int? while pos.x < size && pos.y < size { guard let output = computer.withInput(pos.x, pos.y).runned().outputs.first else { fatalError("No output") } switch output { case 0: if firstColumn != nil { pos.x = firstColumn! pos.y += 1 firstColumn = nil } case 1: count += 1 if firstColumn == nil { firstColumn = pos.x } default: fatalError("Unknown output") } pos.x += 1 if pos.x >= size { pos.x = firstColumn ?? 0 pos.y += 1 firstColumn = nil } } return count } func fitSquare(of targetSize: Int) -> Vector2D { func line(from: Vector2D, dimension: WritableKeyPath<Vector2D, Int>) -> (start: Vector2D, size: Int)? { var start: Vector2D? var size = 0 var pos = from var safety = 0 while safety < 100 { guard let output = computer.withInput(pos.x, pos.y).runned().outputs.first else { fatalError("No output") } switch output { case 0: if let start = start { return (start, size) } else { safety += 1 } case 1: size += 1 if start == nil { start = pos } default: fatalError("Unknown output") } pos[keyPath: dimension] += 1 } return nil } var potentialY = false var pos = Vector2D.zero var saveX = 0 while true { guard let line = line(from: pos, dimension: potentialY ? \.y : \.x) else { potentialY = false pos.y += 1 continue } guard line.size >= targetSize else { if potentialY { pos.x = saveX } else { pos.x = line.start.x } potentialY = false pos.y += 1 continue } if !potentialY { // We have a potential Y potentialY = true saveX = line.start.x pos.x = line.start.x + (line.size - targetSize) } else { // We are go for launch :D break } } return pos } } }
33.017241
123
0.375196
ed4206d664145e0e3c65c4ca3563d2e877fdf12d
5,439
// // SPCCPAConsent.swift // ConsentViewController // // Created by Andre Herculano on 08.02.21. // import Foundation /// Indicates the consent status of a given user. @objc public enum CCPAConsentStatus: Int, Codable { /// Indicates the user has rejected none of the vendors or purposes (categories) case RejectedNone /// Indicates the user has rejected none of the vendors or purposes (categories) case RejectedSome /// Indicates the user has rejected none of the vendors or purposes (categories) case RejectedAll /// Indicates the user has **explicitly** acceted all vendors and purposes (categories). /// That's slightly different than `RejectNone`. By default in the CCPA users are already /// `RejectedNone`, the `ConsentedAll` indicates the user has taken an action to /// consent to all vendors and purposes. case ConsentedAll public typealias RawValue = String public var rawValue: RawValue { switch self { case .ConsentedAll: return "consentedAll" case .RejectedAll: return "rejectedAll" case .RejectedSome: return "rejectedSome" case .RejectedNone: return "rejectedNone" } } public init?(rawValue: RawValue) { switch rawValue { case "consentedAll": self = .ConsentedAll case "rejectedAll": self = .RejectedAll case "rejectedSome": self = .RejectedSome case "rejectedNone": self = .RejectedNone default: return nil } } } public typealias SPUsPrivacyString = String /** The UserConsent class encapsulates the consent status, rejected vendor ids and rejected categories (purposes) ids. - Important: The `rejectedVendors` and `rejectedCategories` arrays will only be populated if the `status` is `.Some`. That is, if the user has rejected `.All` or `.None` vendors/categories, those arrays will be empty. */ @objcMembers public class SPCCPAConsent: NSObject, Codable { /// represents the default state of the consumer prior to seeing the consent message /// - seealso: https://github.com/InteractiveAdvertisingBureau/USPrivacy/blob/master/CCPA/US%20Privacy%20String.md#us-privacy-string-format public static let defaultUsPrivacyString = "1---" public static func empty() -> SPCCPAConsent { SPCCPAConsent( status: .RejectedNone, rejectedVendors: [], rejectedCategories: [], uspstring: defaultUsPrivacyString )} /// Indicates if the user has rejected `.All`, `.Some` or `.None` of the vendors **and** categories. public let status: CCPAConsentStatus /// The ids of the rejected vendors and categories. These can be found in SourcePoint's dashboard public let rejectedVendors, rejectedCategories: [String] /// the US Privacy String as described by the IAB public let uspstring: SPUsPrivacyString /// that's the internal Sourcepoint id we give to this consent profile public var uuid: String? public static func rejectedNone () -> SPCCPAConsent { SPCCPAConsent( status: CCPAConsentStatus.RejectedNone, rejectedVendors: [], rejectedCategories: [], uspstring: "" )} public init( uuid: String? = nil, status: CCPAConsentStatus, rejectedVendors: [String], rejectedCategories: [String], uspstring: SPUsPrivacyString ) { self.uuid = uuid self.status = status self.rejectedVendors = rejectedVendors self.rejectedCategories = rejectedCategories self.uspstring = uspstring } open override var description: String { "UserConsent(uuid: \(uuid ?? ""), status: \(status.rawValue), rejectedVendors: \(rejectedVendors), rejectedCategories: \(rejectedCategories), uspstring: \(uspstring))" } enum CodingKeys: CodingKey { case status, rejectedVendors, rejectedCategories, uspstring, uuid } required public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) uuid = try values.decodeIfPresent(String.self, forKey: .uuid) rejectedVendors = try values.decode([String].self, forKey: .rejectedVendors) rejectedCategories = try values.decode([String].self, forKey: .rejectedCategories) uspstring = try values.decode(SPUsPrivacyString.self, forKey: .uspstring) let statusString = try values.decode(String.self, forKey: .status) switch statusString { case "rejectedNone": status = .RejectedNone case "rejectedSome": status = .RejectedSome case "rejectedAll": status = .RejectedAll case "consentedAll": status = .ConsentedAll default: throw DecodingError.dataCorruptedError( forKey: CodingKeys.status, in: values, debugDescription: "Unknown Status: \(statusString)") } } public override func isEqual(_ object: Any?) -> Bool { if let other = object as? SPCCPAConsent { return other.uuid == uuid && other.rejectedCategories.elementsEqual(rejectedCategories) && other.rejectedVendors.elementsEqual(rejectedVendors) && other.status == status && other.uspstring == uspstring } else { return false } } }
37.253425
175
0.659496
2953bd866d85cafef289270a300ea3064eefcdd0
784
// // TimeHelper.swift // Pomodoro // // Created by Chelsea Valentine on 10/17/16. // Copyright © 2016 Chelsea Valentine. All rights reserved. // import Foundation class TimeHelper { private init() { } static func toTimeString(count: Int) -> String { let minutes = count / 60; let seconds = count - (minutes * 60) var minutesString: String; var secondsString: String; if (minutes < 10) { minutesString = "0\(minutes)" } else { minutesString = "\(minutes)" } if (seconds < 10) { secondsString = "0\(seconds)" } else { secondsString = "\(seconds)" } return minutesString + ":" + secondsString } }
22.4
60
0.521684
ef8aa3c54ef6b8cd264fac0d1b0bce7c3d3ba994
20,771
// // ClaimableGASTableViewCell.swift // O3 // // Created by Apisit Toompakdee on 6/11/18. // Copyright © 2018 O3 Labs Inc. All rights reserved. // import UIKit import Lottie import Crashlytics import Neoutils import StoreKit protocol ClaimingGasCellDelegate: class { func setIsClaimingNeo(_ isClaiming: Bool) func setIsClaimingOnt(_ isClaiming: Bool) } class ClaimableGASTableViewCell: UITableViewCell { weak var delegate: ClaimingGasCellDelegate? var neoClaimSuccessAnimation: LOTAnimationView = LOTAnimationView(name: "claim_success") var ontClaimSuccessAnimation: LOTAnimationView = LOTAnimationView(name: "claim_success") var ongBalance = 0.0 @IBOutlet var confirmedClaimableGASContainer: UIView! @IBOutlet weak var claimContainerTitleLabel: UILabel! //Neo Claiming Views @IBOutlet weak var neoClaimLoadingContainer: UIView! @IBOutlet weak var neoClaimSuccessContainer: UIView! @IBOutlet weak var neoSyncNowButton: UIButton! @IBOutlet var neoClaimNowButton: UIButton! @IBOutlet var claimableGasAmountLabel: UILabel! @IBOutlet var neoGasClaimingStateLabel: UILabel? @IBOutlet var confirmedClaimableGASTitle: UILabel? //Ont Claiming Views @IBOutlet weak var ontSyncButton: UIButton! @IBOutlet weak var ontClaimButton: UIButton! @IBOutlet weak var claimableOntAmountLabel: UILabel! @IBOutlet weak var ontClaimingStateTitle: UILabel! @IBOutlet weak var ongTitle: UILabel! @IBOutlet weak var ontClaimingSuccessContainer: UIView! @IBOutlet weak var ontClaimingLoadingContainer: UIView! let estimatedString = AccountStrings.estimatedClaimableGasTitle let confirmedString = AccountStrings.confirmedClaimableGasTitle let claimSucceededString = AccountStrings.successClaimTitle let loadingString = AccountStrings.claimingInProgressTitle func setupLocalizedStrings() { neoGasClaimingStateLabel?.text = AccountStrings.confirmedClaimableGasTitle ontClaimingStateTitle?.text = AccountStrings.confirmedClaimableGasTitle neoClaimNowButton?.setTitle(AccountStrings.claimNowButton, for: .normal) neoSyncNowButton?.setTitle(AccountStrings.updateNowButton, for: UIControl.State()) ontClaimButton?.setTitle(AccountStrings.claimNowButton, for: .normal) ontSyncButton?.setTitle(AccountStrings.updateNowButton, for: UIControl.State()) claimContainerTitleLabel.text = AccountStrings.claimNowButton } func setupTheme() { neoGasClaimingStateLabel?.theme_textColor = O3Theme.lightTextColorPicker ontClaimingStateTitle?.theme_textColor = O3Theme.lightTextColorPicker claimableOntAmountLabel?.theme_textColor = O3Theme.titleColorPicker claimableGasAmountLabel?.theme_textColor = O3Theme.titleColorPicker neoSyncNowButton.theme_setTitleColor(O3Theme.titleColorPicker, forState: UIControl.State()) ontSyncButton.theme_setTitleColor(O3Theme.titleColorPicker, forState: UIControl.State()) claimContainerTitleLabel.theme_textColor = O3Theme.titleColorPicker confirmedClaimableGASContainer?.theme_backgroundColor = O3Theme.backgroundColorPicker theme_backgroundColor = O3Theme.backgroundLightgrey contentView.theme_backgroundColor = O3Theme.backgroundLightgrey } override func layoutSubviews() { super.layoutSubviews() self.setupTheme() } func setupView() { let neoLoaderView = LOTAnimationView(name: "loader_portfolio") neoLoaderView.loopAnimation = true neoLoaderView.play() let ontLoaderView = LOTAnimationView(name: "loader_portfolio") neoLoaderView.loopAnimation = true ontLoaderView.play() neoClaimLoadingContainer.embed(neoLoaderView) neoClaimSuccessContainer.embed(neoClaimSuccessAnimation) ontClaimingLoadingContainer.embed(ontLoaderView) ontClaimingSuccessContainer.embed(ontClaimSuccessAnimation) neoSyncNowButton?.addTarget(self, action: #selector(neoSyncNowTapped(_:)), for: .touchUpInside) neoClaimNowButton?.addTarget(self, action: #selector(neoClaimNowTapped(_:)), for: .touchUpInside) ontSyncButton?.addTarget(self, action: #selector(ontSyncNowTapped(_:)), for: .touchUpInside) ontClaimButton?.addTarget(self, action: #selector(ontClaimNowTapped(_:)), for: .touchUpInside) } func resetNEOState() { DispatchQueue.main.async { self.neoClaimLoadingContainer.isHidden = true self.neoClaimSuccessContainer.isHidden = true self.neoClaimNowButton.isHidden = true self.neoSyncNowButton.isHidden = true } } func resetOntState() { DispatchQueue.main.async { self.ontClaimingLoadingContainer.isHidden = true self.ontClaimingSuccessContainer.isHidden = true self.ontClaimButton.isHidden = true self.ontSyncButton.isHidden = true } } override func awakeFromNib() { super.awakeFromNib() self.setupLocalizedStrings() self.setupView() } func loadClaimableGASNeo() { O3APIClient(network: AppState.network).getClaims(address: (Authenticated.wallet?.address)!) { result in switch result { case .failure(let error): self.resetNEOState() OzoneAlert.alertDialog(message: error.localizedDescription, dismissTitle: "OK", didDismiss: {}) return case .success(let claims): DispatchQueue.main.async { if claims.claims.count > 0 { AppState.setClaimingState(address: Authenticated.wallet!.address, claimingState: .ReadyToClaim) } self.displayClaimableStateNeo(claimable: claims) } } } } func loadClaimableOng() { O3Client().getUnboundOng(address: (Authenticated.wallet?.address)!) { result in switch result { case .failure(let error): self.resetOntState() OzoneAlert.alertDialog(message: error.localizedDescription, dismissTitle: "OK", didDismiss: {}) return case .success(let unboundOng): //if claims.claims.count > 0 { // AppState.setClaimingState(address: Authenticated.account!.address, claimingState: .ReadyToClaim) // } DispatchQueue.main.async { self.displayClaimableStateOnt(unboundOng: unboundOng) } } } } func displayClaimableStateNeo(claimable: Claimable) { self.resetNEOState() let gasDouble = NSDecimalNumber(decimal: claimable.gas).doubleValue if claimable.claims.count == 0 { //if claim array is empty then we show estimated let gas = gasDouble.string(8, removeTrailing: true) self.showEstimatedClaimableNeoState(value: gas) } else { //if claim array is not empty then we show the confirmed claimable and let user claims let gas = gasDouble.string(8, removeTrailing: true) self.showConfirmedClaimableGASStateNeo(value: gas) } } func displayClaimableStateOnt(unboundOng: UnboundOng) { self.resetOntState() let doubleAmount = Double(Int(unboundOng.ong)!) / 1000000000.0 if unboundOng.calculated == true { self.showEstimatedClaimableOngState(value: doubleAmount) } else { self.showConfirmedClaimableOngState(value: doubleAmount) } } func showEstimatedClaimableOngState(value: Double?) { self.resetOntState() self.ontClaimingStateTitle?.text = estimatedString DispatchQueue.main.async { self.ontSyncButton.isHidden = false if value != nil { self.ontSyncButton.isHidden = value!.isZero self.claimableOntAmountLabel.text = value!.string(8, removeTrailing: true) } if self.ongBalance < 0.02 { self.ontSyncButton.isHidden = true self.ontClaimingStateTitle?.text = "You must have 0.02 ONG in order to sync" } } } func showConfirmedClaimableOngState(value: Double?) { self.resetOntState() self.ontClaimingStateTitle?.text = confirmedString DispatchQueue.main.async { self.ontClaimButton.isHidden = false self.ontClaimingLoadingContainer.isHidden = true if value != nil { self.claimableOntAmountLabel.text = value!.string(8, removeTrailing: true) } if self.ongBalance < 0.01 { self.ontClaimButton.isHidden = true self.ontClaimingStateTitle?.text = "You must have 0.01 ONG in order to claim" } } } func showEstimatedClaimableNeoState(value: String) { self.resetNEOState() DispatchQueue.main.async { self.neoSyncNowButton.isHidden = false self.neoGasClaimingStateLabel?.text = self.estimatedString self.neoSyncNowButton?.isHidden = Int(value) == 0 self.claimableGasAmountLabel.text = value } } func showConfirmedClaimableGASStateNeo(value: String) { self.resetNEOState() DispatchQueue.main.async { self.claimableGasAmountLabel?.text = value self.neoClaimNowButton?.isHidden = false self.neoGasClaimingStateLabel?.text = self.confirmedString self.neoClaimLoadingContainer.isHidden = true } } func sendAllNEOToTheAddress() { //show loading screen first self.delegate?.setIsClaimingNeo(true) DispatchQueue.main.async { self.neoSyncNowButton.isHidden = true self.neoClaimLoadingContainer.isHidden = false self.startLoadingNeoClaims() } //try to fetch best node if let bestNode = NEONetworkMonitor.autoSelectBestNode(network: AppState.network) { AppState.bestSeedNodeURL = bestNode #if DEBUG print(AppState.network) print(AppState.bestSeedNodeURL) #endif } //to be able to claim. we need to send the entire NEO to ourself. var customAttributes: [TransactionAttritbute] = [] let remark = String(format: "O3XFORCLAIM") customAttributes.append(TransactionAttritbute(remark: remark)) Authenticated.wallet?.sendAssetTransaction(network: AppState.network, seedURL: AppState.bestSeedNodeURL, asset: AssetId.neoAssetId, amount: O3Cache.neoBalance(for: Authenticated.wallet!.address).value, toAddress: (Authenticated.wallet?.address)!, attributes: customAttributes) { txid, _ in if txid == nil { self.delegate?.setIsClaimingNeo(false) //if sending failed then show error message and load the claimable gas again to reset the state OzoneAlert.alertDialog(message: "Error while trying to send", dismissTitle: "OK", didDismiss: { }) self.loadClaimableGASNeo() return } } } func claimConfirmedNeoClaimableGAS() { self.delegate?.setIsClaimingNeo(true) DispatchQueue.main.async { self.neoClaimNowButton?.isHidden = true self.neoClaimLoadingContainer.isHidden = false } //show loading perhaps if let bestNode = NEONetworkMonitor.autoSelectBestNode(network: AppState.network) { AppState.bestSeedNodeURL = bestNode #if DEBUG print(AppState.network) print(AppState.bestSeedNodeURL) #endif } Authenticated.wallet?.claimGas(network: AppState.network, seedURL: AppState.bestSeedNodeURL) { success, error in DispatchQueue.main.async { if error != nil { self.delegate?.setIsClaimingNeo(false) self.neoClaimLoadingContainer.isHidden = true self.neoClaimNowButton?.isHidden = false OzoneAlert.alertDialog(SendStrings.transactionFailedTitle, message: SendStrings.transactionFailedSubtitle, dismissTitle: OzoneAlert.okPositiveConfirmString) {} return } if success == true { self.neoClaimedSuccess() } else { DispatchQueue.main.async { self.delegate?.setIsClaimingNeo(false) self.neoClaimLoadingContainer.isHidden = true self.neoClaimNowButton?.isHidden = false } OzoneAlert.alertDialog(SendStrings.transactionFailedTitle, message: SendStrings.transactionFailedSubtitle, dismissTitle: OzoneAlert.okPositiveConfirmString) {} return } } } } @objc @IBAction func neoSyncNowTapped(_ sender: Any) { self.sendAllNEOToTheAddress() } @objc @IBAction func neoClaimNowTapped(_ sender: Any) { self.claimConfirmedNeoClaimableGAS() } func sendOneOntBackToAddress() { let endpoint = ONTNetworkMonitor.autoSelectBestNode(network: AppState.network) self.delegate?.setIsClaimingOnt(true) DispatchQueue.main.async { self.ontSyncButton.isHidden = true self.startLoadingOntClaims() } OntologyClient().getGasPrice { result in switch result { case .failure(let error): #if DEBUG print(error) #endif //throw some error here DispatchQueue.main.async { self.delegate?.setIsClaimingOnt(false) OzoneAlert.alertDialog(SendStrings.transactionFailedTitle, message: SendStrings.transactionFailedSubtitle, dismissTitle: OzoneAlert.okPositiveConfirmString) {} self.loadClaimableOng() } case .success(let gasPrice): var error: NSError? let txid = NeoutilsOntologyTransfer(endpoint, gasPrice, 20000, Authenticated.wallet!.wif, "ONT", Authenticated.wallet!.address, 1.0, &error) DispatchQueue.main.async { if txid == "" { OzoneAlert.alertDialog(SendStrings.transactionFailedTitle, message: SendStrings.transactionFailedSubtitle, dismissTitle: OzoneAlert.okPositiveConfirmString) {} self.loadClaimableOng() } } } } } func claimConfirmedOng() { self.delegate?.setIsClaimingOnt(true) DispatchQueue.main.async { self.ontClaimButton?.isHidden = true self.ontClaimingLoadingContainer.isHidden = false } //select best node if necessary let endpoint = ONTNetworkMonitor.autoSelectBestNode(network: AppState.network) OntologyClient().getGasPrice { result in switch result { case .failure: //throw some error here DispatchQueue.main.async { OzoneAlert.alertDialog(SendStrings.transactionFailedTitle, message: SendStrings.transactionFailedSubtitle, dismissTitle: OzoneAlert.okPositiveConfirmString) {} self.delegate?.setIsClaimingOnt(false) self.showConfirmedClaimableOngState(value: nil) } case .success(let gasPrice): var error: NSError? let txid = NeoutilsClaimONG(endpoint, gasPrice, 20000, Authenticated.wallet!.wif, &error) DispatchQueue.main.async { if txid != "" { self.ontClaimedSuccess() ClaimEvent.shared.ongClaimed() } else { OzoneAlert.alertDialog(SendStrings.transactionFailedTitle, message: SendStrings.transactionFailedSubtitle, dismissTitle: OzoneAlert.okPositiveConfirmString) {} self.delegate?.setIsClaimingOnt(false) self.showConfirmedClaimableOngState(value: nil) } } } } } @objc func ontSyncNowTapped(_ sender: Any) { OzoneAlert.confirmDialog(message: AccountStrings.ontologySyncFee, cancelTitle: OzoneAlert.cancelNegativeConfirmString, confirmTitle: OzoneAlert.okPositiveConfirmString, didCancel: {return}) { self.sendOneOntBackToAddress() } } @objc func ontClaimNowTapped(_ sender: Any) { OzoneAlert.confirmDialog(message: "Claiming ONG requires the Ontology network fee of 0.01 ONG", cancelTitle: OzoneAlert.cancelNegativeConfirmString, confirmTitle: OzoneAlert.okPositiveConfirmString, didCancel: {return}) { self.claimConfirmedOng() } } func neoClaimedSuccess() { AppState.setClaimingState(address: Authenticated.wallet!.address, claimingState: .Fresh) ClaimEvent.shared.gasClaimed() DispatchQueue.main.async { self.neoClaimLoadingContainer.isHidden = true self.neoClaimSuccessContainer.isHidden = false self.neoClaimSuccessAnimation.play() self.neoGasClaimingStateLabel?.theme_textColor = O3Theme.positiveGainColorPicker self.neoGasClaimingStateLabel?.text = self.claimSucceededString self.startCountdownBackToNeoEstimated() if UserDefaultsManager.numClaims % 10 == 0 { UserDefaultsManager.numClaims = UserDefaultsManager.numClaims + 1 SKStoreReviewController.requestReview() } } } func ontClaimedSuccess() { DispatchQueue.main.async { self.ontClaimingLoadingContainer.isHidden = true self.ontClaimingSuccessContainer.isHidden = false self.ontClaimSuccessAnimation.play() self.ontClaimingStateTitle?.theme_textColor = O3Theme.positiveGainColorPicker self.ontClaimingStateTitle.text = self.claimSucceededString self.startCountdownBackToOntEstimated() } } //CountdownTimers NEO func startCountdownBackToNeoEstimated() { let targetSec = 60 var sec = 0 let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in DispatchQueue.main.async { sec += 1 if sec == targetSec { timer.invalidate() self.delegate?.setIsClaimingNeo(false) self.loadClaimableGASNeo() } } } timer.fire() } func startCountdownBackToOntEstimated() { let targetSec = 30 var sec = 0 let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in DispatchQueue.main.async { sec += 1 if sec == targetSec { timer.invalidate() self.delegate?.setIsClaimingOnt(false) self.loadClaimableOng() } } } timer.fire() } func startLoadingNeoClaims() { self.neoClaimLoadingContainer.isHidden = false let targetSec = 60 var sec = 0 let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in DispatchQueue.main.async { sec += 1 self.delegate?.setIsClaimingNeo(true) if sec == targetSec { timer.invalidate() self.delegate?.setIsClaimingNeo(false) //load claimable api again to check the claim array self.loadClaimableGASNeo() } } } timer.fire() } func startLoadingOntClaims() { self.ontClaimingLoadingContainer.isHidden = false let targetSec = 60 var sec = 0 let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in DispatchQueue.main.async { sec += 1 self.delegate?.setIsClaimingNeo(true) if sec == targetSec { timer.invalidate() self.delegate?.setIsClaimingNeo(false) //load claimable api again to check the claim array self.loadClaimableOng() } } } timer.fire() } }
40.887795
297
0.629772
abd905a3419c34620e66b93a07b7fdd13a992400
13,569
// // TagListView.swift // TagListViewDemo // // Created by Dongyuan Liu on 2015-05-09. // Copyright (c) 2015 Ela. All rights reserved. // import UIKit @objc public protocol TagListViewDelegate { @objc optional func tagPressed(_ title: String, tagView: TagView, sender: TagListView) -> Void @objc optional func tagRemoveButtonPressed(_ title: String, tagView: TagView, sender: TagListView) -> Void } @IBDesignable open class TagListView: UIView { @IBInspectable open dynamic var textColor: UIColor = UIColor.white { didSet { for tagView in tagViews { tagView.textColor = textColor } } } @IBInspectable open dynamic var selectedTextColor: UIColor = UIColor.white { didSet { for tagView in tagViews { tagView.selectedTextColor = selectedTextColor } } } @IBInspectable open dynamic var tagLineBreakMode: NSLineBreakMode = .byTruncatingMiddle { didSet { for tagView in tagViews { tagView.titleLineBreakMode = tagLineBreakMode } } } @IBInspectable open dynamic var tagBackgroundColor: UIColor = UIColor.gray { didSet { for tagView in tagViews { tagView.tagBackgroundColor = tagBackgroundColor } } } @IBInspectable open dynamic var tagHighlightedBackgroundColor: UIColor? { didSet { for tagView in tagViews { tagView.highlightedBackgroundColor = tagHighlightedBackgroundColor } } } @IBInspectable open dynamic var tagSelectedBackgroundColor: UIColor? { didSet { for tagView in tagViews { tagView.selectedBackgroundColor = tagSelectedBackgroundColor } } } @IBInspectable open dynamic var cornerRadius: CGFloat = 0 { didSet { for tagView in tagViews { tagView.cornerRadius = cornerRadius } } } @IBInspectable open dynamic var borderWidth: CGFloat = 0 { didSet { for tagView in tagViews { tagView.borderWidth = borderWidth } } } @IBInspectable open dynamic var borderColor: UIColor? { didSet { for tagView in tagViews { tagView.borderColor = borderColor } } } @IBInspectable open dynamic var selectedBorderColor: UIColor? { didSet { for tagView in tagViews { tagView.selectedBorderColor = selectedBorderColor } } } @IBInspectable open dynamic var paddingY: CGFloat = 2 { didSet { for tagView in tagViews { tagView.paddingY = paddingY } rearrangeViews() } } @IBInspectable open dynamic var paddingX: CGFloat = 5 { didSet { for tagView in tagViews { tagView.paddingX = paddingX } rearrangeViews() } } @IBInspectable open dynamic var marginY: CGFloat = 2 { didSet { rearrangeViews() } } @IBInspectable open dynamic var marginX: CGFloat = 5 { didSet { rearrangeViews() } } @objc public enum Alignment: Int { case left case center case right } @IBInspectable open var alignment: Alignment = .left { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowColor: UIColor = UIColor.white { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowRadius: CGFloat = 0 { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowOffset: CGSize = CGSize.zero { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowOpacity: Float = 0 { didSet { rearrangeViews() } } @IBInspectable open dynamic var enableRemoveButton: Bool = false { didSet { for tagView in tagViews { tagView.enableRemoveButton = enableRemoveButton } rearrangeViews() } } @IBInspectable open dynamic var removeButtonIconSize: CGFloat = 12 { didSet { for tagView in tagViews { tagView.removeButtonIconSize = removeButtonIconSize } rearrangeViews() } } @IBInspectable open dynamic var removeIconLineWidth: CGFloat = 1 { didSet { for tagView in tagViews { tagView.removeIconLineWidth = removeIconLineWidth } rearrangeViews() } } @IBInspectable open dynamic var removeIconLineColor: UIColor = UIColor.white.withAlphaComponent(0.54) { didSet { for tagView in tagViews { tagView.removeIconLineColor = removeIconLineColor } rearrangeViews() } } @objc open dynamic var textFont: UIFont = UIFont.systemFont(ofSize: 12) { didSet { for tagView in tagViews { tagView.textFont = textFont } rearrangeViews() } } @IBOutlet open weak var delegate: TagListViewDelegate? open private(set) var tagViews: [TagView] = [] private(set) var tagBackgroundViews: [UIView] = [] private(set) var rowViews: [UIView] = [] private(set) var tagViewHeight: CGFloat = 0 private(set) var rows = 0 { didSet { invalidateIntrinsicContentSize() } } // MARK: - Interface Builder open override func prepareForInterfaceBuilder() { addTag("Welcome", false) addTag("to", false) addTag("TagListView", true).isSelected = true } // MARK: - Layout open override func layoutSubviews() { super.layoutSubviews() rearrangeViews() } private func rearrangeViews() { let views = tagViews as [UIView] + tagBackgroundViews + rowViews for view in views { view.removeFromSuperview() } rowViews.removeAll(keepingCapacity: true) var currentRow = 0 var currentRowView: UIView! var currentRowTagCount = 0 var currentRowWidth: CGFloat = 0 for (index, tagView) in tagViews.enumerated() { tagView.frame.size = tagView.intrinsicContentSize tagViewHeight = tagView.frame.height if currentRowTagCount == 0 || currentRowWidth + tagView.frame.width > frame.width { currentRow += 1 currentRowWidth = 0 currentRowTagCount = 0 currentRowView = UIView() currentRowView.frame.origin.y = CGFloat(currentRow - 1) * (tagViewHeight + marginY) rowViews.append(currentRowView) addSubview(currentRowView) tagView.frame.size.width = min(tagView.frame.size.width, frame.width) } let tagBackgroundView = tagBackgroundViews[index] tagBackgroundView.frame.origin = CGPoint(x: currentRowWidth, y: 0) tagBackgroundView.frame.size = tagView.bounds.size tagBackgroundView.layer.shadowColor = shadowColor.cgColor tagBackgroundView.layer.shadowPath = UIBezierPath(roundedRect: tagBackgroundView.bounds, cornerRadius: cornerRadius).cgPath tagBackgroundView.layer.shadowOffset = shadowOffset tagBackgroundView.layer.shadowOpacity = shadowOpacity tagBackgroundView.layer.shadowRadius = shadowRadius tagBackgroundView.addSubview(tagView) currentRowView.addSubview(tagBackgroundView) currentRowTagCount += 1 currentRowWidth += tagView.frame.width + marginX switch alignment { case .left: currentRowView.frame.origin.x = 0 case .center: currentRowView.frame.origin.x = (frame.width - (currentRowWidth - marginX)) / 2 case .right: currentRowView.frame.origin.x = frame.width - (currentRowWidth - marginX) } currentRowView.frame.size.width = currentRowWidth currentRowView.frame.size.height = max(tagViewHeight, currentRowView.frame.height) } rows = currentRow invalidateIntrinsicContentSize() } // MARK: - Manage tags override open var intrinsicContentSize: CGSize { var height = CGFloat(rows) * (tagViewHeight + marginY) if rows > 0 { height -= marginY } return CGSize(width: frame.width, height: height) } private func createNewTagView(_ title: String ,_ isHotKeyword:Bool) -> TagView { let tagView = TagView(title: title, isHotKeyword: isHotKeyword) tagView.textColor = textColor tagView.selectedTextColor = selectedTextColor tagView.tagBackgroundColor = tagBackgroundColor tagView.highlightedBackgroundColor = tagHighlightedBackgroundColor tagView.selectedBackgroundColor = tagSelectedBackgroundColor tagView.titleLineBreakMode = tagLineBreakMode tagView.cornerRadius = cornerRadius tagView.borderWidth = borderWidth tagView.borderColor = borderColor tagView.selectedBorderColor = selectedBorderColor tagView.paddingX = paddingX tagView.paddingY = paddingY tagView.textFont = textFont tagView.removeIconLineWidth = removeIconLineWidth tagView.removeButtonIconSize = removeButtonIconSize tagView.enableRemoveButton = enableRemoveButton tagView.removeIconLineColor = removeIconLineColor tagView.addTarget(self, action: #selector(tagPressed(_:)), for: .touchUpInside) tagView.removeButton.addTarget(self, action: #selector(removeButtonPressed(_:)), for: .touchUpInside) // On long press, deselect all tags except this one tagView.onLongPress = { [unowned self] this in for tag in self.tagViews { tag.isSelected = (tag == this) } } return tagView } @discardableResult open func addTag(_ title: String , _ isHotKeyword:Bool) -> TagView { return addTagView(createNewTagView(title ,isHotKeyword)) } @discardableResult open func addTags(_ titles: [String:Bool]) -> [TagView] { var tagViews: [TagView] = [] for (title,isHotKeyWord) in titles { tagViews.append(createNewTagView(title,isHotKeyWord)) } return addTagViews(tagViews) } @discardableResult open func addTagViews(_ tagViews: [TagView]) -> [TagView] { for tagView in tagViews { self.tagViews.append(tagView) tagBackgroundViews.append(UIView(frame: tagView.bounds)) } rearrangeViews() return tagViews } @discardableResult open func insertTag(_ title: String, at index: Int) -> TagView { return insertTagView(createNewTagView(title, true), at: index) } @discardableResult open func addTagView(_ tagView: TagView) -> TagView { tagViews.append(tagView) tagBackgroundViews.append(UIView(frame: tagView.bounds)) rearrangeViews() return tagView } @discardableResult open func insertTagView(_ tagView: TagView, at index: Int) -> TagView { tagViews.insert(tagView, at: index) tagBackgroundViews.insert(UIView(frame: tagView.bounds), at: index) rearrangeViews() return tagView } open func setTitle(_ title: String, at index: Int) { tagViews[index].titleLabel?.text = title } open func removeTag(_ title: String) { // loop the array in reversed order to remove items during loop for index in stride(from: (tagViews.count - 1), through: 0, by: -1) { let tagView = tagViews[index] if tagView.currentTitle == title { removeTagView(tagView) } } } open func removeTagView(_ tagView: TagView) { tagView.removeFromSuperview() if let index = tagViews.index(of: tagView) { tagViews.remove(at: index) tagBackgroundViews.remove(at: index) } rearrangeViews() } open func removeAllTags() { let views = tagViews as [UIView] + tagBackgroundViews for view in views { view.removeFromSuperview() } tagViews = [] tagBackgroundViews = [] rearrangeViews() } open func selectedTags() -> [TagView] { return tagViews.filter() { $0.isSelected == true } } // MARK: - Events @objc func tagPressed(_ sender: TagView!) { sender.onTap?(sender) delegate?.tagPressed?(sender.currentTitle ?? "", tagView: sender, sender: self) } @objc func removeButtonPressed(_ closeButton: CloseButton!) { if let tagView = closeButton.tagView { delegate?.tagRemoveButtonPressed?(tagView.currentTitle ?? "", tagView: tagView, sender: self) } } }
31.852113
135
0.590021
e0e42cc8ed79cb2094d2b16cbd47757aac88d35a
157
// // Main.swift // CombineWeather // // Created by Durbalo, Andrii on 18.12.2020. // import Foundation struct Main: Codable { let temp: Double }
10.466667
45
0.643312
211d298ca4bb89775d40b2c6d8481c5c64fdbe1e
368
// // LoginViewController.swift // Router // // Created by GK on 2017/2/8. // Copyright © 2017年 GK. All rights reserved. // import Foundation import UIKit class LoginViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } }
18.4
80
0.663043
917ffbac99095f73fc915e554743685e196f7c47
3,296
import Foundation class RegionCodes { static func getRegionCode(fromCountryName countryName: String) -> String? { return RegionCodes.regionCodesByCountryName[countryName] } // The country names here should exactly match the names in the pricing matrix CSV file. // The two-letter region codes here must be ISO 3166-1 country codes (compatible with the Locale class): // https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 static fileprivate let regionCodesByCountryName: Dictionary<String, String> = [ "Hong Kong": "HK", "Portugal": "PT", "Honduras": "HN", "Paraguay": "PY", "Croatia": "HR", "Hungary": "HU", "Qatar": "QA", "Indonesia": "ID", "Ireland": "IE", "Israel": "IL", "United Arab Emirates": "AE", "Afghanistan": "AF", "India": "IN", "South Africa": "ZA", "Iraq": "IQ", "Iceland": "IS", "Albania": "AL", "Italy": "IT", "Armenia": "AM", "Argentina": "AR", "Zambia": "ZM", "Austria": "AT", "Australia": "AU", "Romania": "RO", "Bosnia and Herzegovina": "BA", "Barbados": "BB", "Serbia": "RS", "Russia": "RU", "Belgium": "BE", "Bulgaria": "BG", "Rwanda": "RW", "Japan": "JP", "Bahrain": "BH", "Bolivia": "BO", "Saudi Arabia": "SA", "Brazil": "BR", "Sweden": "SE", "Singapore": "SG", "Slovenia": "SI", "Belarus": "BY", "Slovakia": "SK", "Canada": "CA", "Congo, Democratic Republic of": "CD", "El Salvador": "SV", "Switzerland": "CH", "Cote D'Ivoire": "CI", "Ivoire": "CI", "South Korea": "KR", "Chile": "CL", "Cameroon": "CM", "China": "CN", "Colombia": "CO", "Costa Rica": "CR", "Kazakhstan": "KZ", "Thailand": "TH", "Cyprus": "CY", "Czech Republic": "CZ", "Tonga": "TO", "Turkey": "TR", "Germany": "DE", "Taiwan": "TW", "Tanzania": "TZ", "Denmark": "DK", "Lithuania": "LT", "Luxembourg": "LU", "Latvia": "LV", "Dominican Republic": "DO", "Ukraine": "UA", "Libya": "LF", "Morocco": "MA", "Moldova": "MD", "Montenegro": "ME", "Ecuador": "EC", "United States": "US", "Myanmar": "MM", "Estonia": "EW", "Egypt": "EG", "Uruguay": "UY", "Uzbekistan": "UZ", "Malta": "MT", "Maldives": "MV", "Mexico": "MX", "Malaysia": "MY", "Spain": "ES", "Vietnam": "VN", "Nigeria": "NG", "Nicaragua": "NI", "Netherlands": "NL", "Vanuatu": "VU", "Norway": "NO", "Finland": "SF", "Nauru": "NR", "New Zealand": "NZ", "France": "FR", "Gabon": "GA", "United Kingdom": "UK", "Georgia": "GE", "Greece": "GR", "Guatemala": "GT", "Panama": "PA", "Kosovo": "XK", "Peru": "PE", "Philippines": "PH", "Pakistan": "PK", "Poland": "PL" ] }
27.466667
108
0.437803
bb239de261f877f3db21fd38b232e5321541ca38
3,801
// // structural-fold-phase.swift // Campuswelle // // Created by Valentin Knabel on 20.05.15. // Copyright (c) 2015 Valentin Knabel. All rights reserved. // import Foundation enum HtmlNode { case Node(tag: String, attributes: [String: String], children: [HtmlNode]) case Text(text: String) case Nil } enum StructuralNode { typealias Children = [StructuralNode] typealias Type = [String] case Nil case Group(dfghjkwedfghfjghkj) case Break case Text(String) case Image(src: String, type: String) case Paragraph(type: Type, children: Children) case Heading(type: Type, children: Children) case Link(url: String, type: Type, children: Children) } func toHtmlNode(hpple: TFHppleElement) -> HtmlNode { if hpple.isTextNode() { return HtmlNode.Text(text: hpple.text()) } return HtmlNode.Node(tag: hpple.tagName, attributes: hpple.attributes as! [String: String], children: map(hpple.children as! [TFHppleElement], toHtmlNode) ) } func foldHtmlNode<T>(html: HtmlNode, initial: T, textFolder: (left: T, text: String) -> T, nodeFolder: (left: T, tag: String, attributes: [String: String], children: [T]) -> T) -> T { switch html { case .Nil: return initial case let .Text(text: t): return textFolder(left: initial, text: t) case let .Node(tag: t, attributes: a, children: cs): let flattenedChildren: [T] = map(cs) { c in foldHtmlNode(c, initial: initial, textFolder: textFolder, nodeFolder: nodeFolder) } return nodeFolder(left: initial, tag: t, attributes: a, children: flattenedChildren) } } func getType(attributes: [String: String]) -> [String] { return split((attributes["class"] ?? ""), maxSplit: 0, allowEmptySlices: false, isSeparator: { c in c == Character(" ") }) } func combineStructuralNode(lhs: StructuralNode, rhs: StructuralNode) -> StructuralNode { switch lhs { case .Nil: return rhs case .Break, .Image(src: _, type: _), .Text(_): return StructuralNode.Paragraph(type: [], children: [lhs, rhs]) case .Paragraph(type: let ts, children: var cs): cs.append(rhs) return .Paragraph(type: ts, children: cs) case .Heading(type: let ts, children: var cs): cs.append(rhs) return .Heading(type: ts, children: cs) case .Link(url: let url, type: let ts, children: var cs): cs.append(rhs) return .Link(url: url, type: ts, children: cs) } } func toStructuralNode(html: HtmlNode) -> StructuralNode { return foldHtmlNode(html, initial: StructuralNode.Nil, textFolder: { (left, text) -> StructuralNode in let node = StructuralNode.Text(text) return combineStructuralNode(left, node) }) { (left, tag, attributes, children) -> StructuralNode in let node: StructuralNode switch tag { case "br": node = .Break case "img": if let src = attributes["src"] { node = .Image(src: src, type: attributes["class"] ?? "") } else { node = .Nil } case "p": node = StructuralNode.Paragraph(type: getType(attributes), children: children) case "h1": node = StructuralNode.Heading(type: getType(attributes), children: children) case "a": if let href = attributes["href"] { node = StructuralNode.Link(url: href, type: getType(attributes), children: children) } else { node = StructuralNode.Nil } default: DO NOT THROW NODES AWAY node = StructuralNode.Nil } return combineStructuralNode(left, node) } }
33.052174
183
0.606156
d5df2897c49ad9d00d50c0d2c9dbe8e7d7ae2349
1,128
// // HomeContainerView.swift // Recipes // // Created by James Talano on 11/10/19. // Copyright © 2019 James Talano. All rights reserved. // import SwiftUI struct HomeContainerView: View { @EnvironmentObject var store: AppStore @State private var favoritesShown = false private var hasFavorites: Bool { !store.state.favorited.isEmpty } private var health: Binding<Health> { store.binding(for: \.health) { .setHealth(health: $0) } } var body: some View { HomeView(health: health) .navigationBarTitle("recipes") .navigationBarItems( trailing: hasFavorites ? Button(action: { self.favoritesShown = true }) { Image(systemName: "heart.fill") .font(.headline) .accessibility(label: Text("favorites")) } : nil ).sheet(isPresented: $favoritesShown) { FavoritesContainerView() .environmentObject(self.store) .embedInNavigation() .accentColor(.green) } } }
28.923077
89
0.56383
ddca8500dc3c455d7c9c7f92e5f76f1dd1549d8f
265
import Vapor extension Droplet { func setupRoutes() throws { let userController = UserController(drop: self) userController.addRoutes() let rideController = RideController(drop: self) rideController.addRoutes() } }
22.083333
55
0.649057
f966b87bf8d57f4211bbf3e35f51840d0954e187
36,439
import UIKit import Foundation // MARK: - NestedLayout public class NestedLayout: UIView { // MARK: Lifecycle public init() { super.init(frame: .zero) setUpViews() setUpConstraints() update() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Private private var topRowView = UIView(frame: .zero) private var column1View = UIView(frame: .zero) private var view1View = UIView(frame: .zero) private var localAssetView = LocalAsset() private var view2View = UIView(frame: .zero) private var localAsset2View = LocalAsset() private var view3View = UIView(frame: .zero) private var localAsset3View = LocalAsset() private var column2View = UIView(frame: .zero) private var view4View = UIView(frame: .zero) private var localAsset4View = LocalAsset() private var view5View = UIView(frame: .zero) private var localAsset5View = LocalAsset() private var view6View = UIView(frame: .zero) private var localAsset6View = LocalAsset() private var column3View = UIView(frame: .zero) private var view7View = UIView(frame: .zero) private var localAsset7View = LocalAsset() private var view8View = UIView(frame: .zero) private var localAsset8View = LocalAsset() private var view9View = UIView(frame: .zero) private var localAsset9View = LocalAsset() private var bottomRowView = UIView(frame: .zero) private var column4View = UIView(frame: .zero) private var view10View = UIView(frame: .zero) private var localAsset10View = LocalAsset() private var view11View = UIView(frame: .zero) private var localAsset11View = LocalAsset() private var view12View = UIView(frame: .zero) private var localAsset12View = LocalAsset() private var column5View = UIView(frame: .zero) private var view13View = UIView(frame: .zero) private var localAsset13View = LocalAsset() private var view14View = UIView(frame: .zero) private var localAsset14View = LocalAsset() private var view15View = UIView(frame: .zero) private var localAsset15View = LocalAsset() private var column6View = UIView(frame: .zero) private var view16View = UIView(frame: .zero) private var localAsset16View = LocalAsset() private var view17View = UIView(frame: .zero) private var localAsset17View = LocalAsset() private var view18View = UIView(frame: .zero) private var localAsset18View = LocalAsset() private func setUpViews() { addSubview(topRowView) addSubview(bottomRowView) topRowView.addSubview(column1View) topRowView.addSubview(column2View) topRowView.addSubview(column3View) column1View.addSubview(view1View) column1View.addSubview(view2View) column1View.addSubview(view3View) view1View.addSubview(localAssetView) view2View.addSubview(localAsset2View) view3View.addSubview(localAsset3View) column2View.addSubview(view4View) column2View.addSubview(view5View) column2View.addSubview(view6View) view4View.addSubview(localAsset4View) view5View.addSubview(localAsset5View) view6View.addSubview(localAsset6View) column3View.addSubview(view7View) column3View.addSubview(view8View) column3View.addSubview(view9View) view7View.addSubview(localAsset7View) view8View.addSubview(localAsset8View) view9View.addSubview(localAsset9View) bottomRowView.addSubview(column4View) bottomRowView.addSubview(column5View) bottomRowView.addSubview(column6View) column4View.addSubview(view10View) column4View.addSubview(view11View) column4View.addSubview(view12View) view10View.addSubview(localAsset10View) view11View.addSubview(localAsset11View) view12View.addSubview(localAsset12View) column5View.addSubview(view13View) column5View.addSubview(view14View) column5View.addSubview(view15View) view13View.addSubview(localAsset13View) view14View.addSubview(localAsset14View) view15View.addSubview(localAsset15View) column6View.addSubview(view16View) column6View.addSubview(view17View) column6View.addSubview(view18View) view16View.addSubview(localAsset16View) view17View.addSubview(localAsset17View) view18View.addSubview(localAsset18View) view1View.backgroundColor = Colors.grey50 view2View.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0) view3View.backgroundColor = Colors.grey50 view5View.backgroundColor = Colors.grey50 view7View.backgroundColor = Colors.grey50 view9View.backgroundColor = Colors.grey50 view10View.backgroundColor = Colors.grey50 view11View.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0) view12View.backgroundColor = Colors.grey50 view14View.backgroundColor = Colors.grey50 view16View.backgroundColor = Colors.grey50 view18View.backgroundColor = Colors.grey50 } private func setUpConstraints() { translatesAutoresizingMaskIntoConstraints = false topRowView.translatesAutoresizingMaskIntoConstraints = false bottomRowView.translatesAutoresizingMaskIntoConstraints = false column1View.translatesAutoresizingMaskIntoConstraints = false column2View.translatesAutoresizingMaskIntoConstraints = false column3View.translatesAutoresizingMaskIntoConstraints = false view1View.translatesAutoresizingMaskIntoConstraints = false view2View.translatesAutoresizingMaskIntoConstraints = false view3View.translatesAutoresizingMaskIntoConstraints = false localAssetView.translatesAutoresizingMaskIntoConstraints = false localAsset2View.translatesAutoresizingMaskIntoConstraints = false localAsset3View.translatesAutoresizingMaskIntoConstraints = false view4View.translatesAutoresizingMaskIntoConstraints = false view5View.translatesAutoresizingMaskIntoConstraints = false view6View.translatesAutoresizingMaskIntoConstraints = false localAsset4View.translatesAutoresizingMaskIntoConstraints = false localAsset5View.translatesAutoresizingMaskIntoConstraints = false localAsset6View.translatesAutoresizingMaskIntoConstraints = false view7View.translatesAutoresizingMaskIntoConstraints = false view8View.translatesAutoresizingMaskIntoConstraints = false view9View.translatesAutoresizingMaskIntoConstraints = false localAsset7View.translatesAutoresizingMaskIntoConstraints = false localAsset8View.translatesAutoresizingMaskIntoConstraints = false localAsset9View.translatesAutoresizingMaskIntoConstraints = false column4View.translatesAutoresizingMaskIntoConstraints = false column5View.translatesAutoresizingMaskIntoConstraints = false column6View.translatesAutoresizingMaskIntoConstraints = false view10View.translatesAutoresizingMaskIntoConstraints = false view11View.translatesAutoresizingMaskIntoConstraints = false view12View.translatesAutoresizingMaskIntoConstraints = false localAsset10View.translatesAutoresizingMaskIntoConstraints = false localAsset11View.translatesAutoresizingMaskIntoConstraints = false localAsset12View.translatesAutoresizingMaskIntoConstraints = false view13View.translatesAutoresizingMaskIntoConstraints = false view14View.translatesAutoresizingMaskIntoConstraints = false view15View.translatesAutoresizingMaskIntoConstraints = false localAsset13View.translatesAutoresizingMaskIntoConstraints = false localAsset14View.translatesAutoresizingMaskIntoConstraints = false localAsset15View.translatesAutoresizingMaskIntoConstraints = false view16View.translatesAutoresizingMaskIntoConstraints = false view17View.translatesAutoresizingMaskIntoConstraints = false view18View.translatesAutoresizingMaskIntoConstraints = false localAsset16View.translatesAutoresizingMaskIntoConstraints = false localAsset17View.translatesAutoresizingMaskIntoConstraints = false localAsset18View.translatesAutoresizingMaskIntoConstraints = false let topRowViewTopAnchorConstraint = topRowView.topAnchor.constraint(equalTo: topAnchor) let topRowViewLeadingAnchorConstraint = topRowView.leadingAnchor.constraint(equalTo: leadingAnchor) let topRowViewTrailingAnchorConstraint = topRowView.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor) let bottomRowViewBottomAnchorConstraint = bottomRowView.bottomAnchor.constraint(equalTo: bottomAnchor) let bottomRowViewTopAnchorConstraint = bottomRowView.topAnchor.constraint(equalTo: topRowView.bottomAnchor) let bottomRowViewLeadingAnchorConstraint = bottomRowView.leadingAnchor.constraint(equalTo: leadingAnchor) let bottomRowViewTrailingAnchorConstraint = bottomRowView .trailingAnchor .constraint(lessThanOrEqualTo: trailingAnchor) let column1ViewHeightAnchorParentConstraint = column1View .heightAnchor .constraint(lessThanOrEqualTo: topRowView.heightAnchor) let column2ViewHeightAnchorParentConstraint = column2View .heightAnchor .constraint(lessThanOrEqualTo: topRowView.heightAnchor) let column3ViewHeightAnchorParentConstraint = column3View .heightAnchor .constraint(lessThanOrEqualTo: topRowView.heightAnchor) let column1ViewLeadingAnchorConstraint = column1View.leadingAnchor.constraint(equalTo: topRowView.leadingAnchor) let column1ViewTopAnchorConstraint = column1View.topAnchor.constraint(equalTo: topRowView.topAnchor) let column1ViewBottomAnchorConstraint = column1View.bottomAnchor.constraint(equalTo: topRowView.bottomAnchor) let column2ViewLeadingAnchorConstraint = column2View.leadingAnchor.constraint(equalTo: column1View.trailingAnchor) let column2ViewTopAnchorConstraint = column2View.topAnchor.constraint(equalTo: topRowView.topAnchor) let column2ViewBottomAnchorConstraint = column2View.bottomAnchor.constraint(equalTo: topRowView.bottomAnchor) let column3ViewTrailingAnchorConstraint = column3View.trailingAnchor.constraint(equalTo: topRowView.trailingAnchor) let column3ViewLeadingAnchorConstraint = column3View.leadingAnchor.constraint(equalTo: column2View.trailingAnchor) let column3ViewTopAnchorConstraint = column3View.topAnchor.constraint(equalTo: topRowView.topAnchor) let column3ViewBottomAnchorConstraint = column3View.bottomAnchor.constraint(equalTo: topRowView.bottomAnchor) let column4ViewHeightAnchorParentConstraint = column4View .heightAnchor .constraint(lessThanOrEqualTo: bottomRowView.heightAnchor) let column5ViewHeightAnchorParentConstraint = column5View .heightAnchor .constraint(lessThanOrEqualTo: bottomRowView.heightAnchor) let column6ViewHeightAnchorParentConstraint = column6View .heightAnchor .constraint(lessThanOrEqualTo: bottomRowView.heightAnchor) let column4ViewLeadingAnchorConstraint = column4View.leadingAnchor.constraint(equalTo: bottomRowView.leadingAnchor) let column4ViewTopAnchorConstraint = column4View.topAnchor.constraint(equalTo: bottomRowView.topAnchor) let column4ViewBottomAnchorConstraint = column4View.bottomAnchor.constraint(equalTo: bottomRowView.bottomAnchor) let column5ViewLeadingAnchorConstraint = column5View.leadingAnchor.constraint(equalTo: column4View.trailingAnchor) let column5ViewTopAnchorConstraint = column5View.topAnchor.constraint(equalTo: bottomRowView.topAnchor) let column5ViewBottomAnchorConstraint = column5View.bottomAnchor.constraint(equalTo: bottomRowView.bottomAnchor) let column6ViewTrailingAnchorConstraint = column6View .trailingAnchor .constraint(equalTo: bottomRowView.trailingAnchor) let column6ViewLeadingAnchorConstraint = column6View.leadingAnchor.constraint(equalTo: column5View.trailingAnchor) let column6ViewTopAnchorConstraint = column6View.topAnchor.constraint(equalTo: bottomRowView.topAnchor) let column6ViewBottomAnchorConstraint = column6View.bottomAnchor.constraint(equalTo: bottomRowView.bottomAnchor) let column1ViewWidthAnchorConstraint = column1View.widthAnchor.constraint(equalToConstant: 150) let view1ViewTopAnchorConstraint = view1View.topAnchor.constraint(equalTo: column1View.topAnchor) let view1ViewLeadingAnchorConstraint = view1View.leadingAnchor.constraint(equalTo: column1View.leadingAnchor) let view2ViewTopAnchorConstraint = view2View.topAnchor.constraint(equalTo: view1View.bottomAnchor) let view2ViewLeadingAnchorConstraint = view2View.leadingAnchor.constraint(equalTo: column1View.leadingAnchor) let view3ViewBottomAnchorConstraint = view3View.bottomAnchor.constraint(equalTo: column1View.bottomAnchor) let view3ViewTopAnchorConstraint = view3View.topAnchor.constraint(equalTo: view2View.bottomAnchor) let view3ViewLeadingAnchorConstraint = view3View.leadingAnchor.constraint(equalTo: column1View.leadingAnchor) let column2ViewWidthAnchorConstraint = column2View.widthAnchor.constraint(equalToConstant: 150) let view4ViewTopAnchorConstraint = view4View.topAnchor.constraint(equalTo: column2View.topAnchor) let view4ViewLeadingAnchorConstraint = view4View.leadingAnchor.constraint(equalTo: column2View.leadingAnchor) let view5ViewTopAnchorConstraint = view5View.topAnchor.constraint(equalTo: view4View.bottomAnchor) let view5ViewLeadingAnchorConstraint = view5View.leadingAnchor.constraint(equalTo: column2View.leadingAnchor) let view6ViewBottomAnchorConstraint = view6View.bottomAnchor.constraint(equalTo: column2View.bottomAnchor) let view6ViewTopAnchorConstraint = view6View.topAnchor.constraint(equalTo: view5View.bottomAnchor) let view6ViewLeadingAnchorConstraint = view6View.leadingAnchor.constraint(equalTo: column2View.leadingAnchor) let column3ViewWidthAnchorConstraint = column3View.widthAnchor.constraint(equalToConstant: 150) let view7ViewTopAnchorConstraint = view7View.topAnchor.constraint(equalTo: column3View.topAnchor) let view7ViewLeadingAnchorConstraint = view7View.leadingAnchor.constraint(equalTo: column3View.leadingAnchor) let view8ViewTopAnchorConstraint = view8View.topAnchor.constraint(equalTo: view7View.bottomAnchor) let view8ViewLeadingAnchorConstraint = view8View.leadingAnchor.constraint(equalTo: column3View.leadingAnchor) let view9ViewBottomAnchorConstraint = view9View.bottomAnchor.constraint(equalTo: column3View.bottomAnchor) let view9ViewTopAnchorConstraint = view9View.topAnchor.constraint(equalTo: view8View.bottomAnchor) let view9ViewLeadingAnchorConstraint = view9View.leadingAnchor.constraint(equalTo: column3View.leadingAnchor) let view1ViewHeightAnchorConstraint = view1View.heightAnchor.constraint(equalToConstant: 150) let view1ViewWidthAnchorConstraint = view1View.widthAnchor.constraint(equalToConstant: 150) let localAssetViewTopAnchorConstraint = localAssetView.topAnchor.constraint(equalTo: view1View.topAnchor) let localAssetViewLeadingAnchorConstraint = localAssetView .leadingAnchor .constraint(equalTo: view1View.leadingAnchor) let localAssetViewTrailingAnchorConstraint = localAssetView .trailingAnchor .constraint(equalTo: view1View.trailingAnchor) let view2ViewHeightAnchorConstraint = view2View.heightAnchor.constraint(equalToConstant: 150) let view2ViewWidthAnchorConstraint = view2View.widthAnchor.constraint(equalToConstant: 150) let localAsset2ViewTopAnchorConstraint = localAsset2View.topAnchor.constraint(equalTo: view2View.topAnchor) let localAsset2ViewLeadingAnchorConstraint = localAsset2View .leadingAnchor .constraint(equalTo: view2View.leadingAnchor) let localAsset2ViewTrailingAnchorConstraint = localAsset2View .trailingAnchor .constraint(equalTo: view2View.trailingAnchor) let view3ViewHeightAnchorConstraint = view3View.heightAnchor.constraint(equalToConstant: 150) let view3ViewWidthAnchorConstraint = view3View.widthAnchor.constraint(equalToConstant: 150) let localAsset3ViewTopAnchorConstraint = localAsset3View.topAnchor.constraint(equalTo: view3View.topAnchor) let localAsset3ViewLeadingAnchorConstraint = localAsset3View .leadingAnchor .constraint(equalTo: view3View.leadingAnchor) let localAsset3ViewTrailingAnchorConstraint = localAsset3View .trailingAnchor .constraint(equalTo: view3View.trailingAnchor) let view4ViewHeightAnchorConstraint = view4View.heightAnchor.constraint(equalToConstant: 150) let view4ViewWidthAnchorConstraint = view4View.widthAnchor.constraint(equalToConstant: 150) let localAsset4ViewTopAnchorConstraint = localAsset4View.topAnchor.constraint(equalTo: view4View.topAnchor) let localAsset4ViewLeadingAnchorConstraint = localAsset4View .leadingAnchor .constraint(equalTo: view4View.leadingAnchor) let localAsset4ViewCenterXAnchorConstraint = localAsset4View .centerXAnchor .constraint(equalTo: view4View.centerXAnchor) let localAsset4ViewTrailingAnchorConstraint = localAsset4View .trailingAnchor .constraint(equalTo: view4View.trailingAnchor) let view5ViewHeightAnchorConstraint = view5View.heightAnchor.constraint(equalToConstant: 150) let view5ViewWidthAnchorConstraint = view5View.widthAnchor.constraint(equalToConstant: 150) let localAsset5ViewTopAnchorConstraint = localAsset5View.topAnchor.constraint(equalTo: view5View.topAnchor) let localAsset5ViewLeadingAnchorConstraint = localAsset5View .leadingAnchor .constraint(equalTo: view5View.leadingAnchor) let localAsset5ViewCenterXAnchorConstraint = localAsset5View .centerXAnchor .constraint(equalTo: view5View.centerXAnchor) let localAsset5ViewTrailingAnchorConstraint = localAsset5View .trailingAnchor .constraint(equalTo: view5View.trailingAnchor) let view6ViewHeightAnchorConstraint = view6View.heightAnchor.constraint(equalToConstant: 150) let view6ViewWidthAnchorConstraint = view6View.widthAnchor.constraint(equalToConstant: 150) let localAsset6ViewTopAnchorConstraint = localAsset6View.topAnchor.constraint(equalTo: view6View.topAnchor) let localAsset6ViewLeadingAnchorConstraint = localAsset6View .leadingAnchor .constraint(equalTo: view6View.leadingAnchor) let localAsset6ViewCenterXAnchorConstraint = localAsset6View .centerXAnchor .constraint(equalTo: view6View.centerXAnchor) let localAsset6ViewTrailingAnchorConstraint = localAsset6View .trailingAnchor .constraint(equalTo: view6View.trailingAnchor) let view7ViewHeightAnchorConstraint = view7View.heightAnchor.constraint(equalToConstant: 150) let view7ViewWidthAnchorConstraint = view7View.widthAnchor.constraint(equalToConstant: 150) let localAsset7ViewTopAnchorConstraint = localAsset7View.topAnchor.constraint(equalTo: view7View.topAnchor) let localAsset7ViewLeadingAnchorConstraint = localAsset7View .leadingAnchor .constraint(equalTo: view7View.leadingAnchor) let localAsset7ViewTrailingAnchorConstraint = localAsset7View .trailingAnchor .constraint(equalTo: view7View.trailingAnchor) let view8ViewHeightAnchorConstraint = view8View.heightAnchor.constraint(equalToConstant: 150) let view8ViewWidthAnchorConstraint = view8View.widthAnchor.constraint(equalToConstant: 150) let localAsset8ViewTopAnchorConstraint = localAsset8View.topAnchor.constraint(equalTo: view8View.topAnchor) let localAsset8ViewLeadingAnchorConstraint = localAsset8View .leadingAnchor .constraint(equalTo: view8View.leadingAnchor) let localAsset8ViewTrailingAnchorConstraint = localAsset8View .trailingAnchor .constraint(equalTo: view8View.trailingAnchor) let view9ViewHeightAnchorConstraint = view9View.heightAnchor.constraint(equalToConstant: 150) let view9ViewWidthAnchorConstraint = view9View.widthAnchor.constraint(equalToConstant: 150) let localAsset9ViewTopAnchorConstraint = localAsset9View.topAnchor.constraint(equalTo: view9View.topAnchor) let localAsset9ViewLeadingAnchorConstraint = localAsset9View .leadingAnchor .constraint(equalTo: view9View.leadingAnchor) let localAsset9ViewTrailingAnchorConstraint = localAsset9View .trailingAnchor .constraint(equalTo: view9View.trailingAnchor) let column4ViewWidthAnchorConstraint = column4View.widthAnchor.constraint(equalToConstant: 150) let view10ViewTopAnchorConstraint = view10View.topAnchor.constraint(equalTo: column4View.topAnchor) let view10ViewLeadingAnchorConstraint = view10View.leadingAnchor.constraint(equalTo: column4View.leadingAnchor) let view11ViewTopAnchorConstraint = view11View.topAnchor.constraint(equalTo: view10View.bottomAnchor) let view11ViewLeadingAnchorConstraint = view11View.leadingAnchor.constraint(equalTo: column4View.leadingAnchor) let view12ViewBottomAnchorConstraint = view12View.bottomAnchor.constraint(equalTo: column4View.bottomAnchor) let view12ViewTopAnchorConstraint = view12View.topAnchor.constraint(equalTo: view11View.bottomAnchor) let view12ViewLeadingAnchorConstraint = view12View.leadingAnchor.constraint(equalTo: column4View.leadingAnchor) let column5ViewWidthAnchorConstraint = column5View.widthAnchor.constraint(equalToConstant: 150) let view13ViewTopAnchorConstraint = view13View.topAnchor.constraint(equalTo: column5View.topAnchor) let view13ViewLeadingAnchorConstraint = view13View.leadingAnchor.constraint(equalTo: column5View.leadingAnchor) let view14ViewTopAnchorConstraint = view14View.topAnchor.constraint(equalTo: view13View.bottomAnchor) let view14ViewLeadingAnchorConstraint = view14View.leadingAnchor.constraint(equalTo: column5View.leadingAnchor) let view15ViewBottomAnchorConstraint = view15View.bottomAnchor.constraint(equalTo: column5View.bottomAnchor) let view15ViewTopAnchorConstraint = view15View.topAnchor.constraint(equalTo: view14View.bottomAnchor) let view15ViewLeadingAnchorConstraint = view15View.leadingAnchor.constraint(equalTo: column5View.leadingAnchor) let column6ViewWidthAnchorConstraint = column6View.widthAnchor.constraint(equalToConstant: 150) let view16ViewTopAnchorConstraint = view16View.topAnchor.constraint(equalTo: column6View.topAnchor) let view16ViewLeadingAnchorConstraint = view16View.leadingAnchor.constraint(equalTo: column6View.leadingAnchor) let view17ViewTopAnchorConstraint = view17View.topAnchor.constraint(equalTo: view16View.bottomAnchor) let view17ViewLeadingAnchorConstraint = view17View.leadingAnchor.constraint(equalTo: column6View.leadingAnchor) let view18ViewBottomAnchorConstraint = view18View.bottomAnchor.constraint(equalTo: column6View.bottomAnchor) let view18ViewTopAnchorConstraint = view18View.topAnchor.constraint(equalTo: view17View.bottomAnchor) let view18ViewLeadingAnchorConstraint = view18View.leadingAnchor.constraint(equalTo: column6View.leadingAnchor) let view10ViewHeightAnchorConstraint = view10View.heightAnchor.constraint(equalToConstant: 150) let view10ViewWidthAnchorConstraint = view10View.widthAnchor.constraint(equalToConstant: 150) let localAsset10ViewLeadingAnchorConstraint = localAsset10View .leadingAnchor .constraint(equalTo: view10View.leadingAnchor) let localAsset10ViewTopAnchorConstraint = localAsset10View.topAnchor.constraint(equalTo: view10View.topAnchor) let localAsset10ViewBottomAnchorConstraint = localAsset10View .bottomAnchor .constraint(equalTo: view10View.bottomAnchor) let view11ViewHeightAnchorConstraint = view11View.heightAnchor.constraint(equalToConstant: 150) let view11ViewWidthAnchorConstraint = view11View.widthAnchor.constraint(equalToConstant: 150) let localAsset11ViewLeadingAnchorConstraint = localAsset11View .leadingAnchor .constraint(equalTo: view11View.leadingAnchor) let localAsset11ViewTopAnchorConstraint = localAsset11View.topAnchor.constraint(equalTo: view11View.topAnchor) let localAsset11ViewCenterYAnchorConstraint = localAsset11View .centerYAnchor .constraint(equalTo: view11View.centerYAnchor) let localAsset11ViewBottomAnchorConstraint = localAsset11View .bottomAnchor .constraint(equalTo: view11View.bottomAnchor) let view12ViewHeightAnchorConstraint = view12View.heightAnchor.constraint(equalToConstant: 150) let view12ViewWidthAnchorConstraint = view12View.widthAnchor.constraint(equalToConstant: 150) let localAsset12ViewLeadingAnchorConstraint = localAsset12View .leadingAnchor .constraint(equalTo: view12View.leadingAnchor) let localAsset12ViewTopAnchorConstraint = localAsset12View.topAnchor.constraint(equalTo: view12View.topAnchor) let localAsset12ViewBottomAnchorConstraint = localAsset12View .bottomAnchor .constraint(equalTo: view12View.bottomAnchor) let view13ViewHeightAnchorConstraint = view13View.heightAnchor.constraint(equalToConstant: 150) let view13ViewWidthAnchorConstraint = view13View.widthAnchor.constraint(equalToConstant: 150) let localAsset13ViewLeadingAnchorConstraint = localAsset13View .leadingAnchor .constraint(equalTo: view13View.leadingAnchor) let localAsset13ViewTopAnchorConstraint = localAsset13View.topAnchor.constraint(equalTo: view13View.topAnchor) let localAsset13ViewBottomAnchorConstraint = localAsset13View .bottomAnchor .constraint(equalTo: view13View.bottomAnchor) let view14ViewHeightAnchorConstraint = view14View.heightAnchor.constraint(equalToConstant: 150) let view14ViewWidthAnchorConstraint = view14View.widthAnchor.constraint(equalToConstant: 150) let localAsset14ViewLeadingAnchorConstraint = localAsset14View .leadingAnchor .constraint(equalTo: view14View.leadingAnchor) let localAsset14ViewTopAnchorConstraint = localAsset14View.topAnchor.constraint(equalTo: view14View.topAnchor) let localAsset14ViewCenterYAnchorConstraint = localAsset14View .centerYAnchor .constraint(equalTo: view14View.centerYAnchor) let localAsset14ViewBottomAnchorConstraint = localAsset14View .bottomAnchor .constraint(equalTo: view14View.bottomAnchor) let view15ViewHeightAnchorConstraint = view15View.heightAnchor.constraint(equalToConstant: 150) let view15ViewWidthAnchorConstraint = view15View.widthAnchor.constraint(equalToConstant: 150) let localAsset15ViewLeadingAnchorConstraint = localAsset15View .leadingAnchor .constraint(equalTo: view15View.leadingAnchor) let localAsset15ViewTopAnchorConstraint = localAsset15View.topAnchor.constraint(equalTo: view15View.topAnchor) let localAsset15ViewBottomAnchorConstraint = localAsset15View .bottomAnchor .constraint(equalTo: view15View.bottomAnchor) let view16ViewHeightAnchorConstraint = view16View.heightAnchor.constraint(equalToConstant: 150) let view16ViewWidthAnchorConstraint = view16View.widthAnchor.constraint(equalToConstant: 150) let localAsset16ViewLeadingAnchorConstraint = localAsset16View .leadingAnchor .constraint(equalTo: view16View.leadingAnchor) let localAsset16ViewTopAnchorConstraint = localAsset16View.topAnchor.constraint(equalTo: view16View.topAnchor) let localAsset16ViewBottomAnchorConstraint = localAsset16View .bottomAnchor .constraint(equalTo: view16View.bottomAnchor) let view17ViewHeightAnchorConstraint = view17View.heightAnchor.constraint(equalToConstant: 150) let view17ViewWidthAnchorConstraint = view17View.widthAnchor.constraint(equalToConstant: 150) let localAsset17ViewLeadingAnchorConstraint = localAsset17View .leadingAnchor .constraint(equalTo: view17View.leadingAnchor) let localAsset17ViewTopAnchorConstraint = localAsset17View.topAnchor.constraint(equalTo: view17View.topAnchor) let localAsset17ViewCenterYAnchorConstraint = localAsset17View .centerYAnchor .constraint(equalTo: view17View.centerYAnchor) let localAsset17ViewBottomAnchorConstraint = localAsset17View .bottomAnchor .constraint(equalTo: view17View.bottomAnchor) let view18ViewHeightAnchorConstraint = view18View.heightAnchor.constraint(equalToConstant: 150) let view18ViewWidthAnchorConstraint = view18View.widthAnchor.constraint(equalToConstant: 150) let localAsset18ViewLeadingAnchorConstraint = localAsset18View .leadingAnchor .constraint(equalTo: view18View.leadingAnchor) let localAsset18ViewTopAnchorConstraint = localAsset18View.topAnchor.constraint(equalTo: view18View.topAnchor) let localAsset18ViewBottomAnchorConstraint = localAsset18View .bottomAnchor .constraint(equalTo: view18View.bottomAnchor) column1ViewHeightAnchorParentConstraint.priority = UILayoutPriority.defaultLow column2ViewHeightAnchorParentConstraint.priority = UILayoutPriority.defaultLow column3ViewHeightAnchorParentConstraint.priority = UILayoutPriority.defaultLow column4ViewHeightAnchorParentConstraint.priority = UILayoutPriority.defaultLow column5ViewHeightAnchorParentConstraint.priority = UILayoutPriority.defaultLow column6ViewHeightAnchorParentConstraint.priority = UILayoutPriority.defaultLow NSLayoutConstraint.activate([ topRowViewTopAnchorConstraint, topRowViewLeadingAnchorConstraint, topRowViewTrailingAnchorConstraint, bottomRowViewBottomAnchorConstraint, bottomRowViewTopAnchorConstraint, bottomRowViewLeadingAnchorConstraint, bottomRowViewTrailingAnchorConstraint, column1ViewHeightAnchorParentConstraint, column2ViewHeightAnchorParentConstraint, column3ViewHeightAnchorParentConstraint, column1ViewLeadingAnchorConstraint, column1ViewTopAnchorConstraint, column1ViewBottomAnchorConstraint, column2ViewLeadingAnchorConstraint, column2ViewTopAnchorConstraint, column2ViewBottomAnchorConstraint, column3ViewTrailingAnchorConstraint, column3ViewLeadingAnchorConstraint, column3ViewTopAnchorConstraint, column3ViewBottomAnchorConstraint, column4ViewHeightAnchorParentConstraint, column5ViewHeightAnchorParentConstraint, column6ViewHeightAnchorParentConstraint, column4ViewLeadingAnchorConstraint, column4ViewTopAnchorConstraint, column4ViewBottomAnchorConstraint, column5ViewLeadingAnchorConstraint, column5ViewTopAnchorConstraint, column5ViewBottomAnchorConstraint, column6ViewTrailingAnchorConstraint, column6ViewLeadingAnchorConstraint, column6ViewTopAnchorConstraint, column6ViewBottomAnchorConstraint, column1ViewWidthAnchorConstraint, view1ViewTopAnchorConstraint, view1ViewLeadingAnchorConstraint, view2ViewTopAnchorConstraint, view2ViewLeadingAnchorConstraint, view3ViewBottomAnchorConstraint, view3ViewTopAnchorConstraint, view3ViewLeadingAnchorConstraint, column2ViewWidthAnchorConstraint, view4ViewTopAnchorConstraint, view4ViewLeadingAnchorConstraint, view5ViewTopAnchorConstraint, view5ViewLeadingAnchorConstraint, view6ViewBottomAnchorConstraint, view6ViewTopAnchorConstraint, view6ViewLeadingAnchorConstraint, column3ViewWidthAnchorConstraint, view7ViewTopAnchorConstraint, view7ViewLeadingAnchorConstraint, view8ViewTopAnchorConstraint, view8ViewLeadingAnchorConstraint, view9ViewBottomAnchorConstraint, view9ViewTopAnchorConstraint, view9ViewLeadingAnchorConstraint, view1ViewHeightAnchorConstraint, view1ViewWidthAnchorConstraint, localAssetViewTopAnchorConstraint, localAssetViewLeadingAnchorConstraint, localAssetViewTrailingAnchorConstraint, view2ViewHeightAnchorConstraint, view2ViewWidthAnchorConstraint, localAsset2ViewTopAnchorConstraint, localAsset2ViewLeadingAnchorConstraint, localAsset2ViewTrailingAnchorConstraint, view3ViewHeightAnchorConstraint, view3ViewWidthAnchorConstraint, localAsset3ViewTopAnchorConstraint, localAsset3ViewLeadingAnchorConstraint, localAsset3ViewTrailingAnchorConstraint, view4ViewHeightAnchorConstraint, view4ViewWidthAnchorConstraint, localAsset4ViewTopAnchorConstraint, localAsset4ViewLeadingAnchorConstraint, localAsset4ViewCenterXAnchorConstraint, localAsset4ViewTrailingAnchorConstraint, view5ViewHeightAnchorConstraint, view5ViewWidthAnchorConstraint, localAsset5ViewTopAnchorConstraint, localAsset5ViewLeadingAnchorConstraint, localAsset5ViewCenterXAnchorConstraint, localAsset5ViewTrailingAnchorConstraint, view6ViewHeightAnchorConstraint, view6ViewWidthAnchorConstraint, localAsset6ViewTopAnchorConstraint, localAsset6ViewLeadingAnchorConstraint, localAsset6ViewCenterXAnchorConstraint, localAsset6ViewTrailingAnchorConstraint, view7ViewHeightAnchorConstraint, view7ViewWidthAnchorConstraint, localAsset7ViewTopAnchorConstraint, localAsset7ViewLeadingAnchorConstraint, localAsset7ViewTrailingAnchorConstraint, view8ViewHeightAnchorConstraint, view8ViewWidthAnchorConstraint, localAsset8ViewTopAnchorConstraint, localAsset8ViewLeadingAnchorConstraint, localAsset8ViewTrailingAnchorConstraint, view9ViewHeightAnchorConstraint, view9ViewWidthAnchorConstraint, localAsset9ViewTopAnchorConstraint, localAsset9ViewLeadingAnchorConstraint, localAsset9ViewTrailingAnchorConstraint, column4ViewWidthAnchorConstraint, view10ViewTopAnchorConstraint, view10ViewLeadingAnchorConstraint, view11ViewTopAnchorConstraint, view11ViewLeadingAnchorConstraint, view12ViewBottomAnchorConstraint, view12ViewTopAnchorConstraint, view12ViewLeadingAnchorConstraint, column5ViewWidthAnchorConstraint, view13ViewTopAnchorConstraint, view13ViewLeadingAnchorConstraint, view14ViewTopAnchorConstraint, view14ViewLeadingAnchorConstraint, view15ViewBottomAnchorConstraint, view15ViewTopAnchorConstraint, view15ViewLeadingAnchorConstraint, column6ViewWidthAnchorConstraint, view16ViewTopAnchorConstraint, view16ViewLeadingAnchorConstraint, view17ViewTopAnchorConstraint, view17ViewLeadingAnchorConstraint, view18ViewBottomAnchorConstraint, view18ViewTopAnchorConstraint, view18ViewLeadingAnchorConstraint, view10ViewHeightAnchorConstraint, view10ViewWidthAnchorConstraint, localAsset10ViewLeadingAnchorConstraint, localAsset10ViewTopAnchorConstraint, localAsset10ViewBottomAnchorConstraint, view11ViewHeightAnchorConstraint, view11ViewWidthAnchorConstraint, localAsset11ViewLeadingAnchorConstraint, localAsset11ViewTopAnchorConstraint, localAsset11ViewCenterYAnchorConstraint, localAsset11ViewBottomAnchorConstraint, view12ViewHeightAnchorConstraint, view12ViewWidthAnchorConstraint, localAsset12ViewLeadingAnchorConstraint, localAsset12ViewTopAnchorConstraint, localAsset12ViewBottomAnchorConstraint, view13ViewHeightAnchorConstraint, view13ViewWidthAnchorConstraint, localAsset13ViewLeadingAnchorConstraint, localAsset13ViewTopAnchorConstraint, localAsset13ViewBottomAnchorConstraint, view14ViewHeightAnchorConstraint, view14ViewWidthAnchorConstraint, localAsset14ViewLeadingAnchorConstraint, localAsset14ViewTopAnchorConstraint, localAsset14ViewCenterYAnchorConstraint, localAsset14ViewBottomAnchorConstraint, view15ViewHeightAnchorConstraint, view15ViewWidthAnchorConstraint, localAsset15ViewLeadingAnchorConstraint, localAsset15ViewTopAnchorConstraint, localAsset15ViewBottomAnchorConstraint, view16ViewHeightAnchorConstraint, view16ViewWidthAnchorConstraint, localAsset16ViewLeadingAnchorConstraint, localAsset16ViewTopAnchorConstraint, localAsset16ViewBottomAnchorConstraint, view17ViewHeightAnchorConstraint, view17ViewWidthAnchorConstraint, localAsset17ViewLeadingAnchorConstraint, localAsset17ViewTopAnchorConstraint, localAsset17ViewCenterYAnchorConstraint, localAsset17ViewBottomAnchorConstraint, view18ViewHeightAnchorConstraint, view18ViewWidthAnchorConstraint, localAsset18ViewLeadingAnchorConstraint, localAsset18ViewTopAnchorConstraint, localAsset18ViewBottomAnchorConstraint ]) } private func update() {} }
56.494574
119
0.819863
2819ac1973244f79adf1fcc0172052012b7dfb81
1,865
// // LoginLinkStack.swift // FitGoal // // Created by Eliany Barrera on 20/3/20. // Copyright © 2020 Eliany Barrera. All rights reserved. // import UIKit protocol AuthenticationTypeSwitcherViewDelegate: AnyObject { func userDidSwitchAuthenticationType() } class AuthenticationTypeSwitcherView: UIStackView { private var question = UILabel() private var link = UIButton(type: .system) weak var delegate: AuthenticationTypeSwitcherViewDelegate? convenience init(type: AuthenticationType) { self.init(frame: .zero) var questionText = String() var linkText = String() switch type { case .signUp: questionText = "Don't have an account?" linkText = "Signup" case .login: questionText = "Already onboard?" linkText = "Login" } question.attributedText = questionText.formattedText( font: "Roboto-Light", size: 15, color: UIColor(red: 0.52, green: 0.53, blue: 0.57, alpha: 1), kern: 0 ) link.setAttributedTitle(linkText.formattedText( font: "Roboto-Light", size: 15, color: UIColor(red: 0.24, green: 0.78, blue: 0.9, alpha: 1), kern: 0 ), for: .normal) link.addTarget(self, action: #selector(handleTap), for: .touchUpInside) } @objc private func handleTap() { delegate?.userDidSwitchAuthenticationType() } override init(frame: CGRect) { super.init(frame: frame) axis = .horizontal alignment = .center spacing = 8 addArrangedSubview(question) addArrangedSubview(link) } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
27.028986
79
0.587668
d58ae886024c6b7919a34f7cc8d1dc562d86ae50
1,338
// // NSDictionary+KeyPathConvenience.swift // InRoZe // // Created by Erick Olibo on 03/08/2017. // Copyright © 2017 Erick Olibo. All rights reserved. // import Foundation extension NSDictionary { func double(forKeyPath keyPath: String) -> Double? { return value(forKeyPath: keyPath) as? Double } func int(forKeyPath keyPath: String) -> Int? { return value(forKeyPath: keyPath) as? Int } func string(forKeyPath keyPath: String) -> String? { return value(forKeyPath: keyPath) as? String } func bool(forKeyPath keyPath: String) -> Bool? { return (value(forKeyPath: keyPath) as? NSNumber)?.boolValue } func url(forKeyPath keyPath: String) -> URL? { if let urlString = string(forKeyPath: keyPath), urlString.count > 0, let url = URL(string: urlString) { return url } else { return nil } } func colors(forKeyPath keyPath: String) -> UIImageColors? { return value(forKeyPath: keyPath) as? UIImageColors } func dictionary(forKeyPath keyPath: String) -> NSDictionary? { return value(forKeyPath: keyPath) as? NSDictionary } func array(forKeyPath keyPath: String) -> NSArray? { return value(forKeyPath: keyPath) as? NSArray } }
26.76
111
0.621824
8f01ae1ff35e451e624da25d1fdac1719c39c918
513
// // UIView+Extension.swift // Pods // // Created by Lolo on 27/06/2016. // // import UIKit extension UIView { public func addBorders(_ width: CGFloat, color: UIColor) { addBorders(width, color: color, radius: 0.0) } public func addBorders(_ width: CGFloat, color: UIColor, radius: CGFloat) { self.layer.borderWidth = width self.layer.borderColor = color.cgColor self.layer.cornerRadius = radius self.clipsToBounds = true } }
19
79
0.612086
0a423970a6280d8b4e8e25311b87991676bbfabc
2,174
// // AppDelegate.swift // TipCalculator // // Created by cs_apple_04 on 9/12/19. // Copyright © 2019 codepath. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.255319
285
0.75575
21cb60dca557d7aa500da5115d93bf4b767afcd4
1,004
// Copyright 2020 Tokamak contributors // // 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. // // Created by Carson Katri on 06/29/2020. // /// A `View` that fills the major axis of its parent stack. /// /// HStack { /// Text("Hello") /// Spacer() /// Text("World") /// } public struct Spacer: View { public var minLength: CGFloat? public init(minLength: CGFloat? = nil) { self.minLength = minLength } public var body: Never { neverBody("Spacer") } }
27.888889
75
0.678287
33c88b6411c42ea53fecebf210b97eba213a6fc9
27,710
// // SideMenuNavigationController.swift // // Created by Jon Kent on 1/14/16. // Copyright © 2016 Jon Kent. All rights reserved. // import UIKit @objc public enum SideMenuPushStyle: Int { case `default`, popWhenPossible, preserve, preserveAndHideBackButton, replace, subMenu internal var hidesBackButton: Bool { switch self { case .preserveAndHideBackButton, .replace: return true case .default, .popWhenPossible, .preserve, .subMenu: return false } } } internal protocol MenuModel { /// Prevents the same view controller (or a view controller of the same class) from being pushed more than once. Defaults to true. var allowPushOfSameClassTwice: Bool { get } /// Forces menus to always animate when appearing or disappearing, regardless of a pushed view controller's animation. var alwaysAnimate: Bool { get } /** The blur effect style of the menu if the menu's root view controller is a UITableViewController or UICollectionViewController. - Note: If you want cells in a UITableViewController menu to show vibrancy, make them a subclass of UITableViewVibrantCell. */ var blurEffectStyle: UIBlurEffect.Style? { get } /// Animation curve of the remaining animation when the menu is partially dismissed with gestures. Default is .easeIn. var completionCurve: UIView.AnimationCurve { get } /// Automatically dismisses the menu when another view is presented from it. var dismissOnPresent: Bool { get } /// Automatically dismisses the menu when another view controller is pushed from it. var dismissOnPush: Bool { get } /// Automatically dismisses the menu when the screen is rotated. var dismissOnRotation: Bool { get } /// Automatically dismisses the menu when app goes to the background. var dismissWhenBackgrounded: Bool { get } /// Enable or disable a swipe gesture that dismisses the menu. Will not be triggered when `presentingViewControllerUserInteractionEnabled` is set to true. Default is true. var enableSwipeToDismissGesture: Bool { get } /// Enable or disable a tap gesture that dismisses the menu. Will not be triggered when `presentingViewControllerUserInteractionEnabled` is set to true. Default is true. var enableTapToDismissGesture: Bool { get } /** The push style of the menu. There are six modes in MenuPushStyle: - defaultBehavior: The view controller is pushed onto the stack. - popWhenPossible: If a view controller already in the stack is of the same class as the pushed view controller, the stack is instead popped back to the existing view controller. This behavior can help users from getting lost in a deep navigation stack. - preserve: If a view controller already in the stack is of the same class as the pushed view controller, the existing view controller is pushed to the end of the stack. This behavior is similar to a UITabBarController. - preserveAndHideBackButton: Same as .preserve and back buttons are automatically hidden. - replace: Any existing view controllers are released from the stack and replaced with the pushed view controller. Back buttons are automatically hidden. This behavior is ideal if view controllers require a lot of memory or their state doesn't need to be preserved.. - subMenu: Unlike all other behaviors that push using the menu's presentingViewController, this behavior pushes view controllers within the menu. Use this behavior if you want to display a sub menu. */ var pushStyle: SideMenuPushStyle { get } } @objc public protocol SideMenuNavigationControllerDelegate { @objc optional func sideMenuWillAppear(menu: SideMenuNavigationController, animated: Bool) @objc optional func sideMenuDidAppear(menu: SideMenuNavigationController, animated: Bool) @objc optional func sideMenuWillDisappear(menu: SideMenuNavigationController, animated: Bool) @objc optional func sideMenuDidDisappear(menu: SideMenuNavigationController, animated: Bool) } internal protocol SideMenuNavigationControllerTransitionDelegate: AnyObject { func sideMenuTransitionDidDismiss(menu: Menu) } public struct SideMenuSettings: Model, InitializableStruct { public var allowPushOfSameClassTwice: Bool = true public var alwaysAnimate: Bool = true public var animationOptions: UIView.AnimationOptions = .curveEaseInOut public var blurEffectStyle: UIBlurEffect.Style? public var completeGestureDuration: Double = 0.35 public var completionCurve: UIView.AnimationCurve = .easeIn public var dismissDuration: Double = 0.35 public var dismissOnPresent: Bool = true public var dismissOnPush: Bool = true public var dismissOnRotation: Bool = true public var dismissWhenBackgrounded: Bool = true public var enableSwipeToDismissGesture: Bool = true public var enableTapToDismissGesture: Bool = true public var initialSpringVelocity: CGFloat = 1 public var menuWidth: CGFloat = { let appScreenRect = UIApplication.shared.keyWindow?.bounds ?? UIWindow().bounds let minimumSize = min(appScreenRect.width, appScreenRect.height) return min(round(minimumSize * 0.75), 240) }() public var presentingViewControllerUserInteractionEnabled: Bool = false public var presentingViewControllerUseSnapshot: Bool = false public var presentDuration: Double = 0.35 public var presentationStyle: SideMenuPresentationStyle = .viewSlideOut public var pushStyle: SideMenuPushStyle = .default public var statusBarEndAlpha: CGFloat = 0 public var usingSpringWithDamping: CGFloat = 1 public init() {} } internal typealias Menu = SideMenuNavigationController typealias Model = MenuModel & PresentationModel & AnimationModel @objcMembers open class SideMenuNavigationController: UINavigationController { private lazy var _leftSide = Protected(false) { [weak self] oldValue, newValue in guard self?.isHidden != false else { Print.warning(.property, arguments: .leftSide, required: true) return oldValue } return newValue } private weak var _sideMenuManager: SideMenuManager? private weak var foundViewController: UIViewController? private var originalBackgroundColor: UIColor? private var rotating: Bool = false private var transitionController: SideMenuTransitionController? private var transitionInteractive: Bool = false /// Delegate for receiving appear and disappear related events. If `nil` the visible view controller that displays a `SideMenuNavigationController` automatically receives these events. public weak var sideMenuDelegate: SideMenuNavigationControllerDelegate? /// The swipe to dismiss gesture. open private(set) weak var swipeToDismissGesture: UIPanGestureRecognizer? /// The tap to dismiss gesture. open private(set) weak var tapToDismissGesture: UITapGestureRecognizer? open var sideMenuManager: SideMenuManager { get { return _sideMenuManager ?? SideMenuManager.default } set { newValue.setMenu(self, forLeftSide: leftSide) if let sideMenuManager = _sideMenuManager, sideMenuManager !== newValue { let side = SideMenuManager.PresentDirection(leftSide: leftSide) Print.warning(.menuAlreadyAssigned, arguments: String(describing: self.self), side.name, String(describing: newValue)) } _sideMenuManager = newValue } } /// The menu settings. open var settings = SideMenuSettings() { didSet { setupBlur() if !enableSwipeToDismissGesture { swipeToDismissGesture?.remove() } if !enableTapToDismissGesture { tapToDismissGesture?.remove() } } } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) setup() } public init(rootViewController: UIViewController, settings: SideMenuSettings = SideMenuSettings()) { self.settings = settings super.init(rootViewController: rootViewController) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override open func awakeFromNib() { super.awakeFromNib() sideMenuManager.setMenu(self, forLeftSide: leftSide) } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if topViewController == nil { Print.warning(.emptyMenu) } // Dismiss keyboard to prevent weird keyboard animations from occurring during transition presentingViewController?.view.endEditing(true) foundViewController = nil activeDelegate?.sideMenuWillAppear?(menu: self, animated: animated) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // We had presented a view before, so lets dismiss ourselves as already acted upon if view.isHidden { dismiss(animated: false, completion: { [weak self] in self?.view.isHidden = false }) } else { activeDelegate?.sideMenuDidAppear?(menu: self, animated: animated) } } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) defer { activeDelegate?.sideMenuWillDisappear?(menu: self, animated: animated) } guard !isBeingDismissed else { return } // When presenting a view controller from the menu, the menu view gets moved into another transition view above our transition container // which can break the visual layout we had before. So, we move the menu view back to its original transition view to preserve it. if let presentingView = presentingViewController?.view, let containerView = presentingView.superview { containerView.addSubview(view) } if dismissOnPresent { // We're presenting a view controller from the menu, so we need to hide the menu so it isn't showing when the presented view is dismissed. transitionController?.transition(presenting: false, animated: animated, alongsideTransition: { [weak self] in guard let self = self else { return } self.activeDelegate?.sideMenuWillDisappear?(menu: self, animated: animated) }, complete: false, completion: { [weak self] _ in guard let self = self else { return } self.activeDelegate?.sideMenuDidDisappear?(menu: self, animated: animated) self.view.isHidden = true }) } } override open func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) // Work-around: if the menu is dismissed without animation the transition logic is never called to restore the // the view hierarchy leaving the screen black/empty. This is because the transition moves views within a container // view, but dismissing without animation removes the container view before the original hierarchy is restored. // This check corrects that. if isBeingDismissed { transitionController?.transition(presenting: false, animated: false) } // Clear selection on UITableViewControllers when reappearing using custom transitions if let tableViewController = topViewController as? UITableViewController, let tableView = tableViewController.tableView, let indexPaths = tableView.indexPathsForSelectedRows, tableViewController.clearsSelectionOnViewWillAppear { indexPaths.forEach { tableView.deselectRow(at: $0, animated: false) } } activeDelegate?.sideMenuDidDisappear?(menu: self, animated: animated) if isBeingDismissed { transitionController = nil } else if dismissOnPresent { view.isHidden = true } } override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // Don't bother resizing if the view isn't visible guard let transitionController = transitionController, !view.isHidden else { return } rotating = true let dismiss = self.presentingViewControllerUseSnapshot || self.dismissOnRotation coordinator.animate(alongsideTransition: { _ in if dismiss { transitionController.transition(presenting: false, animated: false, complete: false) } else { transitionController.layout() } }) { [weak self] _ in guard let self = self else { return } if dismiss { self.dismissMenu(animated: false) } self.rotating = false } } open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() transitionController?.layout() } override open func pushViewController(_ viewController: UIViewController, animated: Bool) { guard viewControllers.count > 0 else { // NOTE: pushViewController is called by init(rootViewController: UIViewController) // so we must perform the normal super method in this case return super.pushViewController(viewController, animated: animated) } var alongsideTransition: (() -> Void)? if dismissOnPush { alongsideTransition = { [weak self] in guard let self = self else { return } self.dismissAnimation(animated: animated || self.alwaysAnimate) } } let pushed = SideMenuPushCoordinator(config: .init( allowPushOfSameClassTwice: allowPushOfSameClassTwice, alongsideTransition: alongsideTransition, animated: animated, fromViewController: self, pushStyle: pushStyle, toViewController: viewController ) ).start() if !pushed { super.pushViewController(viewController, animated: animated) } } override open var transitioningDelegate: UIViewControllerTransitioningDelegate? { get { guard transitionController == nil else { return transitionController } transitionController = SideMenuTransitionController(leftSide: leftSide, config: settings) transitionController?.delegate = self transitionController?.interactive = transitionInteractive transitionInteractive = false return transitionController } set { // swiftlint:disable:this unused_setter_value Print.warning(.transitioningDelegate, required: true) } } } // Interface extension SideMenuNavigationController: Model { @IBInspectable open var allowPushOfSameClassTwice: Bool { get { return settings.allowPushOfSameClassTwice } set { settings.allowPushOfSameClassTwice = newValue } } @IBInspectable open var alwaysAnimate: Bool { get { return settings.alwaysAnimate } set { settings.alwaysAnimate = newValue } } open var animationOptions: UIView.AnimationOptions { get { return settings.animationOptions } set { settings.animationOptions = newValue } } @IBInspectable open var animationOptionsIBAdapter: UInt { get { return settings.animationOptions.rawValue } set { settings.animationOptions = UIView.AnimationOptions(rawValue: newValue) } } open var blurEffectStyle: UIBlurEffect.Style? { get { return settings.blurEffectStyle } set { settings.blurEffectStyle = newValue } } @IBInspectable open var completeGestureDuration: Double { get { return settings.completeGestureDuration } set { settings.completeGestureDuration = newValue } } open var completionCurve: UIView.AnimationCurve { get { return settings.completionCurve } set { settings.completionCurve = newValue } } @IBInspectable open var completionCurveIBAdapter: Int { get { return settings.completionCurve.rawValue } set { settings.completionCurve = UIView.AnimationCurve(rawValue: newValue) ?? .easeInOut } } @IBInspectable open var dismissDuration: Double { get { return settings.dismissDuration } set { settings.dismissDuration = newValue } } @IBInspectable open var dismissOnPresent: Bool { get { return settings.dismissOnPresent } set { settings.dismissOnPresent = newValue } } @IBInspectable open var dismissOnPush: Bool { get { return settings.dismissOnPush } set { settings.dismissOnPush = newValue } } @IBInspectable open var dismissOnRotation: Bool { get { return settings.dismissOnRotation } set { settings.dismissOnRotation = newValue } } @IBInspectable open var dismissWhenBackgrounded: Bool { get { return settings.dismissWhenBackgrounded } set { settings.dismissWhenBackgrounded = newValue } } @IBInspectable open var enableSwipeToDismissGesture: Bool { get { return settings.enableSwipeToDismissGesture } set { settings.enableSwipeToDismissGesture = newValue } } @IBInspectable open var enableTapToDismissGesture: Bool { get { return settings.enableTapToDismissGesture } set { settings.enableTapToDismissGesture = newValue } } @IBInspectable open var initialSpringVelocity: CGFloat { get { return settings.initialSpringVelocity } set { settings.initialSpringVelocity = newValue } } /// Whether the menu appears on the right or left side of the screen. Right is the default. This property cannot be changed after the menu has loaded. @IBInspectable open var leftSide: Bool { get { return _leftSide.value } set { _leftSide.value = newValue } } /// Indicates if the menu is anywhere in the view hierarchy, even if covered by another view controller. open override var isHidden: Bool { return super.isHidden } @IBInspectable open var menuWidth: CGFloat { get { return settings.menuWidth } set { settings.menuWidth = newValue } } @IBInspectable open var presentingViewControllerUserInteractionEnabled: Bool { get { return settings.presentingViewControllerUserInteractionEnabled } set { settings.presentingViewControllerUserInteractionEnabled = newValue } } @IBInspectable open var presentingViewControllerUseSnapshot: Bool { get { return settings.presentingViewControllerUseSnapshot } set { settings.presentingViewControllerUseSnapshot = newValue } } @IBInspectable open var presentDuration: Double { get { return settings.presentDuration } set { settings.presentDuration = newValue } } open var presentationStyle: SideMenuPresentationStyle { get { return settings.presentationStyle } set { settings.presentationStyle = newValue } } open var pushStyle: SideMenuPushStyle { get { return settings.pushStyle } set { settings.pushStyle = newValue } } @IBInspectable open var pushStyleIBAdapter: Int { get { return settings.pushStyle.rawValue } set { settings.pushStyle = SideMenuPushStyle(rawValue: newValue) ?? .default } } @IBInspectable open var statusBarEndAlpha: CGFloat { get { return settings.statusBarEndAlpha } set { settings.statusBarEndAlpha = newValue } } @IBInspectable open var usingSpringWithDamping: CGFloat { get { return settings.usingSpringWithDamping } set { settings.usingSpringWithDamping = newValue } } } extension SideMenuNavigationController: SideMenuTransitionControllerDelegate { func sideMenuTransitionController(_ transitionController: SideMenuTransitionController, didDismiss viewController: UIViewController) { sideMenuManager.sideMenuTransitionDidDismiss(menu: self) } func sideMenuTransitionController(_ transitionController: SideMenuTransitionController, didPresent viewController: UIViewController) { swipeToDismissGesture?.remove() swipeToDismissGesture = addSwipeToDismissGesture(to: view.superview) tapToDismissGesture = addTapToDismissGesture(to: view.superview) } } internal extension SideMenuNavigationController { func handleMenuPan(_ gesture: UIPanGestureRecognizer, _ presenting: Bool) { let width = menuWidth let distance = gesture.xTranslation / width let progress = max(min(distance * factor(presenting), 1), 0) switch gesture.state { case .began: if !presenting { dismissMenu(interactively: true) } fallthrough case .changed: transitionController?.handle(state: .update(progress: progress)) case .ended: let velocity = gesture.xVelocity * factor(presenting) let finished = velocity >= 100 || velocity >= -50 && abs(progress) >= 0.5 transitionController?.handle(state: finished ? .finish : .cancel) default: transitionController?.handle(state: .cancel) } } func cancelMenuPan(_ gesture: UIPanGestureRecognizer) { transitionController?.handle(state: .cancel) } func dismissMenu(animated flag: Bool = true, interactively: Bool = false, completion: (() -> Void)? = nil) { guard !isHidden else { return } transitionController?.interactive = interactively dismiss(animated: flag, completion: completion) } // Note: although this method is syntactically reversed it allows the interactive property to scoped privately func present(from viewController: UIViewController?, interactively: Bool, completion: (() -> Void)? = nil) { guard let viewController = viewController else { return } transitionInteractive = interactively viewController.present(self, animated: true, completion: completion) } } private extension SideMenuNavigationController { weak var activeDelegate: SideMenuNavigationControllerDelegate? { guard !view.isHidden else { return nil } if let sideMenuDelegate = sideMenuDelegate { return sideMenuDelegate } return findViewController as? SideMenuNavigationControllerDelegate } var findViewController: UIViewController? { foundViewController = foundViewController ?? presentingViewController?.activeViewController return foundViewController } func dismissAnimation(animated: Bool) { transitionController?.transition(presenting: false, animated: animated, alongsideTransition: { [weak self] in guard let self = self else { return } self.activeDelegate?.sideMenuWillDisappear?(menu: self, animated: animated) }, completion: { [weak self] _ in guard let self = self else { return } self.activeDelegate?.sideMenuDidDisappear?(menu: self, animated: animated) self.dismiss(animated: false, completion: nil) self.foundViewController = nil }) } func setup() { modalPresentationStyle = .overFullScreen setupBlur() if #available(iOS 13.0, *) {} else { registerForNotifications() } } func setupBlur() { removeBlur() guard let blurEffectStyle = blurEffectStyle, let view = topViewController?.view, !UIAccessibility.isReduceTransparencyEnabled else { return } originalBackgroundColor = originalBackgroundColor ?? view.backgroundColor let blurEffect = UIBlurEffect(style: blurEffectStyle) let blurView = UIVisualEffectView(effect: blurEffect) view.backgroundColor = UIColor.clear if let tableViewController = topViewController as? UITableViewController { tableViewController.tableView.backgroundView = blurView tableViewController.tableView.separatorEffect = UIVibrancyEffect(blurEffect: blurEffect) tableViewController.tableView.reloadData() } else { blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth] blurView.frame = view.bounds view.insertSubview(blurView, at: 0) } } func removeBlur() { guard let originalBackgroundColor = originalBackgroundColor, let view = topViewController?.view else { return } self.originalBackgroundColor = nil view.backgroundColor = originalBackgroundColor if let tableViewController = topViewController as? UITableViewController { tableViewController.tableView.backgroundView = nil tableViewController.tableView.separatorEffect = nil tableViewController.tableView.reloadData() } else if let blurView = view.subviews.first as? UIVisualEffectView { blurView.removeFromSuperview() } } @available(iOS, deprecated: 13.0) func registerForNotifications() { NotificationCenter.default.removeObserver(self) [UIApplication.willChangeStatusBarFrameNotification, UIApplication.didEnterBackgroundNotification].forEach { NotificationCenter.default.addObserver(self, selector: #selector(handleNotification), name: $0, object: nil) } } @available(iOS, deprecated: 13.0) @objc func handleNotification(notification: NSNotification) { guard isHidden else { return } switch notification.name { case UIApplication.willChangeStatusBarFrameNotification: // Dismiss for in-call status bar changes but not rotation if !rotating { dismissMenu() } case UIApplication.didEnterBackgroundNotification: if dismissWhenBackgrounded { dismissMenu() } default: break } } @discardableResult func addSwipeToDismissGesture(to view: UIView?) -> UIPanGestureRecognizer? { guard enableSwipeToDismissGesture else { return nil } return UIPanGestureRecognizer(addTo: view, target: self, action: #selector(handleDismissMenuPan(_:)))?.with { $0.cancelsTouchesInView = false } } @discardableResult func addTapToDismissGesture(to view: UIView?) -> UITapGestureRecognizer? { guard enableTapToDismissGesture else { return nil } return UITapGestureRecognizer(addTo: view, target: self, action: #selector(handleDismissMenuTap(_:)))?.with { $0.cancelsTouchesInView = false } } @objc func handleDismissMenuTap(_ tap: UITapGestureRecognizer) { let hitTest = view.window?.hitTest(tap.location(in: view.superview), with: nil) guard hitTest == view.superview else { return } dismissMenu() } @objc func handleDismissMenuPan(_ gesture: UIPanGestureRecognizer) { handleMenuPan(gesture, false) } func factor(_ presenting: Bool) -> CGFloat { return presenting ? presentFactor : hideFactor } var presentFactor: CGFloat { return leftSide ? 1 : -1 } var hideFactor: CGFloat { return -presentFactor } }
41.11276
271
0.68708
e886cfa022b6e18c15ae26c61043d30b42b192b3
233
// // AppGroup.swift // Rocket.Chat // // Created by Matheus Cardoso on 3/5/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation struct AppGroup { static let identifier = "group.ios.chat.rocket" }
16.642857
54
0.682403
f758044d6607be3e0a2a46e43466f075eedf772a
2,005
// // MyNavigationController.swift // News_c // // Created by 杨博兴 on 2018/2/28. // Copyright © 2018年 xx_cc. All rights reserved. // import UIKit import SwiftTheme class MyNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() let navigationBar = UINavigationBar.appearance() navigationBar.theme_tintColor = "colors.black" navigationBar.setBackgroundImage(UIImage.init(named: "navigation_background" + (UserDefaults.standard.bool(forKey: isNight) ? "_night" : "")), for: UIBarMetrics.default) // 添加通知 NotificationCenter.default.addObserver(self, selector: #selector(receiveDayOrNightButtonClicked), name: NSNotification.Name(rawValue : "dayOrNightButtonClicked"), object: nil) } @objc func receiveDayOrNightButtonClicked(notification : NSNotification) { // 设置为夜间/日间 navigationBar.setBackgroundImage(UIImage.init(named: "navigation_background" + (notification.object as! Bool ? "_night" : "")), for: UIBarMetrics.default) } // 拦截 push 操作 override func pushViewController(_ viewController: UIViewController, animated: Bool) { if self.viewControllers.count > 0 { viewController.hidesBottomBarWhenPushed = true // 通知设置push进界面之后的nav的左边按钮 viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "lefterbackicon_titlebar_24x24_"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(navigationBack)) } super.pushViewController(viewController, animated: animated) } // 返回上一控制器 @objc func navigationBack() -> Void { popViewController(animated: true) } deinit { NotificationCenter.default.removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
35.175439
223
0.687282
38ac30c6b272db1036c92608cf20477c17200fc2
4,067
// // ViewController.swift // NetStatusDemo // // Created by Gabriel Theodoropoulos. // Copyright © 2019 Appcoda. All rights reserved. // import UIKit import NetStatus class ViewController: UIViewController { // MARK: - IBOutlet Properties @IBOutlet weak var tableView: UITableView! @IBOutlet weak var monitorButton: UIButton! // MARK: - VC Lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. configureTableView() monitorButton.layer.cornerRadius = 15.0 NetStatus.shared.didStartMonitoringHandler = { [unowned self] in self.monitorButton.setTitle("Stop Monitoring", for: .normal) } NetStatus.shared.didStopMonitoringHandler = { [unowned self] in self.monitorButton.setTitle("Start Monitoring", for: .normal) self.tableView.reloadData() } NetStatus.shared.netStatusChangeHandler = { DispatchQueue.main.async { [unowned self] in self.tableView.reloadData() } } } // MARK: - Custom Methods func configureTableView() { tableView.dataSource = self tableView.showsVerticalScrollIndicator = false tableView.showsHorizontalScrollIndicator = false tableView.isScrollEnabled = false tableView.alwaysBounceVertical = false tableView.backgroundColor = UIColor.clear tableView.isScrollEnabled = true tableView.tableFooterView = UIView(frame: CGRect.zero) tableView.register(UINib(nibName: "InfoCell", bundle: nil), forCellReuseIdentifier: "infoCell") } // MARK: - IBAction Methods @IBAction func toggleMonitoring(_ sender: Any) { if !NetStatus.shared.isMonitoring { NetStatus.shared.startMonitoring() } else { NetStatus.shared.stopMonitoring() } } } // MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section != 1 ? 1 : NetStatus.shared.availableInterfacesTypes?.count ?? 0 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Connected" case 1: return "Interface Types" case 2: return "Is Expensive" default: return nil } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "infoCell", for: indexPath) as! InfoCell switch indexPath.section { case 0: cell.label?.text = NetStatus.shared.isConnected ? "Connected" : "Not Connected" cell.indicationImageView.image = NetStatus.shared.isConnected ? UIImage(named: "checkmark") : UIImage(named: "delete") case 1: if let interfaceType = NetStatus.shared.availableInterfacesTypes?[indexPath.row] { cell.label?.text = "\(interfaceType)" if let currentInterfaceType = NetStatus.shared.interfaceType { cell.indicationImageView.image = (interfaceType == currentInterfaceType) ? UIImage(named: "checkmark") : nil } } case 2: cell.label?.text = NetStatus.shared.isExpensive ? "Expensive" : "Not Expensive" cell.indicationImageView.image = NetStatus.shared.isExpensive ? UIImage(named: "warning") : nil default: () } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60.0 } }
30.578947
130
0.61372
4b52a33def137f624c5049240201bed8df100be9
7,779
// // SheetContentsViewController.swift // Sheeeeeeeeet // // Created by Gwangbeom on 2018. 9. 29.. // Copyright © 2018년 GwangBeom. All rights reserved. // import UIKit open class SheetContentsViewController: UICollectionViewController, SheetContent { private var options: SheetOptions { return SheetManager.shared.options } private var layout = SheetContentsLayout() public var topMargin: CGFloat = 0 public var contentScrollView: UIScrollView { return collectionView } open var isFullScreenContent: Bool { return false } /// Sheet ToolBar hide property. Defaults to false open var isToolBarHidden: Bool { return options.isToolBarHidden } /// Sheet visible contents height. If contentSize height is less than visibleContentsHeight, contentSize height is applied. open var visibleContentsHeight: CGFloat { return SheetManager.shared.options.defaultVisibleContentHeight } open var sheetToolBar: UIView? { return nil } open override func viewDidLoad() { super.viewDidLoad() registCollectionElement() setupSheetLayout(layout) setupViews() } open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) updateTopMargin() } /// Give CollectionView a chance to regulate Supplementray Element open func registCollectionElement() { } /// Provide an opportunity to set default settings for collectionview custom layout open func setupSheetLayout(_ layout: SheetContentsLayout) { } open override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { fatalError("Implement with override as required") } open override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { fatalError("Implement with override as required") } open override func scrollViewDidScroll(_ scrollView: UIScrollView) { topMargin = max(layout.settings.topMargin - scrollView.contentOffset.y, 0) } open override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let velocity = scrollView.panGestureRecognizer.velocity(in: nil) if scrollView.contentOffset.y <= -10 && velocity.y >= 400 { let diff = UIScreen.main.bounds.height - topMargin let duration = min(0.3, diff / velocity.y) sheetNavigationController?.close(duration: TimeInterval(duration)) } } open override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { if sheetNavigationController == nil { super.dismiss(animated: flag, completion: completion) } else { sheetNavigationController?.close(completion: completion) } } } extension SheetContentsViewController { public var sheetNavigationController: SheetNavigationController? { return navigationController as? SheetNavigationController } public var isRootViewController: Bool { return self == navigationController?.viewControllers.first } public func reload() { let before = topMargin setupSheetLayout(layout) collectionView?.reloadData() updateTopMargin() collectionView?.collectionViewLayout.invalidateLayout() let after = topMargin let diff = before - after collectionView?.transform = CGAffineTransform(translationX: 0, y: diff) UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: [.curveLinear], animations: { self.collectionView?.transform = .identity }, completion: nil) } } // MARK: Views private extension SheetContentsViewController { func setupViews() { view.backgroundColor = .clear setupContainerView() setupDimmingView() } func setupContainerView() { let bottomToolBarHeight: CGFloat = isToolBarHidden ? UIEdgeInsets.safeAreaInsets.bottom : SheetManager.shared.options.sheetToolBarHeight + UIEdgeInsets.safeAreaInsets.bottom collectionView?.delaysContentTouches = true collectionView?.collectionViewLayout.invalidateLayout() collectionView?.setCollectionViewLayout(layout, animated: false) collectionView?.delegate = self collectionView?.dataSource = self collectionView?.alwaysBounceVertical = true collectionView?.showsVerticalScrollIndicator = false collectionView?.contentInset.bottom = bottomToolBarHeight collectionView?.backgroundColor = .clear if #available(iOS 11.0, *) { collectionView?.contentInsetAdjustmentBehavior = .never } updateTopMargin() } func updateTopMargin() { let bottomToolBarHeight: CGFloat = isToolBarHidden ? UIEdgeInsets.safeAreaInsets.bottom : SheetManager.shared.options.sheetToolBarHeight + UIEdgeInsets.safeAreaInsets.bottom collectionView?.layoutIfNeeded() let screenHeight = UIScreen.main.bounds.height let contentHeight = collectionView?.contentSize.height ?? 0 let visibleHeight = min(contentHeight - layout.settings.topMargin, visibleContentsHeight) topMargin = isFullScreenContent ? 0 : max(screenHeight - layout.settings.minTopMargin - visibleHeight - bottomToolBarHeight, 0) layout.settings.topMargin = topMargin } func setupDimmingView() { let dimmingButton = UIButton() collectionView?.insertSubview(dimmingButton, at: 0) dimmingButton.translatesAutoresizingMaskIntoConstraints = false dimmingButton.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true dimmingButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true dimmingButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true dimmingButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true dimmingButton.backgroundColor = .clear dimmingButton.addTarget(self, action: #selector(tappedBackground), for: .touchUpInside) } } // MARK: Events private extension SheetContentsViewController { @objc func tappedBackground() { sheetNavigationController?.close() } @objc func tappedDefaultButton() { if isRootViewController { sheetNavigationController?.close() } else { navigationController?.popViewController(animated: true) } } } public protocol SheetContent { var topMargin: CGFloat { get set } var isToolBarHidden: Bool { get } var visibleContentsHeight: CGFloat { get } var sheetToolBar: UIView? { get } } public extension SheetContent { var topMargin: CGFloat { get { return 0 } set {} } var isToolBarHidden: Bool { return SheetManager.shared.options.isToolBarHidden } var sheetToolBar: UIView? { return nil } var visibleContentsHeight: CGFloat { return SheetManager.shared.options.defaultVisibleContentHeight } } extension SheetContent where Self: UIViewController { public func controlToolBar(isShow: Bool, animated: Bool) { let sheetNavi = navigationController as? SheetNavigationController sheetNavi?.controlToolBar(isShow: isShow, animated: animated) } }
34.268722
181
0.691863
5d12696cfa2c18c52d9a28ba6fee108272bd7424
675
// // PartMaster.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation open class PartMaster: JSONEncodable { public var destination: OneOfPartMasterDestination? public var origin: OneOfPartMasterOrigin? public init() {} // MARK: JSONEncodable open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["destination"] = self.destination?.encodeToJSON() nillableDictionary["origin"] = self.origin?.encodeToJSON() let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } }
25
85
0.687407
e99d1f5bbad4fed261b429d2f164a5fcbcc1ba14
4,956
#if os(Linux) import Glibc #elseif os(macOS) import Darwin.C #elseif os(Windows) import MSVCRT #endif import Foundation /// Generic console that uses a mixture of Swift standard /// library and Foundation code to fulfill protocol requirements. public final class Terminal: Console { /// See `Console` public var userInfo: [AnyHashable: Any] /// Dynamically exclude ANSI commands when in Xcode since it doesn't support them. internal var enableCommands: Bool { if let stylizeOverride = self.stylizedOutputOverride { return stylizeOverride } #if Xcode return false #else return isatty(STDOUT_FILENO) > 0 #endif } /// Create a new Terminal. public init() { self.userInfo = [:] } /// See `Console` public func clear(_ type: ConsoleClear) { switch type { case .line: command(.cursorUp) command(.eraseLine) case .screen: command(.eraseScreen) } } /// See `Console` public func input(isSecure: Bool) -> String { didOutputLines(count: 1) if isSecure { var pass = "" #if os(macOS) || os(Linux) func plat_readpassphrase(into buf: UnsafeMutableBufferPointer<Int8>) -> Int { #if os(macOS) let rpp = readpassphrase #elseif os(Linux) let rpp = linux_readpassphrase, RPP_REQUIRE_TTY = 0 as Int32 #endif while rpp("", buf.baseAddress!, buf.count, RPP_REQUIRE_TTY) == nil { guard errno == EINTR else { return 0 } } return strlen(buf.baseAddress!) } func readpassphrase_str() -> String { #if swift(>=5.3.1) if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { // This initializer is only present in Swift 5.3.1 and later, and has an availability guard as well. return .init(unsafeUninitializedCapacity: 1024) { $0.withMemoryRebound(to: Int8.self) { plat_readpassphrase(into: $0) } } } #endif return .init(decoding: [Int8](unsafeUninitializedCapacity: 1024) { $1 = plat_readpassphrase(into: $0) }.map(UInt8.init), as: UTF8.self) } pass = readpassphrase_str() #elseif os(Windows) while pass.count < 32768 { // arbitrary upper bound for sanity let c = _getch() if c == 0x0d || c == 0x0a { break } else if isprint(c) { pass.append(Character(Unicode.Scalar(c))) } } #endif if pass.hasSuffix("\n") { pass = String(pass.dropLast()) } return pass } else { guard let line = readLine(strippingNewline: true) else { fatalError("Received EOF on stdin; unable to read input. Stopping here.") } return line } } /// See `Console` public func output(_ text: ConsoleText, newLine: Bool) { var lines = 0 for fragment in text.fragments { let strings = fragment.string.split(separator: "\n", omittingEmptySubsequences: false) for string in strings { let count = string.count if count > size.width && count > 0 && size.width > 0 { lines += (count / size.width) + 1 } } /// add line for each fragment lines += strings.count - 1 } if newLine { lines += 1 } didOutputLines(count: lines) let terminator = newLine ? "\n" : "" let output: String if enableCommands { output = text.terminalStylize() } else { output = text.description } Swift.print(output, terminator: terminator) fflush(stdout) } /// See `Console` public func report(error: String, newLine: Bool) { let output = newLine ? error + "\n" : error let data = output.data(using: .utf8) ?? Data() FileHandle.standardError.write(data) } /// See `Console` public var size: (width: Int, height: Int) { var w = winsize() _ = ioctl(STDOUT_FILENO, UInt(TIOCGWINSZ), &w); return (Int(w.ws_col), Int(w.ws_row)) } } extension Console { /// If set, overrides a `Terminal`'s own determination as to whether its /// output supports color commands. Useful for easily implementing an option /// of the form `--color=no|yes|auto`. If the active `Console` is not /// specifically a `Terminal`, has no effect. public var stylizedOutputOverride: Bool? { get { return self.userInfo["stylizedOutputOverride"] as? Bool } set { self.userInfo["stylizedOutputOverride"] = newValue } } }
32.821192
151
0.551655
21f9c55412c60737a84b1497bc4da1fddb6db06c
3,286
// // CDMarkdownCode.swift // CDMarkdownKit // // Created by Christopher de Haan on 11/7/16. // // Copyright © 2016-2018 Christopher de Haan <[email protected]> // // 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. // #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #elseif os(macOS) import Cocoa #endif open class CDMarkdownCode: CDMarkdownCommonElement { fileprivate static let regex = "(?s)(\\s+|^|\\()(`{1})(\\s*[^`]*?\\s*)(\\2)(?!`)(\\)?)" open var font: CDFont? open var color: CDColor? open var backgroundColor: CDColor? open var underline: Bool? open var paragraphStyle: NSParagraphStyle? open var regex: String { return CDMarkdownCode.regex } public init(font: CDFont? = CDFont(name: "Menlo-Regular", size: 11), color: CDColor? = CDColor.codeTextRed(), backgroundColor: CDColor? = CDColor.codeBackgroundRed(), underline: Bool? = false, paragraphStyle: NSParagraphStyle? = nil) { self.font = font self.color = color self.backgroundColor = backgroundColor self.underline = underline self.paragraphStyle = paragraphStyle } open func addAttributes(_ attributedString: NSMutableAttributedString, range: NSRange) { let matchString: String = attributedString.attributedSubstring(from: range).string guard let unescapedString = matchString.unescapeUTF16() else { return } attributedString.replaceCharacters(in: range, with: unescapedString) let range = NSRange(location: range.location, length: unescapedString.characterCount()) attributedString.addAttributes(attributes, range: range) let mutableString = attributedString.mutableString // Remove \n if in string, not valid in Code element // Use Syntax element for \n to parse in string mutableString.replaceOccurrences(of: "\n", with: "", options: [], range: range) } }
41.594937
91
0.638466
8ffa6ecf33144bd3428f254ae5ff561d50b243f6
538
// // ignoreTopDeltaYTransformer.swift // AirBar // // Created by Евгений Матвиенко on 7/7/17. // Copyright © 2017 uptechteam. All rights reserved. // import UIKit internal let ignoreTopDeltaYTransformer: ContentOffsetDeltaYTransformer = { params -> CGFloat in var deltaY = params.contentOffsetDeltaY let start = params.scrollable.contentInset.top if params.previousContentOffset.y < -start || params.contentOffset.y < -start { deltaY += min(0, params.previousContentOffset.y + start) } return deltaY }
21.52
96
0.723048
f7c39b03ffdfd5ecf090029583d8658d9691b3d2
465
// // CDTPersonRemoteDataSource.swift // Mobile2you // // Created by Mobile2you Tecnologia on 27/02/19. // Copyright © 2019 Mobile2You. All rights reserved. // import Foundation import UIKit import Moya import RxSwift open class CDTPersonRemoteDataSource { let provider = MoyaProvider<CDTPersonService>() func findPerson(request: IdRequest) -> Single<Response>{ return provider.rx.request(.findPerson(request: request)) } }
20.217391
65
0.711828
9cdfeb173ee6fcbf477124c60f2a2eab30ca4793
3,236
// // WhatsNewViewControllerTests.swift // WhatsNewKit-iOS Tests // // Created by Sven Tiigi on 26.05.18. // Copyright © 2018 WhatsNewKit. All rights reserved. // import XCTest @testable import WhatsNewKit class WhatsNewViewControllerTests: BaseTests { func testAvailableVersionInVersionStore() { let versionStore = InMemoryWhatsNewVersionStore() versionStore.set(version: self.randomWhatsNew.version) XCTAssertNil(WhatsNewViewController(whatsNew: self.randomWhatsNew, versionStore: versionStore)) } func testUnavailableVersionInVersionStore() { let versionStore = InMemoryWhatsNewVersionStore() let whatsNewViewController = WhatsNewViewController(whatsNew: self.randomWhatsNew, versionStore: versionStore) XCTAssertNotNil(whatsNewViewController) whatsNewViewController?.handleOnPress(buttonType: .completion) XCTAssert(versionStore.has(version: self.randomWhatsNew.version)) } func testWhatsNewPassedToControllerEquatable() { let whatsNewViewController = WhatsNewViewController(whatsNew: self.randomWhatsNew) XCTAssertEqual(self.randomWhatsNew, whatsNewViewController.whatsNew) } func testCoderInitializer() { XCTAssertNil(WhatsNewViewController(coder: .init())) } func testPresent() { let whatsNewViewController = WhatsNewViewController(whatsNew: self.randomWhatsNew) class FakeViewController: UIViewController { var viewControllerToPresent: UIViewController? var shouldAnimate: Bool? override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) { self.viewControllerToPresent = viewControllerToPresent self.shouldAnimate = flag completion?() } } let fakeViewViewController = FakeViewController() let animated = true self.performTest(execution: { expectation in whatsNewViewController.present(on: fakeViewViewController, animated: animated, completion: { XCTAssert(fakeViewViewController.viewControllerToPresent === whatsNewViewController) XCTAssertEqual(fakeViewViewController.shouldAnimate, true) expectation.fulfill() }) }) } func testPush() { let whatsNewViewController = WhatsNewViewController(whatsNew: self.randomWhatsNew) class FakeNavigationController: UINavigationController { var pushedViewController: UIViewController? var shouldAnimate: Bool? override func pushViewController(_ viewController: UIViewController, animated: Bool) { self.pushedViewController = viewController self.shouldAnimate = animated } } let fakeNavigationController = FakeNavigationController() let animated = true whatsNewViewController.push(on: fakeNavigationController, animated: animated) XCTAssert(fakeNavigationController.pushedViewController === whatsNewViewController) XCTAssertEqual(fakeNavigationController.shouldAnimate, animated) } }
42.025974
134
0.69932
67986a2ed3c81c24eafb55383cc60f765c6e2904
1,009
// // DataSourcePraticeTests.swift // DataSourcePraticeTests // // Created by Vincent Lin on 2018/7/1. // Copyright © 2018 Vincent Lin. All rights reserved. // import XCTest @testable import DataSourcePratice class DataSourcePraticeTests: 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.27027
111
0.646184
9c593c96e831d33a6e17c335e3f5d6a1737d62d0
2,016
// // InfoTableViewCell.swift // LLInfo // // Created by CmST0us on 2017/11/17. // Copyright © 2017年 eki. All rights reserved. // import UIKit class InfoListTableViewCell: UITableViewCell { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var sourceNameLabel: UILabel! @IBOutlet weak var sourceIcon: UIImageView! @IBOutlet weak var tagsLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var briefLabel: UILabel! @IBOutlet weak var briefImageImageView: UIImageView! struct CellId { static let infoListCellId = "info_list_cell_id" } private func sourceStringWithIcon(source: String?) -> UIImage? { if source == nil { return nil } let iconName = source! + "_icon" if let iconImage = UIImage(named: iconName) { return iconImage } return nil } func setupCell(withInfoDataModel model: InfoDataModel) { self.timeLabel.text = model.formatTime self.sourceNameLabel.text = model.sourceName self.sourceIcon.image = sourceStringWithIcon(source: model.source) if let t = model.tags { self.tagsLabel.text = t.joined(separator: " ") } self.titleLabel.text = model.title?.trimmingCharacters(in: .whitespacesAndNewlines) self.briefLabel.text = model.brief } } // MARK: - View Life cycle method extension InfoListTableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func draw(_ rect: CGRect) { } override func prepareForReuse() { self.backgroundColor = UIColor.white self.briefImageImageView.image = UIImage(named: "image_placehold") } }
27.616438
91
0.635417
1ae975c5b07230ab33c02ef7d1c2ab6ad76e6e71
564
class Dog { func bark() { print("woof") } } class NoisyDog : Dog { override func bark() { super.bark() super.bark() } func beQuiet() { self.bark() } } func tellToHush(_ d: Dog) { // d.beQuiet(); // (d as! NoisyDog).beQuite() // cast // // Type Check if d is NoisyDog { var d = d as! NoisyDog d.beQuiet() } print() // Type Check if let d = d as? NoisyDog { d.beQuiet() } } let nd = NoisyDog() tellToHush(nd) let d = Dog() tellToHush(d)
13.428571
41
0.478723
79a3c4ba016df9e141376392b48b5cded8ea84ae
747
import Foundation import SwiftyJSON struct TwitterHashtag { let text: String let indices: [Int] init(_ json: JSON) { self.text = json["text"].string ?? "" self.indices = json["indices"].array?.map({ $0.int ?? 0 }) ?? [Int]() } init(json: [String: AnyObject]) { self.text = json["text"] as? String ?? "" self.indices = json["indices"] as? [Int] ?? [] } init(_ dictionary: [String: AnyObject]) { self.text = dictionary["text"] as? String ?? "" self.indices = dictionary["indices"] as? [Int] ?? [] } var dictionaryValue: [String: AnyObject] { return [ "text": text as AnyObject, "indices": indices as AnyObject ] } }
24.9
77
0.536814
140ba6107d3e6a17026930b03efcace1bcd41132
730
// // CoinExchange.swift // Pods // // Created by Dominique Stranz on 14/11/2018. // import Foundation #if canImport(CoinpaprikaNetworking) import CoinpaprikaNetworking #endif /// Coin Exchange public struct CoinExchange: Equatable, CodableModel { /// Coin id, eg. binance public let id: String /// Coin name, eg. Binance public let name: String /// Adjusted volume share in last 24h public let adjustedVolume24hShare: Decimal /// List of supported fiat currencies public let fiats: [Exchange.Fiat] enum CodingKeys: String, CodingKey { case id case name case adjustedVolume24hShare = "adjusted_volume_24h_share" case fiats } }
20.277778
65
0.663014
e5a7704dac8426885a6f8010bc4f6b659d40eb7e
499
// // PublicMessage.swift // FacebookLogin // // Created by Arash Z. Jahangiri on 10/10/2016. // Copyright © 2017 Arash Z. Jahangiri. All rights reserved. // import Foundation import ObjectMapper struct PublicMessage: Mappable { var id: Int? var date: String? var message: String? var user: User? init?(map: Map) { } mutating func mapping(map: Map) { id <- map["id"] date <- map["date"] message <- map["message"] user <- map["user"] } }
16.633333
61
0.601202
33a059ce847b6501397c37a9780b370b796cc869
1,194
import Foundation import HTMLEntities import LoggerAPI struct LicenseHTMLHolder { let html: String static func load(licenses: [LicenseInfo], options: Options) -> LicenseHTMLHolder { var html = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Acknowledgements</title> </head> <body> <h1>Acknowledgements</h1> <p> This project makes use of the following third party libraries: </p> """ licenses.forEach { license in html += """ <h2>\(license.name(withVersion: options.config.addVersionNumbers).htmlEscape())</h2> <pre>\(license.body.htmlEscape())</pre> """ } html += """ </body> </html> """ return LicenseHTMLHolder(html: html) } func write(to htmlPath: URL) { do { try html.data(using: .utf8)!.write(to: htmlPath) } catch let e { Log.error("Failed to write to (htmlPath: \(htmlPath)).\nerror: \(e)") } } }
27.136364
104
0.487437
9041ae75f99c70bc640403977da2a54b03d30bba
3,605
// // ContentModeViewController.swift // Cacao // // Created by Alsey Coleman Miller on 5/29/16. // Copyright © 2016 PureSwift. All rights reserved. // #if os(Linux) import Glibc #elseif os(macOS) import Darwin.C #endif import Foundation #if os(iOS) || os(tvOS) import UIKit import CoreGraphics #else import Cacao import Silica #endif final class ContentModeViewController: UIViewController { // MARK: - Views private(set) weak var label: UILabel! private(set) weak var logoView: SwiftLogoView! private(set) weak var button: UIButton! // MARK: - Properties let modes: [UIViewContentMode] = [.center, .redraw, .scaleToFill, .scaleAspectFit, .scaleAspectFill, .top, .bottom, .left, .right, .topLeft, .topRight, .bottomLeft, .bottomRight] // MARK: - Loading override func loadView() { let logoView = SwiftLogoView(frame: .zero) // since we dont use autoresizing, initial size doesnt matter self.view = logoView logoView.contentMode = modes[0] logoView.pointSize = 150 let label = UILabel() // layoutSubviews will set size label.text = "\(modes[0])" label.textColor = .white let button = UIButton() #if os(iOS) || os(tvOS) button.addTarget(self, action: #selector(_changeMode), for: .touchUpInside) #else let selector = Selector(name: "changeMode", action: { (_, sender, _) in self.changeMode(sender as! UIButton) }) button.addTarget(self, action: selector, for: .touchUpInside) #endif label.textAlignment = .center view.addSubview(button) view.addSubview(label) view.backgroundColor = UIColor.blue self.button = button self.label = label self.logoView = logoView } override func viewWillLayoutSubviews() { let frame = view.frame // from Paint Code label.frame = CGRect(x: frame.minX + floor(frame.width * 0.00000 + 0.5), y: frame.minY + floor(frame.height * 0.82812 + 0.5), width: floor(frame.width * 1.00000 + 0.5) - floor(frame.width * 0.00000 + 0.5), height: floor(frame.height * 1.00000 + 0.5) - floor(frame.height * 0.82812 + 0.5)) button.frame = CGRect(x: frame.minX + floor(frame.width * 0.00000 + 0.5), y: frame.minY + floor(frame.height * 0.00000 + 0.5), width: floor(frame.width * 1.00000 + 0.5) - floor(frame.width * 0.00000 + 0.5), height: floor(frame.height * 0.82812 + 0.5) - floor(frame.height * 0.00000 + 0.5)) logoView.frame = button.frame } // MARK: - Actions #if os(iOS) || os(tvOS) @IBAction func _changeMode(_ sender: UIButton) { changeMode(sender) } #endif func changeMode(_ sender: UIButton) { let currentMode = logoView.contentMode let currentIndex = modes.index(of: currentMode)! var nextIndex = currentIndex + 1 if currentIndex == modes.count - 1 { nextIndex = 0 } let newMode = modes[nextIndex] logoView.contentMode = newMode label.text = "\(newMode)" print("Changing to \(newMode)") } }
28.385827
182
0.545354
f51516ea09aa3998bdf85e362c2631cc6c0909a2
6,175
// // LoginConfigVC.swift // Valine // // Created by xu on 2020/7/2. // Copyright © 2020 xaoxuu.com. All rights reserved. // import UIKit class LoginConfigVC: BaseVC { let titleLabel = UILabel() var addBtn = UIButton() var ts = [[String]]() var cs = [[Callback]]() var vm = Table() var secs = [Section]() lazy var tableView: UITableView = { let tv = UITableView(frame: .zero, style: .insetGrouped) return tv }() override func viewDidLoad() { super.viewDidLoad() titleLabel.font = .bold(28) titleLabel.text = "选择一个应用" view.addSubview(titleLabel) titleLabel.snp.makeConstraints { (mk) in mk.top.equalToSuperview().offset(ipr.screen.safeAreaInsets.top + margin) mk.left.equalToSuperview().offset(margin) mk.height.equalTo(64) } addBtn = BaseButton(image: UIImage(systemName: "plus.circle.fill"), handler: { [weak self] in let vc = LoginConfigEditVC() self?.present(vc, animated: true, completion: nil) }) addBtn.imageView?.snp.makeConstraints({ (mk) in mk.width.height.equalTo(36) }) view.addSubview(addBtn) addBtn.snp.makeConstraints { (mk) in mk.centerY.equalTo(titleLabel).offset(-4) mk.width.equalTo(addBtn.snp.height) mk.right.equalToSuperview().offset(-margin) } reloadData() NotificationCenter.default.rx.notification(.init("onLogin")).subscribe(onNext: { [weak self] (notification) in self?.presentingViewController?.dismiss(animated: true, completion: nil) }).disposed(by: disposeBag) NotificationCenter.default.rx.notification(.init("reloadConfig")).subscribe(onNext: { [weak self] (notification) in self?.reloadData() }).disposed(by: disposeBag) } func reloadData() { let all = ValineAppModel.getAll() if all.count > 0 { view.addSubview(tableView) tableView.backgroundColor = .clear tableView.dataSource = self tableView.delegate = self tableView.snp.makeConstraints { (mk) in mk.left.right.bottom.equalToSuperview() mk.top.equalTo(titleLabel.snp.bottom) } vm.sections.removeAll() for a in all { vm.addSection(title: "") { (sec) in sec.addRow(title: a.alias, subtitle: "id: '\(a.id)'\nkey: '\(a.key)'") { [weak self] in // 登录 if let `self` = self, LibManager.configLeanCloud(id: a.id, key: a.key) { ValineAppModel.current = a let vc = LoginManager.login(from: self) vc.onDismiss { [weak self] in self?.reloadData() } } } } } tableView.reloadData() } else { tableView.removeFromSuperview() } } } extension LoginConfigVC: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return vm.sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return vm.sections[section].rows.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell if let c = tableView.dequeueReusableCell(withIdentifier: "cell") { cell = c } else { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell") cell.backgroundColor = .secondarySystemBackground cell.textLabel?.numberOfLines = 0 cell.detailTextLabel?.textColor = .gray cell.detailTextLabel?.numberOfLines = 0 cell.accessoryType = .disclosureIndicator cell.textLabel?.font = .bold(20) cell.detailTextLabel?.font = .regular(12) cell.textLabel?.snp.makeConstraints({ (mk) in mk.top.equalToSuperview().offset(margin) mk.left.equalToSuperview().offset(margin) mk.right.equalToSuperview().offset(-margin) }) cell.detailTextLabel?.snp.makeConstraints({ (mk) in mk.bottom.equalToSuperview().offset(-margin) mk.left.right.equalTo(cell.textLabel!) mk.top.equalTo(cell.textLabel!.snp.bottom).offset(margin/2) }) } cell.textLabel?.text = vm.sections[indexPath.section].rows[indexPath.row].title cell.detailTextLabel?.text = vm.sections[indexPath.section].rows[indexPath.row].subtitle return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return vm.sections[section].header } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return vm.sections[section].footer } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) vm.sections[indexPath.section].rows[indexPath.row].callback() } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { if indexPath.section < vm.sections.count { vm.sections.remove(at: indexPath.section) tableView.deleteSections([indexPath.section], with: .fade) ValineAppModel.delete(index: indexPath.section) } } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { view.endEditing(true) } }
36.976048
128
0.581862
e92a46ac8ea874a698a00f65453b93c04022deeb
385
var IntArray = [Int](); /* another way of initializing an array:: var Array:[Int] = [1,3,4,5] var Array = [Int](count: 3, repeatedValue: 0) -- repeatedValue initialize the array */ IntArray.append(10) IntArray += [30] var firstElement:Int = IntArray[0] print("Value of the first element is: \(firstElement)") print("Value of the second element is: \(IntArray[1])")
25.666667
85
0.662338
efc8c5c9af1882cbb1dea1e5b7519d9b2abb1314
2,146
// // YOWeightOtherLine.swift // YOWeight // // Created by SYQM on 2022/2/17. // import UIKit class YOWeightOtherLine: UIView { /// 中间线 private let centerLineLayer: CAShapeLayer /// 平均线 private let averageLineLayer: CAShapeLayer var lineParModel = YOWightOtherLineParameter() override init(frame: CGRect) { centerLineLayer = CAShapeLayer() averageLineLayer = CAShapeLayer() super.init(frame: frame) self.layer.addSublayer(centerLineLayer) self.layer.addSublayer(averageLineLayer) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func refreshCenterLine(){ let path = UIBezierPath() path.move(to: CGPoint(x: self.frame.width / 2.0 - lineParModel.centerLineWidth / 2, y: 0)) path.addLine(to: CGPoint(x: self.frame.width / 2.0 - lineParModel.centerLineWidth / 2,y: self.frame.height)) centerLineLayer.lineWidth = lineParModel.centerLineWidth centerLineLayer.strokeColor = lineParModel.centerLineColor.cgColor centerLineLayer.fillColor = lineParModel.centerLineColor.cgColor centerLineLayer.path = path.cgPath layer.addSublayer(centerLineLayer) } func refreshAvageLine(_ value: Double){ averageLineLayer.removeFromSuperlayer() if value <= 0.0 { return } let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: value)) path.addLine(to: CGPoint(x: self.frame.width,y: value)) averageLineLayer.lineWidth = lineParModel.averageLineWidth averageLineLayer.strokeColor = lineParModel.averageLineColor.cgColor averageLineLayer.fillColor = lineParModel.averageLineColor.cgColor if lineParModel.isDottedLine { averageLineLayer.lineDashPattern = [NSNumber(value: lineParModel.dottedWidth),NSNumber(value: lineParModel.blankWidth)] } averageLineLayer.path = path.cgPath layer.addSublayer(averageLineLayer) } }
29.805556
131
0.648183
62617f43db574ef6395eedc2ef6959c8be73a55a
581
// Copyright (c) 2020 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import SWCompression extension CompressionMethod: CustomStringConvertible { public var description: String { switch self { case .bzip2: return "BZip2" case .copy: return "none" case .deflate: return "deflate" case .lzma: return "LZMA" case .lzma2: return "LZMA2" case .other: return "other/unknown" } } }
20.034483
54
0.566265
de874f1eedcf522bb288b8a52134ae4191b110e3
15,647
// // SoundRecordViewController.swift // iNaturalist // // Created by Alex Shepard on 2/3/21. // Copyright © 2021 iNaturalist. All rights reserved. // import UIKit import AVFoundation import FontAwesomeKit @objc protocol SoundRecorderDelegate { func recordedSound(recorder: SoundRecordViewController, uuidString: String) func cancelled(recorder: SoundRecordViewController) } class SoundRecordViewController: UIViewController { var timerLabel: UILabel! var recordButton: UIButton! var doneButton: UIButton! var meter: RecorderLevelView! var recordingSession: AVAudioSession! var audioRecorder: AVAudioRecorder? var timer: Timer? var soundUUIDString: String! var micImage: UIImage? var pauseImage: UIImage? @objc weak var recorderDelegate: SoundRecorderDelegate? override func viewDidLoad() { super.viewDidLoad() // this will be the UUID for the saved observation sound // which is a key for the MediaStore and also for uploading // to the API self.soundUUIDString = UUID().uuidString.lowercased() self.view.backgroundColor = .white timerLabel = UILabel() timerLabel.accessibilityTraits = [.updatesFrequently] timerLabel.text = "" timerLabel.font = UIFont.boldSystemFont(ofSize: 19) timerLabel.textColor = UIColor.inatTint() if let mic = FAKIonIcons.micAIcon(withSize: 50), let pause = FAKIonIcons.pauseIcon(withSize: 50), let circle = FAKIonIcons.recordIcon(withSize: 75) { mic.addAttribute(NSAttributedString.Key.foregroundColor.rawValue, value: UIColor.white) pause.addAttribute(NSAttributedString.Key.foregroundColor.rawValue, value: UIColor.white) circle.addAttribute(NSAttributedString.Key.foregroundColor.rawValue, value: UIColor.inatTint()) self.micImage = UIImage(stackedIcons: [circle, mic], imageSize: CGSize(width: 75, height: 75))? .withRenderingMode(.alwaysOriginal) self.pauseImage = UIImage(stackedIcons: [circle, pause], imageSize: CGSize(width: 75, height: 75))? .withRenderingMode(.alwaysOriginal) } meter = RecorderLevelView() meter.accessibilityTraits = [.updatesFrequently] recordButton = UIButton(type: .system) recordButton.setImage(self.micImage, for: .normal) recordButton.accessibilityLabel = NSLocalizedString("Record", comment: "Accessibility Label for Record/Pause Button") recordButton.addTarget(self, action: #selector(recordPressed), for: .touchUpInside) recordButton.isEnabled = false recordButton.tintColor = UIColor.inatTint() doneButton = UIButton(type: .system) doneButton.setTitle(NSLocalizedString("Save Recording", comment: "Done button for recording observation sounds"), for: .normal) doneButton.addTarget(self, action: #selector(donePressed), for: .touchUpInside) doneButton.tintColor = UIColor.inatTint() doneButton.isEnabled = false let bottomStack = UIStackView(arrangedSubviews: [recordButton, doneButton]) bottomStack.translatesAutoresizingMaskIntoConstraints = false bottomStack.distribution = .fillEqually bottomStack.axis = .vertical bottomStack.spacing = 20 bottomStack.alignment = .center let stack = UIStackView(arrangedSubviews: [timerLabel, meter, bottomStack]) stack.translatesAutoresizingMaskIntoConstraints = false stack.distribution = .fillEqually stack.axis = .vertical stack.spacing = 0 stack.alignment = .center self.view.addSubview(stack) NSLayoutConstraint.activate([ stack.topAnchor.constraint(equalTo: self.view.topAnchor), stack.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), stack.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), stack.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), meter.leadingAnchor.constraint(equalTo: stack.leadingAnchor), meter.trailingAnchor.constraint(equalTo: stack.trailingAnchor), ]) let cancel = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelPressed)) self.navigationItem.leftBarButtonItem = cancel self.title = NSLocalizedString("Recording Sound", comment: "Title for sound recording screen") recordingSession = AVAudioSession.sharedInstance() do { try recordingSession.setCategory(.playAndRecord) try recordingSession.setMode(.default) try recordingSession.setActive(true) recordingSession.requestRecordPermission() { [unowned self] allowed in DispatchQueue.main.async { if allowed { self.prepareRecording() } else { let title = NSLocalizedString("No Microphone Permissions", comment: "title of alert when user tries to record a sound observation without granting mic permissions") let message = NSLocalizedString("If you wish to record a sound observation, you will need to give the iNaturalist app permission to use the microphone.", comment: "message of alert when mic permission is missing") let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancel = NSLocalizedString("Cancel", comment: "") alert.addAction(UIAlertAction(title: cancel, style: .cancel, handler: { _ in self.recorderDelegate?.cancelled(recorder: self) })) let openSettings = NSLocalizedString("Open Settings", comment: "button to open settings when user needs to adjust mic permissions") alert.addAction(UIAlertAction(title: openSettings, style: .default, handler: { _ in if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.openURL(url) } })) self.present(alert, animated: true, completion: nil) } } } } catch (let error) { let title = NSLocalizedString("Failed to Setup Sound Recording", comment: "title of alert when sound recording setup fails") let message = error.localizedDescription let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancel = NSLocalizedString("OK", comment: "") alert.addAction(UIAlertAction(title: cancel, style: .default, handler: { _ in self.recorderDelegate?.cancelled(recorder: self) })) } // notifications about interruptions NotificationCenter.default.addObserver(self, selector: #selector(audioInterruption), name: AVAudioSession.interruptionNotification, object:nil) } @objc func audioInterruption(note: Notification) { guard let userInfo = note.userInfo, let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt, let type = AVAudioSession.InterruptionType(rawValue: typeValue) else { return } switch type { case .began: if #available(iOS 10.3, *) { if let suspended = userInfo[AVAudioSessionInterruptionWasSuspendedKey] as? NSNumber { if suspended.boolValue { // app was previously suspended, not actively interruped // ignore this notification, don't update the UI return } } } // interruption began self.timer?.invalidate() timerLabel.text = NSLocalizedString("Paused", comment: "") case .ended: // interruption ended timerLabel.text = NSLocalizedString("Resuming", comment: "") timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timerCallback), userInfo: nil, repeats: true) default: () } } @objc func recordPressed() { if let recorder = self.audioRecorder, recorder.isRecording { recordButton.setImage(self.micImage, for: .normal) recordButton.accessibilityLabel = NSLocalizedString("Record", comment: "Accessibility Label for Record Button (when recording audio)") pauseRecording() } else { recordButton.setImage(self.pauseImage, for: .normal) recordButton.accessibilityLabel = NSLocalizedString("Pause", comment: "Accessibility Label for Pause Button (when recording audio)") startRecording() } } @objc func cancelPressed() { self.recorderDelegate?.cancelled(recorder: self) } @objc func donePressed() { finishRecording(success: true, error: nil) self.recorderDelegate?.recordedSound(recorder: self, uuidString: self.soundUUIDString) } func startRecording() { if let recorder = self.audioRecorder { recorder.record() } } func prepareRecording() { let mm = MediaStore() let soundUrl = mm.mediaUrlForKey(self.soundUUIDString) let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 44100, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] do { let recorder = try AVAudioRecorder(url: soundUrl, settings: settings) recorder.delegate = self recorder.isMeteringEnabled = true recorder.prepareToRecord() timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timerCallback), userInfo: nil, repeats: true) self.audioRecorder = recorder self.recordButton.isEnabled = true } catch (let error) { finishRecording(success: false, error: error) } } func pauseRecording() { self.audioRecorder?.pause() } func finishRecording(success: Bool, error: Error?) { if !success { let title = NSLocalizedString("Failed to Record", comment: "title of alert when sound recording fails") let message = error?.localizedDescription ?? "" let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancel = NSLocalizedString("OK", comment: "") alert.addAction(UIAlertAction(title: cancel, style: .default, handler: { _ in self.recorderDelegate?.cancelled(recorder: self) })) return } self.timer?.invalidate() self.audioRecorder?.stop() self.audioRecorder = nil } @objc func timerCallback() { if let recorder = self.audioRecorder { recorder.updateMeters() recorder.peakPower(forChannel: 0) let lowPassResults = pow(10, (0.05 * recorder.peakPower(forChannel: 0))) let timerBaseText = NSLocalizedString("%.1f sec", comment: "elapsed time on recording screen, in seconds") let timerText = String(format: timerBaseText, recorder.currentTime) DispatchQueue.main.async { self.meter.level = lowPassResults self.timerLabel.text = timerText if recorder.currentTime > 1.0 { self.doneButton.isEnabled = true } } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.audioRecorder?.stop() self.timer?.invalidate() } } extension SoundRecordViewController: AVAudioRecorderDelegate { func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { if flag { self.recorderDelegate?.recordedSound(recorder: self, uuidString: self.soundUUIDString) } else { finishRecording(success: false, error: nil) } } func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) { finishRecording(success: false, error: error) } } class RecorderLevelView: UIView { public var level: Float = 0.0 { didSet { // clamped to { 0.0, 1.0 } if level < 0.0 { level = 0.0 } if level > 1.0 { level = 1.0 } let baseString = NSLocalizedString("Recording Level (from 0 to 1)", comment: "Accessibility label for sound recorder") self.accessibilityLabel = String(format: baseString, level) self.accessibilityValue = "\(level)" let scaledLevel = level * 30 // anything less than 0.01 is basically nothing if (scaledLevel < 0.01) { return } for i in 0..<30 { DispatchQueue.main.async { if i <= Int(scaledLevel) { self.levelViews[i].backgroundColor = .green } else { self.levelViews[i].backgroundColor = .black } } } } } var levelViews = [UIView]() override init(frame: CGRect) { super.init(frame: frame) for _ in 0..<30 { let levelView = UIView(frame: .zero) levelView.backgroundColor = .black levelViews.append(levelView) } let stack = UIStackView(arrangedSubviews: levelViews) stack.translatesAutoresizingMaskIntoConstraints = false stack.distribution = .fillEqually stack.axis = .horizontal stack.spacing = 2 stack.alignment = .center self.addSubview(stack) for levelView in levelViews { NSLayoutConstraint.activate([ levelView.widthAnchor.constraint(equalToConstant: 20), levelView.heightAnchor.constraint(equalToConstant: 40), levelView.centerYAnchor.constraint(equalTo: stack.centerYAnchor), ]) } NSLayoutConstraint.activate([ stack.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16), stack.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16), stack.topAnchor.constraint(equalTo: self.topAnchor), stack.bottomAnchor.constraint(equalTo: self.bottomAnchor), ]) } required init?(coder: NSCoder) { super.init(coder: coder) fatalError("Interface Builder is not supported!") } }
39.612658
237
0.595322
03abfad8e7794fe87c2954a78023a0d6989fe2a5
782
// // TYPEPersistenceStrategy.swift // import AmberBase import Foundation public class FormatStyleCapitalizationContext_PersistenceStrategy: PersistenceStrategy { public var types: Types { return Types.type("FormatStyleCapitalizationContext") } public func save(_ object: Any) throws -> Data { guard let typedObject = object as? FormatStyleCapitalizationContext else { throw AmberError.wrongTypes(self.types, AmberBase.types(of: object)) } let encoder = JSONEncoder() return try encoder.encode(typedObject) } public func load(_ data: Data) throws -> Any { let decoder = JSONDecoder() return try decoder.decode(FormatStyleCapitalizationContext.self, from: data) } }
25.225806
86
0.681586
2656701b18d4159eddedfe32fb48b81bb83b9d02
716
// 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 // CheckAvailabilityParametersProtocol is parameters supplied to the Check Name Availability for Namespace and // NotificationHubs. public protocol CheckAvailabilityParametersProtocol : Codable { var id: String? { get set } var name: String { get set } var type: String? { get set } var location: String { get set } var tags: [String:String]? { get set } var sku: SkuProtocol? { get set } var isAvailiable: Bool? { get set } }
42.117647
111
0.703911
e48b413e40d8afb395a094629e9bff0fe99182b2
1,134
// swift-tools-version:5.6 import PackageDescription let package = Package( name: "SumoLogicRum", platforms: [.iOS(.v11)], products: [ .library(name: "SumoLogicRum", type: .static, targets: ["SumoLogicRum"]), ], dependencies: [ .package(url: "https://github.com/kkruk-sumo/opentelemetry-swift", from: "100.0.0"), .package(url: "https://github.com/microsoft/plcrashreporter", from: "1.10.1"), ], targets: [ .target( name: "SumoLogicRum", dependencies: [ .product(name: "OpenTelemetryApi", package: "opentelemetry-swift"), .product(name: "OpenTelemetrySdk", package: "opentelemetry-swift"), .product(name: "ResourceExtension", package: "opentelemetry-swift"), .product(name: "URLSessionInstrumentation", package: "opentelemetry-swift"), .product(name: "NetworkStatus", package: "opentelemetry-swift"), .product(name: "CrashReporter", package: "plcrashreporter")] ), ] )
40.5
104
0.558201
91873ce9f0f31153a78951d6acd716d7b6793158
224
// // Errors.swift // GameEstate // // Created by Sky Morey on 5/28/18. // Copyright © 2018 Sky Morey. All rights reserved. // public enum Errors: Error { case argumentNullException case notSupportedException }
17.230769
52
0.6875
9b055a9414fcfca608c69e5e9b2b05cc3b661150
150,359
//===----------------------------------------------------------------------===// // // 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/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension IoT { /// Returns a Device Defender's ML Detect Security Profile training model's status. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getBehaviorModelTrainingSummariesPaginator<Result>( _ input: GetBehaviorModelTrainingSummariesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetBehaviorModelTrainingSummariesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getBehaviorModelTrainingSummaries, inputKey: \GetBehaviorModelTrainingSummariesRequest.nextToken, outputKey: \GetBehaviorModelTrainingSummariesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getBehaviorModelTrainingSummariesPaginator( _ input: GetBehaviorModelTrainingSummariesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetBehaviorModelTrainingSummariesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getBehaviorModelTrainingSummaries, inputKey: \GetBehaviorModelTrainingSummariesRequest.nextToken, outputKey: \GetBehaviorModelTrainingSummariesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the active violations for a given Device Defender security profile. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listActiveViolationsPaginator<Result>( _ input: ListActiveViolationsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListActiveViolationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listActiveViolations, inputKey: \ListActiveViolationsRequest.nextToken, outputKey: \ListActiveViolationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listActiveViolationsPaginator( _ input: ListActiveViolationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListActiveViolationsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listActiveViolations, inputKey: \ListActiveViolationsRequest.nextToken, outputKey: \ListActiveViolationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the policies attached to the specified thing group. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAttachedPoliciesPaginator<Result>( _ input: ListAttachedPoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAttachedPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAttachedPolicies, inputKey: \ListAttachedPoliciesRequest.marker, outputKey: \ListAttachedPoliciesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAttachedPoliciesPaginator( _ input: ListAttachedPoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAttachedPoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAttachedPolicies, inputKey: \ListAttachedPoliciesRequest.marker, outputKey: \ListAttachedPoliciesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Lists the findings (results) of a Device Defender audit or of the audits performed during a specified time period. (Findings are retained for 90 days.) /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAuditFindingsPaginator<Result>( _ input: ListAuditFindingsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAuditFindingsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAuditFindings, inputKey: \ListAuditFindingsRequest.nextToken, outputKey: \ListAuditFindingsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAuditFindingsPaginator( _ input: ListAuditFindingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAuditFindingsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAuditFindings, inputKey: \ListAuditFindingsRequest.nextToken, outputKey: \ListAuditFindingsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Gets the status of audit mitigation action tasks that were executed. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAuditMitigationActionsExecutionsPaginator<Result>( _ input: ListAuditMitigationActionsExecutionsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAuditMitigationActionsExecutionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAuditMitigationActionsExecutions, inputKey: \ListAuditMitigationActionsExecutionsRequest.nextToken, outputKey: \ListAuditMitigationActionsExecutionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAuditMitigationActionsExecutionsPaginator( _ input: ListAuditMitigationActionsExecutionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAuditMitigationActionsExecutionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAuditMitigationActionsExecutions, inputKey: \ListAuditMitigationActionsExecutionsRequest.nextToken, outputKey: \ListAuditMitigationActionsExecutionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Gets a list of audit mitigation action tasks that match the specified filters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAuditMitigationActionsTasksPaginator<Result>( _ input: ListAuditMitigationActionsTasksRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAuditMitigationActionsTasksResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAuditMitigationActionsTasks, inputKey: \ListAuditMitigationActionsTasksRequest.nextToken, outputKey: \ListAuditMitigationActionsTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAuditMitigationActionsTasksPaginator( _ input: ListAuditMitigationActionsTasksRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAuditMitigationActionsTasksResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAuditMitigationActionsTasks, inputKey: \ListAuditMitigationActionsTasksRequest.nextToken, outputKey: \ListAuditMitigationActionsTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists your Device Defender audit listings. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAuditSuppressionsPaginator<Result>( _ input: ListAuditSuppressionsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAuditSuppressionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAuditSuppressions, inputKey: \ListAuditSuppressionsRequest.nextToken, outputKey: \ListAuditSuppressionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAuditSuppressionsPaginator( _ input: ListAuditSuppressionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAuditSuppressionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAuditSuppressions, inputKey: \ListAuditSuppressionsRequest.nextToken, outputKey: \ListAuditSuppressionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the Device Defender audits that have been performed during a given time period. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAuditTasksPaginator<Result>( _ input: ListAuditTasksRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAuditTasksResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAuditTasks, inputKey: \ListAuditTasksRequest.nextToken, outputKey: \ListAuditTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAuditTasksPaginator( _ input: ListAuditTasksRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAuditTasksResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAuditTasks, inputKey: \ListAuditTasksRequest.nextToken, outputKey: \ListAuditTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the authorizers registered in your account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAuthorizersPaginator<Result>( _ input: ListAuthorizersRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAuthorizersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAuthorizers, inputKey: \ListAuthorizersRequest.marker, outputKey: \ListAuthorizersResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAuthorizersPaginator( _ input: ListAuthorizersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAuthorizersResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAuthorizers, inputKey: \ListAuthorizersRequest.marker, outputKey: \ListAuthorizersResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Lists the billing groups you have created. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listBillingGroupsPaginator<Result>( _ input: ListBillingGroupsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListBillingGroupsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listBillingGroups, inputKey: \ListBillingGroupsRequest.nextToken, outputKey: \ListBillingGroupsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listBillingGroupsPaginator( _ input: ListBillingGroupsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListBillingGroupsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listBillingGroups, inputKey: \ListBillingGroupsRequest.nextToken, outputKey: \ListBillingGroupsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the CA certificates registered for your AWS account. The results are paginated with a default page size of 25. You can use the returned marker to retrieve additional results. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listCACertificatesPaginator<Result>( _ input: ListCACertificatesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListCACertificatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listCACertificates, inputKey: \ListCACertificatesRequest.marker, outputKey: \ListCACertificatesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listCACertificatesPaginator( _ input: ListCACertificatesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListCACertificatesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listCACertificates, inputKey: \ListCACertificatesRequest.marker, outputKey: \ListCACertificatesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Lists the certificates registered in your AWS account. The results are paginated with a default page size of 25. You can use the returned marker to retrieve additional results. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listCertificatesPaginator<Result>( _ input: ListCertificatesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListCertificatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listCertificates, inputKey: \ListCertificatesRequest.marker, outputKey: \ListCertificatesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listCertificatesPaginator( _ input: ListCertificatesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListCertificatesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listCertificates, inputKey: \ListCertificatesRequest.marker, outputKey: \ListCertificatesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// List the device certificates signed by the specified CA certificate. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listCertificatesByCAPaginator<Result>( _ input: ListCertificatesByCARequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListCertificatesByCAResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listCertificatesByCA, inputKey: \ListCertificatesByCARequest.marker, outputKey: \ListCertificatesByCAResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listCertificatesByCAPaginator( _ input: ListCertificatesByCARequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListCertificatesByCAResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listCertificatesByCA, inputKey: \ListCertificatesByCARequest.marker, outputKey: \ListCertificatesByCAResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Lists your Device Defender detect custom metrics. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listCustomMetricsPaginator<Result>( _ input: ListCustomMetricsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListCustomMetricsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listCustomMetrics, inputKey: \ListCustomMetricsRequest.nextToken, outputKey: \ListCustomMetricsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listCustomMetricsPaginator( _ input: ListCustomMetricsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListCustomMetricsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listCustomMetrics, inputKey: \ListCustomMetricsRequest.nextToken, outputKey: \ListCustomMetricsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists mitigation actions executions for a Device Defender ML Detect Security Profile. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listDetectMitigationActionsExecutionsPaginator<Result>( _ input: ListDetectMitigationActionsExecutionsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListDetectMitigationActionsExecutionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listDetectMitigationActionsExecutions, inputKey: \ListDetectMitigationActionsExecutionsRequest.nextToken, outputKey: \ListDetectMitigationActionsExecutionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listDetectMitigationActionsExecutionsPaginator( _ input: ListDetectMitigationActionsExecutionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListDetectMitigationActionsExecutionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listDetectMitigationActionsExecutions, inputKey: \ListDetectMitigationActionsExecutionsRequest.nextToken, outputKey: \ListDetectMitigationActionsExecutionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// List of Device Defender ML Detect mitigation actions tasks. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listDetectMitigationActionsTasksPaginator<Result>( _ input: ListDetectMitigationActionsTasksRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListDetectMitigationActionsTasksResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listDetectMitigationActionsTasks, inputKey: \ListDetectMitigationActionsTasksRequest.nextToken, outputKey: \ListDetectMitigationActionsTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listDetectMitigationActionsTasksPaginator( _ input: ListDetectMitigationActionsTasksRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListDetectMitigationActionsTasksResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listDetectMitigationActionsTasks, inputKey: \ListDetectMitigationActionsTasksRequest.nextToken, outputKey: \ListDetectMitigationActionsTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// List the set of dimensions that are defined for your AWS account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listDimensionsPaginator<Result>( _ input: ListDimensionsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListDimensionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listDimensions, inputKey: \ListDimensionsRequest.nextToken, outputKey: \ListDimensionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listDimensionsPaginator( _ input: ListDimensionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListDimensionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listDimensions, inputKey: \ListDimensionsRequest.nextToken, outputKey: \ListDimensionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Gets a list of domain configurations for the user. This list is sorted alphabetically by domain configuration name. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listDomainConfigurationsPaginator<Result>( _ input: ListDomainConfigurationsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListDomainConfigurationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listDomainConfigurations, inputKey: \ListDomainConfigurationsRequest.marker, outputKey: \ListDomainConfigurationsResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listDomainConfigurationsPaginator( _ input: ListDomainConfigurationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListDomainConfigurationsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listDomainConfigurations, inputKey: \ListDomainConfigurationsRequest.marker, outputKey: \ListDomainConfigurationsResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Lists the search indices. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listIndicesPaginator<Result>( _ input: ListIndicesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListIndicesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listIndices, inputKey: \ListIndicesRequest.nextToken, outputKey: \ListIndicesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listIndicesPaginator( _ input: ListIndicesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListIndicesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listIndices, inputKey: \ListIndicesRequest.nextToken, outputKey: \ListIndicesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the job executions for a job. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listJobExecutionsForJobPaginator<Result>( _ input: ListJobExecutionsForJobRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListJobExecutionsForJobResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listJobExecutionsForJob, inputKey: \ListJobExecutionsForJobRequest.nextToken, outputKey: \ListJobExecutionsForJobResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listJobExecutionsForJobPaginator( _ input: ListJobExecutionsForJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListJobExecutionsForJobResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listJobExecutionsForJob, inputKey: \ListJobExecutionsForJobRequest.nextToken, outputKey: \ListJobExecutionsForJobResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the job executions for the specified thing. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listJobExecutionsForThingPaginator<Result>( _ input: ListJobExecutionsForThingRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListJobExecutionsForThingResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listJobExecutionsForThing, inputKey: \ListJobExecutionsForThingRequest.nextToken, outputKey: \ListJobExecutionsForThingResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listJobExecutionsForThingPaginator( _ input: ListJobExecutionsForThingRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListJobExecutionsForThingResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listJobExecutionsForThing, inputKey: \ListJobExecutionsForThingRequest.nextToken, outputKey: \ListJobExecutionsForThingResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists jobs. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listJobsPaginator<Result>( _ input: ListJobsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListJobsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listJobs, inputKey: \ListJobsRequest.nextToken, outputKey: \ListJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listJobsPaginator( _ input: ListJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListJobsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listJobs, inputKey: \ListJobsRequest.nextToken, outputKey: \ListJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Gets a list of all mitigation actions that match the specified filter criteria. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listMitigationActionsPaginator<Result>( _ input: ListMitigationActionsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListMitigationActionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listMitigationActions, inputKey: \ListMitigationActionsRequest.nextToken, outputKey: \ListMitigationActionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listMitigationActionsPaginator( _ input: ListMitigationActionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListMitigationActionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listMitigationActions, inputKey: \ListMitigationActionsRequest.nextToken, outputKey: \ListMitigationActionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists OTA updates. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listOTAUpdatesPaginator<Result>( _ input: ListOTAUpdatesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListOTAUpdatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listOTAUpdates, inputKey: \ListOTAUpdatesRequest.nextToken, outputKey: \ListOTAUpdatesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listOTAUpdatesPaginator( _ input: ListOTAUpdatesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListOTAUpdatesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listOTAUpdates, inputKey: \ListOTAUpdatesRequest.nextToken, outputKey: \ListOTAUpdatesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists certificates that are being transferred but not yet accepted. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listOutgoingCertificatesPaginator<Result>( _ input: ListOutgoingCertificatesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListOutgoingCertificatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listOutgoingCertificates, inputKey: \ListOutgoingCertificatesRequest.marker, outputKey: \ListOutgoingCertificatesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listOutgoingCertificatesPaginator( _ input: ListOutgoingCertificatesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListOutgoingCertificatesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listOutgoingCertificates, inputKey: \ListOutgoingCertificatesRequest.marker, outputKey: \ListOutgoingCertificatesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Lists your policies. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listPoliciesPaginator<Result>( _ input: ListPoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPolicies, inputKey: \ListPoliciesRequest.marker, outputKey: \ListPoliciesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listPoliciesPaginator( _ input: ListPoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPolicies, inputKey: \ListPoliciesRequest.marker, outputKey: \ListPoliciesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Lists the principals associated with the specified policy. Note: This API is deprecated. Please use ListTargetsForPolicy instead. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. @available(*, deprecated, message: "ListPolicyPrincipals is deprecated.") public func listPolicyPrincipalsPaginator<Result>( _ input: ListPolicyPrincipalsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPolicyPrincipalsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPolicyPrincipals, inputKey: \ListPolicyPrincipalsRequest.marker, outputKey: \ListPolicyPrincipalsResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. @available(*, deprecated, message: "ListPolicyPrincipals is deprecated.") public func listPolicyPrincipalsPaginator( _ input: ListPolicyPrincipalsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPolicyPrincipalsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPolicyPrincipals, inputKey: \ListPolicyPrincipalsRequest.marker, outputKey: \ListPolicyPrincipalsResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Lists the policies attached to the specified principal. If you use an Cognito identity, the ID must be in AmazonCognito Identity format. Note: This API is deprecated. Please use ListAttachedPolicies instead. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. @available(*, deprecated, message: "ListPrincipalPolicies is deprecated.") public func listPrincipalPoliciesPaginator<Result>( _ input: ListPrincipalPoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPrincipalPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPrincipalPolicies, inputKey: \ListPrincipalPoliciesRequest.marker, outputKey: \ListPrincipalPoliciesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. @available(*, deprecated, message: "ListPrincipalPolicies is deprecated.") public func listPrincipalPoliciesPaginator( _ input: ListPrincipalPoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPrincipalPoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPrincipalPolicies, inputKey: \ListPrincipalPoliciesRequest.marker, outputKey: \ListPrincipalPoliciesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Lists the things associated with the specified principal. A principal can be X.509 certificates, IAM users, groups, and roles, Amazon Cognito identities or federated identities. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listPrincipalThingsPaginator<Result>( _ input: ListPrincipalThingsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPrincipalThingsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPrincipalThings, inputKey: \ListPrincipalThingsRequest.nextToken, outputKey: \ListPrincipalThingsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listPrincipalThingsPaginator( _ input: ListPrincipalThingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPrincipalThingsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPrincipalThings, inputKey: \ListPrincipalThingsRequest.nextToken, outputKey: \ListPrincipalThingsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// A list of fleet provisioning template versions. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listProvisioningTemplateVersionsPaginator<Result>( _ input: ListProvisioningTemplateVersionsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListProvisioningTemplateVersionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listProvisioningTemplateVersions, inputKey: \ListProvisioningTemplateVersionsRequest.nextToken, outputKey: \ListProvisioningTemplateVersionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listProvisioningTemplateVersionsPaginator( _ input: ListProvisioningTemplateVersionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListProvisioningTemplateVersionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listProvisioningTemplateVersions, inputKey: \ListProvisioningTemplateVersionsRequest.nextToken, outputKey: \ListProvisioningTemplateVersionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the fleet provisioning templates in your AWS account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listProvisioningTemplatesPaginator<Result>( _ input: ListProvisioningTemplatesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListProvisioningTemplatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listProvisioningTemplates, inputKey: \ListProvisioningTemplatesRequest.nextToken, outputKey: \ListProvisioningTemplatesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listProvisioningTemplatesPaginator( _ input: ListProvisioningTemplatesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListProvisioningTemplatesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listProvisioningTemplates, inputKey: \ListProvisioningTemplatesRequest.nextToken, outputKey: \ListProvisioningTemplatesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the role aliases registered in your account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listRoleAliasesPaginator<Result>( _ input: ListRoleAliasesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListRoleAliasesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listRoleAliases, inputKey: \ListRoleAliasesRequest.marker, outputKey: \ListRoleAliasesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listRoleAliasesPaginator( _ input: ListRoleAliasesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListRoleAliasesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listRoleAliases, inputKey: \ListRoleAliasesRequest.marker, outputKey: \ListRoleAliasesResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Lists all of your scheduled audits. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listScheduledAuditsPaginator<Result>( _ input: ListScheduledAuditsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListScheduledAuditsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listScheduledAudits, inputKey: \ListScheduledAuditsRequest.nextToken, outputKey: \ListScheduledAuditsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listScheduledAuditsPaginator( _ input: ListScheduledAuditsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListScheduledAuditsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listScheduledAudits, inputKey: \ListScheduledAuditsRequest.nextToken, outputKey: \ListScheduledAuditsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the Device Defender security profiles you've created. You can filter security profiles by dimension or custom metric. dimensionName and metricName cannot be used in the same request. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listSecurityProfilesPaginator<Result>( _ input: ListSecurityProfilesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListSecurityProfilesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSecurityProfiles, inputKey: \ListSecurityProfilesRequest.nextToken, outputKey: \ListSecurityProfilesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listSecurityProfilesPaginator( _ input: ListSecurityProfilesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListSecurityProfilesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSecurityProfiles, inputKey: \ListSecurityProfilesRequest.nextToken, outputKey: \ListSecurityProfilesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the Device Defender security profiles attached to a target (thing group). /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listSecurityProfilesForTargetPaginator<Result>( _ input: ListSecurityProfilesForTargetRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListSecurityProfilesForTargetResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSecurityProfilesForTarget, inputKey: \ListSecurityProfilesForTargetRequest.nextToken, outputKey: \ListSecurityProfilesForTargetResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listSecurityProfilesForTargetPaginator( _ input: ListSecurityProfilesForTargetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListSecurityProfilesForTargetResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSecurityProfilesForTarget, inputKey: \ListSecurityProfilesForTargetRequest.nextToken, outputKey: \ListSecurityProfilesForTargetResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists all of the streams in your AWS account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listStreamsPaginator<Result>( _ input: ListStreamsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListStreamsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listStreams, inputKey: \ListStreamsRequest.nextToken, outputKey: \ListStreamsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listStreamsPaginator( _ input: ListStreamsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListStreamsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listStreams, inputKey: \ListStreamsRequest.nextToken, outputKey: \ListStreamsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the tags (metadata) you have assigned to the resource. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listTagsForResourcePaginator<Result>( _ input: ListTagsForResourceRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListTagsForResourceResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listTagsForResource, inputKey: \ListTagsForResourceRequest.nextToken, outputKey: \ListTagsForResourceResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listTagsForResourcePaginator( _ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListTagsForResourceResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listTagsForResource, inputKey: \ListTagsForResourceRequest.nextToken, outputKey: \ListTagsForResourceResponse.nextToken, on: eventLoop, onPage: onPage ) } /// List targets for the specified policy. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listTargetsForPolicyPaginator<Result>( _ input: ListTargetsForPolicyRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListTargetsForPolicyResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listTargetsForPolicy, inputKey: \ListTargetsForPolicyRequest.marker, outputKey: \ListTargetsForPolicyResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listTargetsForPolicyPaginator( _ input: ListTargetsForPolicyRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListTargetsForPolicyResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listTargetsForPolicy, inputKey: \ListTargetsForPolicyRequest.marker, outputKey: \ListTargetsForPolicyResponse.nextMarker, on: eventLoop, onPage: onPage ) } /// Lists the targets (thing groups) associated with a given Device Defender security profile. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listTargetsForSecurityProfilePaginator<Result>( _ input: ListTargetsForSecurityProfileRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListTargetsForSecurityProfileResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listTargetsForSecurityProfile, inputKey: \ListTargetsForSecurityProfileRequest.nextToken, outputKey: \ListTargetsForSecurityProfileResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listTargetsForSecurityProfilePaginator( _ input: ListTargetsForSecurityProfileRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListTargetsForSecurityProfileResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listTargetsForSecurityProfile, inputKey: \ListTargetsForSecurityProfileRequest.nextToken, outputKey: \ListTargetsForSecurityProfileResponse.nextToken, on: eventLoop, onPage: onPage ) } /// List the thing groups in your account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listThingGroupsPaginator<Result>( _ input: ListThingGroupsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListThingGroupsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listThingGroups, inputKey: \ListThingGroupsRequest.nextToken, outputKey: \ListThingGroupsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listThingGroupsPaginator( _ input: ListThingGroupsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListThingGroupsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listThingGroups, inputKey: \ListThingGroupsRequest.nextToken, outputKey: \ListThingGroupsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// List the thing groups to which the specified thing belongs. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listThingGroupsForThingPaginator<Result>( _ input: ListThingGroupsForThingRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListThingGroupsForThingResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listThingGroupsForThing, inputKey: \ListThingGroupsForThingRequest.nextToken, outputKey: \ListThingGroupsForThingResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listThingGroupsForThingPaginator( _ input: ListThingGroupsForThingRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListThingGroupsForThingResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listThingGroupsForThing, inputKey: \ListThingGroupsForThingRequest.nextToken, outputKey: \ListThingGroupsForThingResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the principals associated with the specified thing. A principal can be X.509 certificates, IAM users, groups, and roles, Amazon Cognito identities or federated identities. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listThingPrincipalsPaginator<Result>( _ input: ListThingPrincipalsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListThingPrincipalsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listThingPrincipals, inputKey: \ListThingPrincipalsRequest.nextToken, outputKey: \ListThingPrincipalsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listThingPrincipalsPaginator( _ input: ListThingPrincipalsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListThingPrincipalsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listThingPrincipals, inputKey: \ListThingPrincipalsRequest.nextToken, outputKey: \ListThingPrincipalsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Information about the thing registration tasks. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listThingRegistrationTaskReportsPaginator<Result>( _ input: ListThingRegistrationTaskReportsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListThingRegistrationTaskReportsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listThingRegistrationTaskReports, inputKey: \ListThingRegistrationTaskReportsRequest.nextToken, outputKey: \ListThingRegistrationTaskReportsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listThingRegistrationTaskReportsPaginator( _ input: ListThingRegistrationTaskReportsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListThingRegistrationTaskReportsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listThingRegistrationTaskReports, inputKey: \ListThingRegistrationTaskReportsRequest.nextToken, outputKey: \ListThingRegistrationTaskReportsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// List bulk thing provisioning tasks. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listThingRegistrationTasksPaginator<Result>( _ input: ListThingRegistrationTasksRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListThingRegistrationTasksResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listThingRegistrationTasks, inputKey: \ListThingRegistrationTasksRequest.nextToken, outputKey: \ListThingRegistrationTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listThingRegistrationTasksPaginator( _ input: ListThingRegistrationTasksRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListThingRegistrationTasksResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listThingRegistrationTasks, inputKey: \ListThingRegistrationTasksRequest.nextToken, outputKey: \ListThingRegistrationTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the existing thing types. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listThingTypesPaginator<Result>( _ input: ListThingTypesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListThingTypesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listThingTypes, inputKey: \ListThingTypesRequest.nextToken, outputKey: \ListThingTypesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listThingTypesPaginator( _ input: ListThingTypesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListThingTypesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listThingTypes, inputKey: \ListThingTypesRequest.nextToken, outputKey: \ListThingTypesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists your things. Use the attributeName and attributeValue parameters to filter your things. For example, calling ListThings with attributeName=Color and attributeValue=Red retrieves all things in the registry that contain an attribute Color with the value Red. You will not be charged for calling this API if an Access denied error is returned. You will also not be charged if no attributes or pagination token was provided in request and no pagination token and no results were returned. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listThingsPaginator<Result>( _ input: ListThingsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListThingsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listThings, inputKey: \ListThingsRequest.nextToken, outputKey: \ListThingsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listThingsPaginator( _ input: ListThingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListThingsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listThings, inputKey: \ListThingsRequest.nextToken, outputKey: \ListThingsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the things you have added to the given billing group. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listThingsInBillingGroupPaginator<Result>( _ input: ListThingsInBillingGroupRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListThingsInBillingGroupResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listThingsInBillingGroup, inputKey: \ListThingsInBillingGroupRequest.nextToken, outputKey: \ListThingsInBillingGroupResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listThingsInBillingGroupPaginator( _ input: ListThingsInBillingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListThingsInBillingGroupResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listThingsInBillingGroup, inputKey: \ListThingsInBillingGroupRequest.nextToken, outputKey: \ListThingsInBillingGroupResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the things in the specified group. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listThingsInThingGroupPaginator<Result>( _ input: ListThingsInThingGroupRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListThingsInThingGroupResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listThingsInThingGroup, inputKey: \ListThingsInThingGroupRequest.nextToken, outputKey: \ListThingsInThingGroupResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listThingsInThingGroupPaginator( _ input: ListThingsInThingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListThingsInThingGroupResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listThingsInThingGroup, inputKey: \ListThingsInThingGroupRequest.nextToken, outputKey: \ListThingsInThingGroupResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists all the topic rule destinations in your AWS account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listTopicRuleDestinationsPaginator<Result>( _ input: ListTopicRuleDestinationsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListTopicRuleDestinationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listTopicRuleDestinations, inputKey: \ListTopicRuleDestinationsRequest.nextToken, outputKey: \ListTopicRuleDestinationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listTopicRuleDestinationsPaginator( _ input: ListTopicRuleDestinationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListTopicRuleDestinationsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listTopicRuleDestinations, inputKey: \ListTopicRuleDestinationsRequest.nextToken, outputKey: \ListTopicRuleDestinationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the rules for the specific topic. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listTopicRulesPaginator<Result>( _ input: ListTopicRulesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListTopicRulesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listTopicRules, inputKey: \ListTopicRulesRequest.nextToken, outputKey: \ListTopicRulesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listTopicRulesPaginator( _ input: ListTopicRulesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListTopicRulesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listTopicRules, inputKey: \ListTopicRulesRequest.nextToken, outputKey: \ListTopicRulesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists logging levels. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listV2LoggingLevelsPaginator<Result>( _ input: ListV2LoggingLevelsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListV2LoggingLevelsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listV2LoggingLevels, inputKey: \ListV2LoggingLevelsRequest.nextToken, outputKey: \ListV2LoggingLevelsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listV2LoggingLevelsPaginator( _ input: ListV2LoggingLevelsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListV2LoggingLevelsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listV2LoggingLevels, inputKey: \ListV2LoggingLevelsRequest.nextToken, outputKey: \ListV2LoggingLevelsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the Device Defender security profile violations discovered during the given time period. You can use filters to limit the results to those alerts issued for a particular security profile, behavior, or thing (device). /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listViolationEventsPaginator<Result>( _ input: ListViolationEventsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListViolationEventsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listViolationEvents, inputKey: \ListViolationEventsRequest.nextToken, outputKey: \ListViolationEventsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used for logging output /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listViolationEventsPaginator( _ input: ListViolationEventsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListViolationEventsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listViolationEvents, inputKey: \ListViolationEventsRequest.nextToken, outputKey: \ListViolationEventsResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension IoT.GetBehaviorModelTrainingSummariesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.GetBehaviorModelTrainingSummariesRequest { return .init( maxResults: self.maxResults, nextToken: token, securityProfileName: self.securityProfileName ) } } extension IoT.ListActiveViolationsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListActiveViolationsRequest { return .init( behaviorCriteriaType: self.behaviorCriteriaType, listSuppressedAlerts: self.listSuppressedAlerts, maxResults: self.maxResults, nextToken: token, securityProfileName: self.securityProfileName, thingName: self.thingName ) } } extension IoT.ListAttachedPoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListAttachedPoliciesRequest { return .init( marker: token, pageSize: self.pageSize, recursive: self.recursive, target: self.target ) } } extension IoT.ListAuditFindingsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListAuditFindingsRequest { return .init( checkName: self.checkName, endTime: self.endTime, listSuppressedFindings: self.listSuppressedFindings, maxResults: self.maxResults, nextToken: token, resourceIdentifier: self.resourceIdentifier, startTime: self.startTime, taskId: self.taskId ) } } extension IoT.ListAuditMitigationActionsExecutionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListAuditMitigationActionsExecutionsRequest { return .init( actionStatus: self.actionStatus, findingId: self.findingId, maxResults: self.maxResults, nextToken: token, taskId: self.taskId ) } } extension IoT.ListAuditMitigationActionsTasksRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListAuditMitigationActionsTasksRequest { return .init( auditTaskId: self.auditTaskId, endTime: self.endTime, findingId: self.findingId, maxResults: self.maxResults, nextToken: token, startTime: self.startTime, taskStatus: self.taskStatus ) } } extension IoT.ListAuditSuppressionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListAuditSuppressionsRequest { return .init( ascendingOrder: self.ascendingOrder, checkName: self.checkName, maxResults: self.maxResults, nextToken: token, resourceIdentifier: self.resourceIdentifier ) } } extension IoT.ListAuditTasksRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListAuditTasksRequest { return .init( endTime: self.endTime, maxResults: self.maxResults, nextToken: token, startTime: self.startTime, taskStatus: self.taskStatus, taskType: self.taskType ) } } extension IoT.ListAuthorizersRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListAuthorizersRequest { return .init( ascendingOrder: self.ascendingOrder, marker: token, pageSize: self.pageSize, status: self.status ) } } extension IoT.ListBillingGroupsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListBillingGroupsRequest { return .init( maxResults: self.maxResults, namePrefixFilter: self.namePrefixFilter, nextToken: token ) } } extension IoT.ListCACertificatesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListCACertificatesRequest { return .init( ascendingOrder: self.ascendingOrder, marker: token, pageSize: self.pageSize ) } } extension IoT.ListCertificatesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListCertificatesRequest { return .init( ascendingOrder: self.ascendingOrder, marker: token, pageSize: self.pageSize ) } } extension IoT.ListCertificatesByCARequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListCertificatesByCARequest { return .init( ascendingOrder: self.ascendingOrder, caCertificateId: self.caCertificateId, marker: token, pageSize: self.pageSize ) } } extension IoT.ListCustomMetricsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListCustomMetricsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension IoT.ListDetectMitigationActionsExecutionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListDetectMitigationActionsExecutionsRequest { return .init( endTime: self.endTime, maxResults: self.maxResults, nextToken: token, startTime: self.startTime, taskId: self.taskId, thingName: self.thingName, violationId: self.violationId ) } } extension IoT.ListDetectMitigationActionsTasksRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListDetectMitigationActionsTasksRequest { return .init( endTime: self.endTime, maxResults: self.maxResults, nextToken: token, startTime: self.startTime ) } } extension IoT.ListDimensionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListDimensionsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension IoT.ListDomainConfigurationsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListDomainConfigurationsRequest { return .init( marker: token, pageSize: self.pageSize, serviceType: self.serviceType ) } } extension IoT.ListIndicesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListIndicesRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension IoT.ListJobExecutionsForJobRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListJobExecutionsForJobRequest { return .init( jobId: self.jobId, maxResults: self.maxResults, nextToken: token, status: self.status ) } } extension IoT.ListJobExecutionsForThingRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListJobExecutionsForThingRequest { return .init( maxResults: self.maxResults, namespaceId: self.namespaceId, nextToken: token, status: self.status, thingName: self.thingName ) } } extension IoT.ListJobsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListJobsRequest { return .init( maxResults: self.maxResults, namespaceId: self.namespaceId, nextToken: token, status: self.status, targetSelection: self.targetSelection, thingGroupId: self.thingGroupId, thingGroupName: self.thingGroupName ) } } extension IoT.ListMitigationActionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListMitigationActionsRequest { return .init( actionType: self.actionType, maxResults: self.maxResults, nextToken: token ) } } extension IoT.ListOTAUpdatesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListOTAUpdatesRequest { return .init( maxResults: self.maxResults, nextToken: token, otaUpdateStatus: self.otaUpdateStatus ) } } extension IoT.ListOutgoingCertificatesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListOutgoingCertificatesRequest { return .init( ascendingOrder: self.ascendingOrder, marker: token, pageSize: self.pageSize ) } } extension IoT.ListPoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListPoliciesRequest { return .init( ascendingOrder: self.ascendingOrder, marker: token, pageSize: self.pageSize ) } } extension IoT.ListPolicyPrincipalsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListPolicyPrincipalsRequest { return .init( ascendingOrder: self.ascendingOrder, marker: token, pageSize: self.pageSize, policyName: self.policyName ) } } extension IoT.ListPrincipalPoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListPrincipalPoliciesRequest { return .init( ascendingOrder: self.ascendingOrder, marker: token, pageSize: self.pageSize, principal: self.principal ) } } extension IoT.ListPrincipalThingsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListPrincipalThingsRequest { return .init( maxResults: self.maxResults, nextToken: token, principal: self.principal ) } } extension IoT.ListProvisioningTemplateVersionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListProvisioningTemplateVersionsRequest { return .init( maxResults: self.maxResults, nextToken: token, templateName: self.templateName ) } } extension IoT.ListProvisioningTemplatesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListProvisioningTemplatesRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension IoT.ListRoleAliasesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListRoleAliasesRequest { return .init( ascendingOrder: self.ascendingOrder, marker: token, pageSize: self.pageSize ) } } extension IoT.ListScheduledAuditsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListScheduledAuditsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension IoT.ListSecurityProfilesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListSecurityProfilesRequest { return .init( dimensionName: self.dimensionName, maxResults: self.maxResults, metricName: self.metricName, nextToken: token ) } } extension IoT.ListSecurityProfilesForTargetRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListSecurityProfilesForTargetRequest { return .init( maxResults: self.maxResults, nextToken: token, recursive: self.recursive, securityProfileTargetArn: self.securityProfileTargetArn ) } } extension IoT.ListStreamsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListStreamsRequest { return .init( ascendingOrder: self.ascendingOrder, maxResults: self.maxResults, nextToken: token ) } } extension IoT.ListTagsForResourceRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListTagsForResourceRequest { return .init( nextToken: token, resourceArn: self.resourceArn ) } } extension IoT.ListTargetsForPolicyRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListTargetsForPolicyRequest { return .init( marker: token, pageSize: self.pageSize, policyName: self.policyName ) } } extension IoT.ListTargetsForSecurityProfileRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListTargetsForSecurityProfileRequest { return .init( maxResults: self.maxResults, nextToken: token, securityProfileName: self.securityProfileName ) } } extension IoT.ListThingGroupsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListThingGroupsRequest { return .init( maxResults: self.maxResults, namePrefixFilter: self.namePrefixFilter, nextToken: token, parentGroup: self.parentGroup, recursive: self.recursive ) } } extension IoT.ListThingGroupsForThingRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListThingGroupsForThingRequest { return .init( maxResults: self.maxResults, nextToken: token, thingName: self.thingName ) } } extension IoT.ListThingPrincipalsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListThingPrincipalsRequest { return .init( maxResults: self.maxResults, nextToken: token, thingName: self.thingName ) } } extension IoT.ListThingRegistrationTaskReportsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListThingRegistrationTaskReportsRequest { return .init( maxResults: self.maxResults, nextToken: token, reportType: self.reportType, taskId: self.taskId ) } } extension IoT.ListThingRegistrationTasksRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListThingRegistrationTasksRequest { return .init( maxResults: self.maxResults, nextToken: token, status: self.status ) } } extension IoT.ListThingTypesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListThingTypesRequest { return .init( maxResults: self.maxResults, nextToken: token, thingTypeName: self.thingTypeName ) } } extension IoT.ListThingsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListThingsRequest { return .init( attributeName: self.attributeName, attributeValue: self.attributeValue, maxResults: self.maxResults, nextToken: token, thingTypeName: self.thingTypeName, usePrefixAttributeValue: self.usePrefixAttributeValue ) } } extension IoT.ListThingsInBillingGroupRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListThingsInBillingGroupRequest { return .init( billingGroupName: self.billingGroupName, maxResults: self.maxResults, nextToken: token ) } } extension IoT.ListThingsInThingGroupRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListThingsInThingGroupRequest { return .init( maxResults: self.maxResults, nextToken: token, recursive: self.recursive, thingGroupName: self.thingGroupName ) } } extension IoT.ListTopicRuleDestinationsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListTopicRuleDestinationsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension IoT.ListTopicRulesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListTopicRulesRequest { return .init( maxResults: self.maxResults, nextToken: token, ruleDisabled: self.ruleDisabled, topic: self.topic ) } } extension IoT.ListV2LoggingLevelsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListV2LoggingLevelsRequest { return .init( maxResults: self.maxResults, nextToken: token, targetType: self.targetType ) } } extension IoT.ListViolationEventsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IoT.ListViolationEventsRequest { return .init( behaviorCriteriaType: self.behaviorCriteriaType, endTime: self.endTime, listSuppressedAlerts: self.listSuppressedAlerts, maxResults: self.maxResults, nextToken: token, securityProfileName: self.securityProfileName, startTime: self.startTime, thingName: self.thingName ) } }
44.93694
501
0.656662
0a127bf44882f6d5dc85fee1a95ccb4e69f9b2fe
6,034
// // GameScene.swift // Runner // // Created by mac on 2017/9/6. // Copyright © 2017年 CoderZNBmm. All rights reserved. // import SpriteKit class GameScene: SKScene,SKPhysicsContactDelegate,ProtocolMainScene { lazy var runner:Runner = Runner() lazy var platformFactory = PlatformFactory() //跑了多远变量 var distance :CGFloat = 0.0 //移动速度 var moveSpeed:CGFloat = 5.0 //最大速度 var maxSpeed :CGFloat = 15.0 //判断最后一个平台还有多远完全进入游戏场景 var lastDis:CGFloat = 0.0 //是否game over var isLose = false override func didMove(to view: SKView) { super.didMove(to: view) //物理世界代理 self.physicsWorld.contactDelegate = self //重力设置 self.physicsWorld.gravity = CGVector(dx: 0, dy: -5) //设置物理体 self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame) //设置种类标示 self.physicsBody?.categoryBitMask = BitMaskType.scene //是否响应物理效果 self.physicsBody?.isDynamic = false //场景的背景颜色 let skyColor = SKColor(red: 112/255, green: 197/255, blue: 205/255, alpha: 1) self.backgroundColor = skyColor //给跑酷小人定一个初始位置 runner.position = CGPoint(x: 10, y: 200) //将跑酷小人显示在场景中 self.addChild(runner) //将平台工厂加入视图 self.addChild(platformFactory) //将屏幕的宽度传到平台工厂类中 platformFactory.sceneWidth = self.frame.width //设置代理 platformFactory.delegate = self //初始平台让小人有立足之地 platformFactory.createPlatform(midNum: 3, x: 0, y: 160) } //触碰屏幕响应的方法 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if isLose { reSet() }else { runner.jump() } } // MARK: - 碰撞代理方法 //离开平台时记录起跳点 func didEnd(_ contact: SKPhysicsContact) { runner.jumpStart = runner.position.y } //碰撞检测方法 func didBegin(_ contact: SKPhysicsContact) { //小人和台子碰撞 if (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask) == (BitMaskType.platform | BitMaskType.runner){ //假设平台不会下沉,用于给后面判断平台是否会被熊猫震的颤抖 var isDown = false //用于判断接触平台后能否转变为跑的状态,默认值为false不能转换 var canRun = false //如果碰撞体A是平台 if contact.bodyA.categoryBitMask == BitMaskType.platform { //如果是会下沉的平台 if (contact.bodyA.node as! Platform).isDown { isDown = true //让平台接收重力影响 contact.bodyA.node?.physicsBody?.isDynamic = true //不将碰撞效果取消,平台下沉的时候会跟着熊猫跑这不是我们希望看到的, //大家可以将这行注释掉看看效果 contact.bodyA.node?.physicsBody?.collisionBitMask = 0 //如果是会升降的平台 } if (contact.bodyB.node?.position.y)! > contact.bodyA.node!.position.y { canRun=true } //如果碰撞体B是平台 }else if contact.bodyB.categoryBitMask == BitMaskType.platform { if (contact.bodyB.node as! Platform).isDown { contact.bodyB.node?.physicsBody?.isDynamic = true contact.bodyB.node?.physicsBody?.collisionBitMask = 0 isDown = true } if (contact.bodyA.node?.position.y)! > (contact.bodyB.node?.position.y)! { canRun=true } } //判断是否打滚 runner.jumpEnd = runner.position.y if runner.jumpEnd-runner.jumpStart <= -60 { runner.roll() //如果平台下沉就不让它被震得颤抖一下 if !isDown { downAndUp(node: contact.bodyA.node!) downAndUp(node: contact.bodyB.node!) } }else{ if canRun { runner.run() } } } //如果熊猫和场景边缘碰撞 if (contact.bodyA.categoryBitMask|contact.bodyB.categoryBitMask) == (BitMaskType.scene | BitMaskType.runner) { print("游戏结束") isLose = true } } override func update(_ currentTime: TimeInterval) { //如果小人出现了位置偏差,就逐渐恢复 if runner.position.x < 10 { let x = runner.position.x + 1 runner.position = CGPoint(x: x, y: runner.position.y) } if !isLose { lastDis -= moveSpeed //速度以5为基础,以跑的距离除以2000为增量 var tempSpeed = CGFloat(5 + Int(distance/2000)) //将速度控制在maxSpeed if tempSpeed > maxSpeed { tempSpeed = maxSpeed } //如果移动速度小于新的速度就改变 if moveSpeed < tempSpeed { moveSpeed = tempSpeed } if lastDis <= 0 { platformFactory.createPlatformRandom() } platformFactory.move(speed: self.moveSpeed) distance += moveSpeed } } func onGetData(dist:CGFloat){ self.lastDis = dist } //up and down 方法(平台震动一下) func downAndUp(node :SKNode,down:CGFloat = -50,downTime:Double=0.05, up:CGFloat=50,upTime:Double=0.1){ //下沉动作 let downAct = SKAction.moveBy(x: 0, y: down, duration: downTime) //上升动过 let upAct = SKAction.moveBy(x: 0, y: up, duration: upTime) //下沉上升动作序列 let downUpAct = SKAction.sequence([downAct,upAct]) node.run(downUpAct) } //重新开始游戏 func reSet(){ //重置isLose变量 isLose = false //重置小人位置 runner.position = CGPoint(x: 100, y: 200) //重置移动速度 moveSpeed = 15.0 //重置跑的距离 distance = 0.0 //重置首个平台完全进入游戏场景的距离 lastDis = 0.0 //平台工厂的重置方法 platformFactory.reSet() //创建一个初始的平台给熊猫一个立足之地 platformFactory.createPlatform(midNum: 3, x: 0, y: 160) } }
30.0199
90
0.525356
6133ba4ca858e394568bd27706fcd2655f05bc1e
140
import XCTest import SlickLoadingSpinnerTests var tests = [XCTestCaseEntry]() tests += SlickLoadingSpinnerTests.allTests() XCTMain(tests)
17.5
44
0.814286
f41f349581f484ae8ceb2d0917182456f3560cfd
2,334
// // Shared.swift // MeetingBar // // Created by Andrii Leitsius on 13.01.2021. // Copyright © 2021 Andrii Leitsius. All rights reserved. // import SwiftUI import Defaults import UserNotifications struct JoinEventNotificationPicker: View { @Default(.joinEventNotification) var joinEventNotification @Default(.joinEventNotificationTime) var joinEventNotificationTime func checkNotificationSettings() -> (Bool, Bool) { var noAlertStyle: Bool = false var notificationsDisabled: Bool = false let center = UNUserNotificationCenter.current() let group = DispatchGroup() group.enter() center.getNotificationSettings { notificationSettings in noAlertStyle = notificationSettings.alertStyle != UNAlertStyle.alert notificationsDisabled = notificationSettings.authorizationStatus != UNAuthorizationStatus.authorized group.leave() } group.wait() return (noAlertStyle, notificationsDisabled) } var body: some View { HStack { Toggle("Send notification to join next event meeting", isOn: $joinEventNotification) Picker("", selection: $joinEventNotificationTime) { Text("when event starts").tag(JoinEventNotificationTime.atStart) Text("1 minute before").tag(JoinEventNotificationTime.minuteBefore) Text("3 minutes before").tag(JoinEventNotificationTime.threeMinuteBefore) Text("5 minutes before").tag(JoinEventNotificationTime.fiveMinuteBefore) }.frame(width: 150, alignment: .leading).labelsHidden().disabled(!joinEventNotification) } let (noAlertStyle, disabled) = checkNotificationSettings() if noAlertStyle && !disabled && joinEventNotification { Text("⚠️ Your macos notification settings for Meetingbar are currently not set to alert. Please activate alerts if you want to have persistent notifications.").foregroundColor(Color.gray).font(.system(size: 12)) } if disabled && joinEventNotification { Text("⚠️ Your macos notification settings for Meetingbar are currently off. Please enable the notifications in macos system settings to do not miss a meeting.").foregroundColor(Color.gray).font(.system(size: 12)) } } }
40.947368
224
0.692802
7a2befbb629af30811c1a99535a8877581c262ab
2,200
// // AppDelegate.swift // CSSickyFlowLayoutHeaders // // Created by Roman Ustiantcev on 26/05/2017. // Copyright © 2017 Roman Ustiantcev. 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:. } }
46.808511
285
0.758182
69578de627446fbeca6e3863908f933d362d37bd
1,616
import Console public final class DockerRun: Command { public let id = "run" public let signature: [Argument] = [] public let help: [String] = [ "Runs the Docker image created with the", "Docker build command." ] public let console: ConsoleProtocol public init(console: ConsoleProtocol) { self.console = console } public func run(arguments: [String]) throws { do { _ = try console.backgroundExecute(program: "which", arguments: ["docker"]) } catch ConsoleError.backgroundExecute { console.info("Visit https://www.docker.com/products/docker-toolbox") throw ToolboxError.general("Docker not installed.") } do { let contents = try console.backgroundExecute(program: "ls", arguments: ["."]) if !contents.contains("Dockerfile") { throw ToolboxError.general("No Dockerfile found") } } catch ConsoleError.backgroundExecute(_) { throw ToolboxError.general("Could not check for Dockerfile") } let swiftVersion: String do { swiftVersion = try console.backgroundExecute(program: "cat", arguments: [".swift-version"]).trim() } catch { throw ToolboxError.general("Could not determine Swift version from .swift-version file.") } let imageName = DockerBuild.imageName(version: swiftVersion) console.info("Copy and run the following line:") console.print("docker run --rm -it -v $(PWD):/vapor -p 8080:8080 \(imageName)") } }
32.32
110
0.608292
e6f599b556558a2b5c72d88bfca6bd94f551d4bb
577
// // D2SDisplayProperties.swift // Direct to SwiftUI // // Copyright © 2019 ZeeZide GmbH. All rights reserved. // import SwiftUI /** * A ForEach over the `displayPropertyKeys`. */ public struct D2SDisplayProperties: View { @Environment(\.displayPropertyKeys) private var displayPropertyKeys public var body: some View { ForEach(displayPropertyKeys, id: \String.self) { propertyKey in PropertySwitch() .environment(\.propertyKey, propertyKey) } } private struct PropertySwitch: View { @Environment(\.rowComponent) var body } }
20.607143
69
0.69844
9074060d562aa6b9266bdb31e03f1397ef6a0d27
1,120
// // SomaPlugin.swift // Soma // // Created by Calvin Chang on 2018/9/12. // Copyright © 2018 SAP. All rights reserved. // import Foundation public protocol SomaPluginType { func didConnect(target: SomaTargetType) func didDisconnect(target: SomaTargetType) func willEmit(target: SomaTargetType, emit: SomaEmitType) -> SomaEmitType func didReceive(target: SomaTargetType, message: SomaMessage) func process(target: SomaTargetType, message: SomaMessage) -> SomaMessage func didTimeout(target: SomaTargetType) func didErrorOccur(target: SomaTargetType, errors: [Any]) } public extension SomaPluginType { func didConnect(target: SomaTargetType) {} func didDisconnect(target: SomaTargetType) {} func willEmit(target: SomaTargetType, emit: SomaEmitType) -> SomaEmitType { return emit } func didReceive(target: SomaTargetType, message: SomaMessage) {} func process(target: SomaTargetType, message: SomaMessage) -> SomaMessage { return message } func didTimeout(target: SomaTargetType) {} func didErrorOccur(target: SomaTargetType, errors: [Any]) {} }
26.666667
96
0.734821
d6d993c5112ee3f10630d826d6eec01cf11725bf
932
// // CleanSwiftExampleTests.swift // CleanSwiftExampleTests // // Created by Yoni Vizel on 10/30/20. // import XCTest @testable import CleanSwiftExample class CleanSwiftExampleTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } 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 { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.411765
111
0.675966
f70fd5e39a2c1a74c8ab12be73971aa275569984
661
// // DiningView.swift // PennMobile // // Created by CHOI Jongmin on 4/6/2020. // Copyright © 2020 PennLabs. All rights reserved. // import SwiftUI @available(iOS 14, *) struct DiningView: View { @StateObject var diningVM = DiningViewModelSwiftUI.instance var body: some View { return VStack(spacing: 0) { DiningViewHeader() .padding() DiningVenueView() } .environmentObject(diningVM) } } @available(iOS 14, *) struct DiningView_Previews: PreviewProvider { static var previews: some View { DiningView() } }
20.030303
63
0.570348
3385259f157858e3cde61e4935b2adbaa7b583da
3,617
//===--- SequenceWrapper.swift - sequence/collection wrapper protocols ----===// // // 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 // //===----------------------------------------------------------------------===// // // To create a Sequence that forwards requirements to an // underlying Sequence, have it conform to this protocol. // //===----------------------------------------------------------------------===// /// A type that is just a wrapper over some base Sequence @_show_in_interface public // @testable protocol _SequenceWrapper : Sequence { associatedtype Base : Sequence where Base.Element == Element associatedtype Iterator = Base.Iterator associatedtype SubSequence = Base.SubSequence var _base: Base { get } } extension _SequenceWrapper { @inlinable // generic-performance public var underestimatedCount: Int { return _base.underestimatedCount } @inlinable // generic-performance public func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? { return try _base._preprocessingPass(preprocess) } } extension _SequenceWrapper where Iterator == Base.Iterator { @inlinable // generic-performance public __consuming func makeIterator() -> Iterator { return self._base.makeIterator() } @inlinable // generic-performance @discardableResult public __consuming func _copyContents( initializing buf: UnsafeMutableBufferPointer<Element> ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) { return _base._copyContents(initializing: buf) } } extension _SequenceWrapper { @inlinable // generic-performance public func _customContainsEquatableElement( _ element: Element ) -> Bool? { return _base._customContainsEquatableElement(element) } @inlinable // generic-performance public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { return _base._copyToContiguousArray() } } extension _SequenceWrapper where SubSequence == Base.SubSequence { @inlinable // generic-performance public __consuming func dropFirst(_ n: Int) -> SubSequence { return _base.dropFirst(n) } @inlinable // generic-performance public __consuming func dropLast(_ n: Int) -> SubSequence { return _base.dropLast(n) } @inlinable // generic-performance public __consuming func prefix(_ maxLength: Int) -> SubSequence { return _base.prefix(maxLength) } @inlinable // generic-performance public __consuming func suffix(_ maxLength: Int) -> SubSequence { return _base.suffix(maxLength) } @inlinable // generic-performance public __consuming func drop( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence { return try _base.drop(while: predicate) } @inlinable // generic-performance public __consuming func prefix( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence { return try _base.prefix(while: predicate) } @inlinable // generic-performance public __consuming func split( maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator isSeparator: (Element) throws -> Bool ) rethrows -> [SubSequence] { return try _base.split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: isSeparator ) } }
30.91453
80
0.697816
018ba4bba651dd0165a945fcfc80dbe4d36d4efc
3,076
/** * Identity * Copyright (c) John Sundell 2019 * Licensed under the MIT license (see LICENSE file) */ import XCTest import Identity final class IdentityTests: XCTestCase { func testStringBasedIdentifier() { struct Model: Identifiable { let id: ID } let model = Model(id: "Hello, world!") XCTAssertEqual(model.id, "Hello, world!") } func testIntBasedIdentifier() { struct Model: Identifiable { typealias RawIdentifier = Int let id: ID } let model = Model(id: 7) XCTAssertEqual(model.id, 7) } func testCodableIdentifier() throws { struct Model: Identifiable, Codable { typealias RawIdentifier = UUID let id: ID } let model = Model(id: Identifier(rawValue: UUID())) let data = try JSONEncoder().encode(model) let decoded = try JSONDecoder().decode(Model.self, from: data) XCTAssertEqual(model.id, decoded.id) } func testIdentifierEncodedAsSingleValue() throws { struct Model: Identifiable, Codable { let id: ID } let model = Model(id: "I'm an ID") let data = try JSONEncoder().encode(model) let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] XCTAssertEqual(json?["id"] as? String, "I'm an ID") } func testExpressingIdentifierUsingStringInterpolation() { struct Model: Identifiable { let id: ID } let model = Model(id: "Hello, world!") XCTAssertEqual(model.id, "Hello, \("world!")") } func testIdentifierDescription() { struct StringModel: Identifiable { let id: ID } struct IntModel: Identifiable { typealias RawIdentifier = Int let id: ID } let stringID: StringModel.ID = "An ID" let intID: IntModel.ID = 7 XCTAssertEqual(stringID.description, "An ID") XCTAssertEqual(intID.description, "7") } func testIdentifierHashValue() { struct FirstModel: Identifiable { let id: ID } struct SecondModel: Identifiable { let id: ID } let first = FirstModel(id: "0") let second = SecondModel(id: "0") XCTAssertNotEqual(first.id.hashValue, second.id.hashValue) } func testAllTestsRunOnLinux() { verifyAllTestsRunOnLinux() } } extension IdentityTests: LinuxTestable { static var allTests = [ ("testStringBasedIdentifier", testStringBasedIdentifier), ("testIntBasedIdentifier", testIntBasedIdentifier), ("testCodableIdentifier", testCodableIdentifier), ("testIdentifierEncodedAsSingleValue", testIdentifierEncodedAsSingleValue), ("testExpressingIdentifierUsingStringInterpolation", testExpressingIdentifierUsingStringInterpolation), ("testIdentifierDescription", testIdentifierDescription), ("testIdentifierHashValue", testIdentifierHashValue), ] }
27.963636
111
0.616385
9b1725802bbb4effa43c741db42fd17612c42428
1,962
// // ViewController.swift // TableViewPratice // // Created by hyeoktae kwon on 15/04/2019. // Copyright © 2019 hyeoktae kwon. All rights reserved. // import UIKit final class ViewController: UIViewController { var data = Array(1...50) let tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() tableView.frame = view.frame tableView.dataSource = self tableView.rowHeight = 60 view.addSubview(tableView) tableView.register(CustomCellTableViewCell.self, forCellReuseIdentifier: "CustomCell") } @objc func addOne(_ sender: UIButton) { let cell = sender.superview?.superview as! CustomCellTableViewCell } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCellTableViewCell // delegate 로 푸는법 // cell.delegate = self // cell.button.tag = indexPath.row if cell.textLabel?.text == nil { cell.button.addTarget(self, action: #selector(addOne(_:)), for: .touchUpInside) } cell.textLabel?.text = "\(data[indexPath.row])" return cell } } // delegate로 푸는 법 extension ViewController: CustomCellTableViewCellDelegate { func customCell(_ customCell: CustomCellTableViewCell, didTapButton: UIButton) { if let indexPath = tableView.indexPath(for: customCell) { let addedNumber = data[indexPath.row] + 1 data[indexPath.row] = addedNumber customCell.textLabel?.text = "\(addedNumber)" } } }
26.16
122
0.630479
3839560a3eba838e65da05288b8e742d8e01a1c5
1,523
/** * (C) Copyright IBM Corp. 2016, 2018. * * 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 /** Response from the classifier for a phrase. */ public struct Classification: Codable, Equatable { /** Unique identifier for this classifier. */ public var classifierID: String? /** Link to the classifier. */ public var url: String? /** The submitted phrase. */ public var text: String? /** The class with the highest confidence. */ public var topClass: String? /** An array of up to ten class-confidence pairs sorted in descending order of confidence. */ public var classes: [ClassifiedClass]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case classifierID = "classifier_id" case url = "url" case text = "text" case topClass = "top_class" case classes = "classes" } }
25.813559
91
0.664478
ab58bc2c90c91f30c477decf0b218f9dc182e16d
1,317
// // AssetBurnCell.swift // WavesWallet-iOS // // Created by Pavel Gubin on 11/16/18. // Copyright © 2018 Waves Platform. All rights reserved. // import UIKit import Extensions private enum Constants { static let defaultHeight: CGFloat = 56 static let topOffset: CGFloat = 50 } final class AssetBurnCell: UITableViewCell, NibReusable { struct Model { let isSpam: Bool } @IBOutlet private weak var viewContainer: UIView! @IBOutlet private weak var labelTitle: UILabel! @IBOutlet private weak var topOffset: NSLayoutConstraint! var burnAction:(() -> Void)? override func awakeFromNib() { super.awakeFromNib() viewContainer.addTableCellShadowStyle() labelTitle.text = Localizable.Waves.Tokenburn.Label.tokenBurn } @IBAction private func burnTapped(_ sender: Any) { burnAction?() } } extension AssetBurnCell: ViewConfiguration { func update(with model: AssetBurnCell.Model) { topOffset.constant = model.isSpam ? 0 : Constants.topOffset } } extension AssetBurnCell: ViewCalculateHeight { static func viewHeight(model: AssetBurnCell.Model, width: CGFloat) -> CGFloat { return model.isSpam ? Constants.defaultHeight : Constants.defaultHeight + Constants.topOffset } }
25.326923
101
0.690964
757605a14724b0783365f0c40e61f149f7674a2a
5,955
// // SingleBroadcasterViewController.swift // AgoraLive // // Created by CavanSu on 2020/4/13. // Copyright © 2020 Agora. All rights reserved. // import UIKit import RxSwift import RxRelay class SingleBroadcasterViewController: MaskViewController, LiveViewController { @IBOutlet weak var ownerView: IconTextView! @IBOutlet weak var renderView: UIView! // LiveViewController var tintColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6) var bag: DisposeBag = DisposeBag() // ViewController var userListVC: UserListViewController? var giftAudienceVC: GiftAudienceViewController? var chatVC: ChatViewController? var bottomToolsVC: BottomToolsViewController? var beautyVC: BeautySettingsViewController? var musicVC: MusicViewController? var dataVC: RealDataViewController? var extensionVC: ExtensionViewController? var mediaSettingsNavi: UIViewController? var giftVC: GiftViewController? var gifVC: GIFViewController? // View @IBOutlet weak var personCountView: IconTextView! internal lazy var chatInputView: ChatInputView = { let chatHeight: CGFloat = 50.0 let frame = CGRect(x: 0, y: UIScreen.main.bounds.height, width: UIScreen.main.bounds.width, height: chatHeight) let view = ChatInputView(frame: frame) view.isHidden = true return view }() // ViewModel var audienceListVM = LiveRoomAudienceList() var musicVM = MusicVM() var chatVM = ChatVM() var giftVM = GiftVM() var deviceVM = MediaDeviceVM() var playerVM = PlayerVM() var enhancementVM = VideoEnhancementVM() var monitor = NetworkMonitor(host: "www.apple.com") override func viewDidLoad() { super.viewDidLoad() let image = UIImage(named: "live-bg") self.view.layer.contents = image?.cgImage guard let session = ALCenter.shared().liveSession else { assert(false) return } liveSession(session) liveRoom(session: session) audience() chatList() gift() bottomTools(session: session, tintColor: tintColor) chatInput() musicList() netMonitor() superResolution(session: session) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier else { return } switch identifier { case "GiftAudienceViewController": let vc = segue.destination as! GiftAudienceViewController self.giftAudienceVC = vc case "BottomToolsViewController": guard let session = ALCenter.shared().liveSession, let role = session.role else { assert(false) return } let vc = segue.destination as! BottomToolsViewController vc.perspective = role.type vc.liveType = session.type self.bottomToolsVC = vc case "ChatViewController": let vc = segue.destination as! ChatViewController vc.cellColor = tintColor self.chatVC = vc default: break } } } extension SingleBroadcasterViewController { // MARK: - Live Room func liveRoom(session: LiveSession) { guard let owner = session.owner else { assert(false) return } let images = ALCenter.shared().centerProvideImagesHelper() ownerView.offsetLeftX = -13 ownerView.offsetRightX = 5 ownerView.label.textColor = .white ownerView.label.font = UIFont.systemFont(ofSize: 11) switch owner { case .localUser(let user): ownerView.label.text = user.info.name ownerView.imageView.image = images.getHead(index: user.info.imageIndex) playerVM.startRenderLocalVideoStream(id: user.agoraUserId, view: self.renderView) deviceVM.camera = .on deviceVM.mic = .on case .otherUser(let remote): ownerView.label.text = remote.info.name ownerView.imageView.image = images.getHead(index: remote.info.imageIndex) playerVM.startRenderRemoteVideoStream(id: remote.agoraUserId, view: self.renderView) deviceVM.camera = .off deviceVM.mic = .off } } func superResolution(session: LiveSession) { bottomToolsVC?.superRenderButton.rx.tap.subscribe(onNext: { [unowned self, unowned session] () in guard let vc = self.bottomToolsVC else { assert(false) return } vc.superRenderButton.isSelected.toggle() if vc.superRenderButton.isSelected { let view = TagImageTextToast(frame: CGRect(x: 0, y: 300, width: 181, height: 44.0), filletRadius: 8) view.text = NSLocalizedString("Super_Resolution_Enabled") view.tagImage = UIImage(named: "icon-done") self.showToastView(view, duration: 1.0) } switch session.owner { case .otherUser(let remote): let media = ALCenter.shared().centerProvideMediaHelper() media.player.renderRemoteVideoStream(id: remote.agoraUserId, superResolution: vc.superRenderButton.isSelected ? .on : .off) default: assert(false) break } }).disposed(by: bag) } }
33.835227
116
0.575483
394278458843392b1bcc905755c3d4b47a6d6a31
493
// // APBaseTableViewCell.swift // APLayoutKit // // Created by Vladislav Sosiuk on 30.10.2020. // import UIKit open class APBaseTableViewCell: UITableViewCell { public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } public required init?(coder: NSCoder) { super.init(coder: coder) setup() } open func setup() { } }
19.72
86
0.63286
f96b9f2eeb706d99e17b92dfe128a814fb4a5330
15,036
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. @_exported import AWSSDKSwiftCore /* Client object for interacting with AWS Snowball service. AWS Snowball is a petabyte-scale data transport solution that uses secure devices to transfer large amounts of data between your on-premises data centers and Amazon Simple Storage Service (Amazon S3). The Snowball commands described here provide access to the same functionality that is available in the AWS Snowball Management Console, which enables you to create and manage jobs for Snowball. To transfer data locally with a Snowball device, you'll need to use the Snowball client or the Amazon S3 API adapter for Snowball. For more information, see the User Guide. */ public struct Snowball { // MARK: Member variables public let client: AWSClient public let serviceConfig: AWSServiceConfig // MARK: Initialization /// Initialize the Snowball client /// - parameters: /// - client: AWSClient used to process requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, region: AWSSDKSwiftCore.Region? = nil, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil ) { self.client = client self.serviceConfig = AWSServiceConfig( region: region, partition: region?.partition ?? partition, amzTarget: "AWSIESnowballJobManagementService", service: "snowball", serviceProtocol: .json(version: "1.1"), apiVersion: "2016-06-30", endpoint: endpoint, possibleErrorTypes: [SnowballErrorType.self], timeout: timeout ) } // MARK: API Calls /// Cancels a cluster job. You can only cancel a cluster job while it's in the AwaitingQuorum status. You'll have at least an hour after creating a cluster job to cancel it. public func cancelCluster(_ input: CancelClusterRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<CancelClusterResult> { return self.client.execute(operation: "CancelCluster", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Cancels the specified job. You can only cancel a job before its JobState value changes to PreparingAppliance. Requesting the ListJobs or DescribeJob action returns a job's JobState as part of the response element data returned. public func cancelJob(_ input: CancelJobRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<CancelJobResult> { return self.client.execute(operation: "CancelJob", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Creates an address for a Snowball to be shipped to. In most regions, addresses are validated at the time of creation. The address you provide must be located within the serviceable area of your region. If the address is invalid or unsupported, then an exception is thrown. public func createAddress(_ input: CreateAddressRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<CreateAddressResult> { return self.client.execute(operation: "CreateAddress", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Creates an empty cluster. Each cluster supports five nodes. You use the CreateJob action separately to create the jobs for each of these nodes. The cluster does not ship until these five node jobs have been created. public func createCluster(_ input: CreateClusterRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<CreateClusterResult> { return self.client.execute(operation: "CreateCluster", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Creates a job to import or export data between Amazon S3 and your on-premises data center. Your AWS account must have the right trust policies and permissions in place to create a job for Snowball. If you're creating a job for a node in a cluster, you only need to provide the clusterId value; the other job attributes are inherited from the cluster. public func createJob(_ input: CreateJobRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<CreateJobResult> { return self.client.execute(operation: "CreateJob", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Takes an AddressId and returns specific details about that address in the form of an Address object. public func describeAddress(_ input: DescribeAddressRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeAddressResult> { return self.client.execute(operation: "DescribeAddress", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Returns a specified number of ADDRESS objects. Calling this API in one of the US regions will return addresses from the list of all addresses associated with this account in all US regions. public func describeAddresses(_ input: DescribeAddressesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeAddressesResult> { return self.client.execute(operation: "DescribeAddresses", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Returns information about a specific cluster including shipping information, cluster status, and other important metadata. public func describeCluster(_ input: DescribeClusterRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeClusterResult> { return self.client.execute(operation: "DescribeCluster", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Returns information about a specific job including shipping information, job status, and other important metadata. public func describeJob(_ input: DescribeJobRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeJobResult> { return self.client.execute(operation: "DescribeJob", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Returns a link to an Amazon S3 presigned URL for the manifest file associated with the specified JobId value. You can access the manifest file for up to 60 minutes after this request has been made. To access the manifest file after 60 minutes have passed, you'll have to make another call to the GetJobManifest action. The manifest is an encrypted file that you can download after your job enters the WithCustomer status. The manifest is decrypted by using the UnlockCode code value, when you pass both values to the Snowball through the Snowball client when the client is started for the first time. As a best practice, we recommend that you don't save a copy of an UnlockCode value in the same location as the manifest file for that job. Saving these separately helps prevent unauthorized parties from gaining access to the Snowball associated with that job. The credentials of a given job, including its manifest file and unlock code, expire 90 days after the job is created. public func getJobManifest(_ input: GetJobManifestRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<GetJobManifestResult> { return self.client.execute(operation: "GetJobManifest", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Returns the UnlockCode code value for the specified job. A particular UnlockCode value can be accessed for up to 90 days after the associated job has been created. The UnlockCode value is a 29-character code with 25 alphanumeric characters and 4 hyphens. This code is used to decrypt the manifest file when it is passed along with the manifest to the Snowball through the Snowball client when the client is started for the first time. As a best practice, we recommend that you don't save a copy of the UnlockCode in the same location as the manifest file for that job. Saving these separately helps prevent unauthorized parties from gaining access to the Snowball associated with that job. public func getJobUnlockCode(_ input: GetJobUnlockCodeRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<GetJobUnlockCodeResult> { return self.client.execute(operation: "GetJobUnlockCode", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Returns information about the Snowball service limit for your account, and also the number of Snowballs your account has in use. The default service limit for the number of Snowballs that you can have at one time is 1. If you want to increase your service limit, contact AWS Support. public func getSnowballUsage(_ input: GetSnowballUsageRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<GetSnowballUsageResult> { return self.client.execute(operation: "GetSnowballUsage", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Returns an Amazon S3 presigned URL for an update file associated with a specified JobId. public func getSoftwareUpdates(_ input: GetSoftwareUpdatesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<GetSoftwareUpdatesResult> { return self.client.execute(operation: "GetSoftwareUpdates", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Returns an array of JobListEntry objects of the specified length. Each JobListEntry object is for a job in the specified cluster and contains a job's state, a job's ID, and other information. public func listClusterJobs(_ input: ListClusterJobsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListClusterJobsResult> { return self.client.execute(operation: "ListClusterJobs", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Returns an array of ClusterListEntry objects of the specified length. Each ClusterListEntry object contains a cluster's state, a cluster's ID, and other important status information. public func listClusters(_ input: ListClustersRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListClustersResult> { return self.client.execute(operation: "ListClusters", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// This action returns a list of the different Amazon EC2 Amazon Machine Images (AMIs) that are owned by your AWS account that would be supported for use on a Snowball Edge device. Currently, supported AMIs are based on the CentOS 7 (x86_64) - with Updates HVM, Ubuntu Server 14.04 LTS (HVM), and Ubuntu 16.04 LTS - Xenial (HVM) images, available on the AWS Marketplace. public func listCompatibleImages(_ input: ListCompatibleImagesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListCompatibleImagesResult> { return self.client.execute(operation: "ListCompatibleImages", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Returns an array of JobListEntry objects of the specified length. Each JobListEntry object contains a job's state, a job's ID, and a value that indicates whether the job is a job part, in the case of export jobs. Calling this API action in one of the US regions will return jobs from the list of all jobs associated with this account in all US regions. public func listJobs(_ input: ListJobsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListJobsResult> { return self.client.execute(operation: "ListJobs", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// While a cluster's ClusterState value is in the AwaitingQuorum state, you can update some of the information associated with a cluster. Once the cluster changes to a different job state, usually 60 minutes after the cluster being created, this action is no longer available. public func updateCluster(_ input: UpdateClusterRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<UpdateClusterResult> { return self.client.execute(operation: "UpdateCluster", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// While a job's JobState value is New, you can update some of the information associated with a job. Once the job changes to a different job state, usually within 60 minutes of the job being created, this action is no longer available. public func updateJob(_ input: UpdateJobRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<UpdateJobResult> { return self.client.execute(operation: "UpdateJob", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } }
95.164557
987
0.744081
26be2920038f02d8614492a6f799258a5396bb06
8,563
import UIKit import MapboxMaps @objc(SymbolClusteringExample) class SymbolClusteringExample: UIViewController, ExampleProtocol { internal var mapView: MapView! override public func viewDidLoad() { super.viewDidLoad() // Create a `MapView` centered over Washington, DC. let center = CLLocationCoordinate2D(latitude: 38.889215, longitude: -77.039354) let cameraOptions = CameraOptions(center: center, zoom: 11) let mapInitOptions = MapInitOptions(cameraOptions: cameraOptions, styleURI: .dark) mapView = MapView(frame: view.bounds, mapInitOptions: mapInitOptions) mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(mapView) // Add the source and style layers once the map has loaded. mapView.mapboxMap.onNext(.mapLoaded) { _ in self.addSymbolClusteringLayers() } let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(gestureRecognizer:))) mapView.addGestureRecognizer(tapGestureRecognizer) } func addSymbolClusteringLayers() { let style = mapView.mapboxMap.style // The image named `fire-station-11` is included in the app's Assets.xcassets bundle. // In order to recolor an image, you need to add a template image to the map's style. // The image's rendering mode can be set programmatically or in the asset catalogue. let image = UIImage(named: "fire-station-11")!.withRenderingMode(.alwaysTemplate) // Add the image tp the map's style. Set `sdf` to `true`. This allows the icon images to be recolored. // For more information about `SDF`, or Signed Distance Fields, see // https://docs.mapbox.com/help/troubleshooting/using-recolorable-images-in-mapbox-maps/#what-are-signed-distance-fields-sdf try! style.addImage(image, id: "fire-station-icon", sdf: true, stretchX: [], stretchY: []) // Fire_Hydrants.geojson contains information about fire hydrants in the District of Columbia. // It was downloaded on 6/10/21 from https://opendata.dc.gov/datasets/DCGIS::fire-hydrants/about let url = Bundle.main.url(forResource: "Fire_Hydrants", withExtension: "geojson")! // Create a GeoJSONSource using the previously specified URL. var source = GeoJSONSource() source.data = .url(url) // Enable clustering for this source. source.cluster = true source.clusterRadius = 75 let sourceID = "fire-hydrant-source" var clusteredLayer = createClusteredLayer() clusteredLayer.source = sourceID var unclusteredLayer = createUnclusteredLayer() unclusteredLayer.source = sourceID // Add the source and two layers to the map. try! style.addSource(source, id: sourceID) try! style.addLayer(clusteredLayer) try! style.addLayer(unclusteredLayer, layerPosition: .below(clusteredLayer.id)) // This is used for internal testing purposes only and can be excluded // from your implementation. finish() } func createClusteredLayer() -> SymbolLayer { // Create a symbol layer to represent the clustered points. var clusteredLayer = SymbolLayer(id: "clustered-fire-hydrant-layer") // Filter out unclustered features by checking for `point_count`. This // is added to clusters when the cluster is created. If your source // data includes a `point_count` property, consider checking // for `cluster_id`. clusteredLayer.filter = Exp(.has) { "point_count" } clusteredLayer.iconImage = .constant(.name("fire-station-icon")) // Set the color of the icons based on the number of points within // a given cluster. The first value is a default value. clusteredLayer.iconColor = .expression(Exp(.step) { Exp(.get) { "point_count" } UIColor(red: 0.12, green: 0.90, blue: 0.57, alpha: 1.00) 50 UIColor(red: 0.12, green: 0.53, blue: 0.90, alpha: 1.00) 100 UIColor(red: 0.85, green: 0.11, blue: 0.38, alpha: 1.00) }) // Add an outline to the icons. clusteredLayer.iconHaloColor = .constant(StyleColor(.black)) clusteredLayer.iconHaloWidth = .constant(4) // Adjust the scale of the icons based on the number of points within an // individual cluster. The first value is a default value. clusteredLayer.iconSize = .expression(Exp(.step) { Exp(.get) { "point_count" } 2.5 0 2.5 50 3 100 3.5 }) return clusteredLayer } func createUnclusteredLayer() -> SymbolLayer { // Create a symbol layer to represent the points that aren't clustered. var unclusteredLayer = SymbolLayer(id: "unclustered-point-layer") // Filter out clusters by checking for `point_count`. unclusteredLayer.filter = Exp(.not) { Exp(.has) { "point_count" } } unclusteredLayer.iconImage = .constant(.name("fire-station-icon")) unclusteredLayer.iconColor = .constant(StyleColor(.white)) // Rotate the icon image based on the recorded water flow. // The `mod` operator allows you to use the remainder after dividing // the specified values. unclusteredLayer.iconRotate = .expression(Exp(.mod) { Exp(.get) { "FLOW" } 360 }) // Double the size of the icon image. unclusteredLayer.iconSize = .constant(2) return unclusteredLayer } @objc func handleTap(gestureRecognizer: UITapGestureRecognizer) { let point = gestureRecognizer.location(in: mapView) // Look for features at the tap location within the clustered and // unclustered layers. mapView.mapboxMap.queryRenderedFeatures(at: point, options: RenderedQueryOptions(layerIds: ["unclustered-point-layer", "clustered-fire-hydrant-layer"], filter: nil)) { [weak self] result in switch result { case .success(let queriedFeatures): // Return the first feature at that location, then pass attributes to the alert controller. // Check whether the feature has values for `ASSETNUM` and `LOCATIONDETAIL`. These properties // come from the fire hydrant dataset and indicate that the selected feature is not clustered. if let selectedFeatureProperties = queriedFeatures.first?.feature.properties, case let .string(featureInformation) = selectedFeatureProperties["ASSETNUM"], case let .string(location) = selectedFeatureProperties["LOCATIONDETAIL"] { self?.showAlert(withTitle: "Hydrant \(featureInformation)", and: "\(location)") // If the feature is a cluster, it will have `point_count` and `cluster_id` properties. These are assigned // when the cluster is created. } else if let selectedFeatureProperties = queriedFeatures.first?.feature.properties, case let .number(pointCount) = selectedFeatureProperties["point_count"], case let .number(clusterId) = selectedFeatureProperties["cluster_id"] { // If the tap landed on a cluster, pass the cluster ID and point count to the alert. self?.showAlert(withTitle: "Cluster ID \(Int(clusterId))", and: "There are \(Int(pointCount)) points in this cluster") } case .failure(let error): self?.showAlert(withTitle: "An error occurred: \(error.localizedDescription)", and: "Please try another hydrant") } } } // Present an alert with a given title and message. func showAlert(withTitle title: String, and message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } }
46.79235
148
0.625599
db9405051a15b477da5638b53b5f313cbdb976d8
3,312
// // PListDictionary.swift // PListKit • https://github.com/orchetect/PListKit // import Foundation extension PList { /// Translated Dictionary type used by PList public typealias PListDictionary = Dictionary<String, PListValue> } extension PList.RawDictionary { public func convertedToPListDictionary() -> PList.PListDictionary? { // translate to Swift-friendly types var newDict: PList.PListDictionary = [:] for (keyRaw, value) in self { // key must be translatable to String guard let key = keyRaw as? String else { return nil } //if key == "SidebarWidthTenElevenOrLater" { // print("SidebarWidthTenElevenOrLater - type: ", String(describing: type(of: value)), "value:", value) // print("NSNumber doubleValue:", (value as? NSNumber)?.doubleValue as Any) // print("NSNumber intValue:", (value as? NSNumber)?.intValue as Any) // (value as? NSNumber)?.boolValue // (value as? NSNumber)?.decimalValue // (value as? NSNumber)?.doubleValue // (value as? NSNumber)?.floatValue // (value as? NSNumber)?.attributeKeys // (value as? NSNumber)?.className //} // ***** type(of:) is a workaround to test for a boolean type, since testing for NSNumber's boolValue constants is tricky in Swift // this may be a computationally expensive operation, so ideally it should be replaced with a better method in future if String(describing: type(of: value)) == "__NSCFBoolean" { // ensure conversion to Bool actually succeeds; if not, add as its original type as a silent failsafe if let val = value as? Bool { newDict[key] = val } else { return nil } } else { switch value { case let val as String: newDict[key] = val case let val as Int: // ***** values stored as <real> will import as Int if they have a decimal of .0 newDict[key] = val case let val as Double: newDict[key] = val case let val as Date: newDict[key] = val case let val as Data: newDict[key] = val case let val as PList.RawDictionary: guard let translated = val.convertedToPListDictionary() else { return nil } newDict[key] = translated case let val as PList.RawArray: guard let translated = val.convertedToPListArray() else { return nil } newDict[key] = translated default: return nil // this should never happen } } } return newDict } }
36.395604
142
0.486111
bf924a1e8f0d2b6ec7ed1120b02120acd6b700d0
1,984
import UIKit import ThemeKit struct UniswapSettingsModule { static func dataSource(tradeService: UniswapTradeService) -> ISwapSettingsDataSource? { guard let ethereumPlatformCoin = try? App.shared.marketKit.platformCoin(coinType: .ethereum) else { return nil } let platformCoin = tradeService.platformCoinIn let coinCode = platformCoin?.code ?? ethereumPlatformCoin.code let chainCoinCode = platformCoin.flatMap { UDNAddressParserItem.chainCoinCode(coinType: $0.platform.coinType) } let chain = platformCoin.flatMap { UDNAddressParserItem.chain(coinType: $0.platform.coinType) } let addressParserChain = AddressParserChain() .append(handler: EvmAddressParser()) .append(handler: UDNAddressParserItem(coinCode: coinCode, platformCoinCode: chainCoinCode, chain: chain)) let addressUriParser = AddressParserFactory.parser(coinType: ethereumPlatformCoin.coinType) let addressService = AddressService(addressUriParser: addressUriParser, addressParserChain: addressParserChain, initialAddress: tradeService.settings.recipient) let service = UniswapSettingsService(tradeOptions: tradeService.settings, addressService: addressService) let viewModel = UniswapSettingsViewModel(service: service, tradeService: tradeService, decimalParser: AmountDecimalParser()) let recipientViewModel = RecipientAddressViewModel(service: addressService, handlerDelegate: nil) let slippageViewModel = SwapSlippageViewModel(service: service, decimalParser: AmountDecimalParser()) let deadlineViewModel = SwapDeadlineViewModel(service: service, decimalParser: AmountDecimalParser()) return UniswapSettingsDataSource( viewModel: viewModel, recipientViewModel: recipientViewModel, slippageViewModel: slippageViewModel, deadlineViewModel: deadlineViewModel ) } }
50.871795
168
0.739415
5bad285ba7ea3ce718b443b576eaab134193d2e5
1,828
// // SirenBundleExtension.swift // SirenExample // // Created by Arthur Sabintsev on 3/17/17. // Copyright © 2017 Sabintsev iOS Projects. All rights reserved. // import Foundation // MARK: - Bundle Extension for Siren extension Bundle { class func bundleID() -> String? { return Bundle.main.bundleIdentifier } class func sirenBundlePath() -> String { return Bundle(for: Siren.self).path(forResource: "Siren", ofType: "bundle") as String! } class func sirenForcedBundlePath(forceLanguageLocalization: Siren.LanguageType) -> String { let path = sirenBundlePath() let name = forceLanguageLocalization.rawValue return Bundle(path: path)!.path(forResource: name, ofType: "lproj")! } class func localizedString(forKey key: String, forceLanguageLocalization: Siren.LanguageType?) -> String { var path = sirenBundlePath() let table = "SirenLocalizable" if let forceLanguageLocalization = forceLanguageLocalization { path = sirenForcedBundlePath(forceLanguageLocalization: forceLanguageLocalization) } return Bundle(path: path)!.localizedString(forKey: key, value: key, table: table) } class func bestMatchingAppName() -> String { let bundleDisplayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String let bundleName = Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) as? String return bundleDisplayName ?? bundleName ?? "" } } // MARK: - Bundle Extension for Testing Siren extension Bundle { func testLocalizedString(forKey key: String, forceLanguageLocalization: Siren.LanguageType?) -> String { return Bundle.localizedString(forKey: key, forceLanguageLocalization: forceLanguageLocalization) } }
33.236364
110
0.706783
ab43451612f215cca013d236884364f0998e124e
13,834
import Foundation import UIKit public protocol DynamicPickerableView { associatedtype ValueType: Codable var value: ValueType { get } } open class DynamicPickerView<V>: View where V: UIView, V: DynamicPickerableView { public typealias Done = (_ result: V.ValueType) -> () public typealias Cancel = () -> () let title: String public init (_ title: String? = nil) { self.title = title ?? "" super.init(frame: .zero) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Variables var defaultHeight: CGFloat = 238 var allowImpactFeedback = true var cancelTitle: String = "Cancel" { didSet { cancelButton.title(cancelTitle) }} var doneTitle: String = "Done" { didSet { doneButton.title(doneTitle) }} var cancelFont: UIFont = .boldSystemFont(ofSize: 15) { didSet { cancelButton.font(v: cancelFont) }} var doneFont: UIFont = .boldSystemFont(ofSize: 15) { didSet { doneButton.font(v: doneFont) }} var titleFont: UIFont = .systemFont(ofSize: 17) { didSet { titleLabel.font(v: titleFont) }} var cancelColor: UIColor = .cyan { didSet { cancelButton.color(cancelColor) }} var doneColor: UIColor = .cyan { didSet { doneButton.color(doneColor) }} var cancelHighlightedColor: UIColor = .blue { didSet { cancelButton.color(cancelHighlightedColor, .highlighted) }} var doneHighlightedColor: UIColor = .blue { didSet { doneButton.color(doneHighlightedColor, .highlighted) }} var titleColor: UIColor = .black { didSet { titleLabel.color(titleColor) }} // MARK: Callbacks var onDone: Done = { _ in } var onChange: Done = { _ in } var onCancel: Cancel = {} lazy var containerView = View.subviews { return [pickerView, cancelButton, titleLabel, doneButton] }.edgesToSuperview(leading: 0, trailing: 0, bottom: defaultHeight) .height(defaultHeight) .background(.white) lazy var pickerView = V() lazy var cancelButton = Button(cancelTitle) .edgesToSuperview(top: 0, leading: 8) .font(v: cancelFont) .color(cancelColor) .color(cancelHighlightedColor, .highlighted) .onTapGesture { // TODO: onCancel() } lazy var titleLabel = Text(title) .font(v: titleFont) .color(titleColor) .centerY(to: cancelButton) .centerXInSuperview() lazy var doneButton = Button(doneTitle) .edgesToSuperview(top: 0, trailing: -8) .font(v: doneFont) .color(doneColor) .color(doneHighlightedColor, .highlighted) .onTapGesture { // TODO: onDone() } open override func buildView() { super.buildView() edgesToSuperview() background(.init(red: 0, green: 0, blue: 0, alpha: 0.3)) hidden() alpha(0) body { containerView } pickerView.leftAnchor.constraint(equalTo: containerView.leftAnchor).activated() pickerView.rightAnchor.constraint(equalTo: containerView.rightAnchor).activated() pickerView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).activated() pickerView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4).activated() } @discardableResult public func disableImpactFeedback() -> Self { allowImpactFeedback = false return self } @discardableResult public func height(_ value: CGFloat) -> Self { defaultHeight = value return self } @discardableResult public func onDone(_ value: @escaping Done) -> Self { onDone = value return self } @discardableResult public func onChange(_ value: @escaping Done) -> Self { onChange = value return self } @discardableResult public func onCancel(_ value: @escaping Cancel) -> Self { onCancel = value return self } // MARK: Fonts @discardableResult public func cancelFont(v: UIFont?) -> Self { guard let v = v else { return self } self.cancelFont = v return self } @discardableResult public func doneFont(v: UIFont?) -> Self { guard let v = v else { return self } self.doneFont = v return self } @discardableResult public func titleFont(v: UIFont?) -> Self { guard let v = v else { return self } self.titleFont = v return self } @discardableResult public func cancelFont(_ identifier: FontIdentifier, _ size: CGFloat) -> Self { cancelFont(v: UIFont(name: identifier.fontName, size: size)) } @discardableResult public func doneFont(_ identifier: FontIdentifier, _ size: CGFloat) -> Self { doneFont(v: UIFont(name: identifier.fontName, size: size)) } @discardableResult public func titleFont(_ identifier: FontIdentifier, _ size: CGFloat) -> Self { titleFont(v: UIFont(name: identifier.fontName, size: size)) } @discardableResult public func buttonsFont(v: UIFont?) -> Self { cancelFont(v: v).doneFont(v: v) } @discardableResult public func buttonsFont(_ identifier: FontIdentifier, _ size: CGFloat) -> Self { buttonsFont(v: UIFont(name: identifier.fontName, size: size)) } // MARK: Colors @discardableResult public func titleColor(_ color: UIColor) -> Self { titleColor = color return self } @discardableResult public func titleColor(_ number: Int) -> Self { titleColor(number.color) } @discardableResult public func cancelColor(_ color: UIColor) -> Self { cancelColor = color return self } @discardableResult public func cancelColor(_ number: Int) -> Self { cancelColor(number.color) } @discardableResult public func doneColor(_ color: UIColor) -> Self { doneColor = color return self } @discardableResult public func doneColor(_ number: Int) -> Self { doneColor(number.color) } @discardableResult public func buttonsColor(_ color: UIColor) -> Self { cancelColor(color).doneColor(color) } @discardableResult public func buttonsColor(_ number: Int) -> Self { buttonsColor(number.color) } @discardableResult public func cancelHighlightedColor(_ color: UIColor) -> Self { cancelHighlightedColor = color return self } @discardableResult public func cancelHighlightedColor(_ number: Int) -> Self { cancelHighlightedColor(number.color) } @discardableResult public func doneHighlightedColor(_ color: UIColor) -> Self { doneHighlightedColor = color return self } @discardableResult public func doneHighlightedColor(_ number: Int) -> Self { doneHighlightedColor(number.color) } @discardableResult public func buttonsHighlightedColor(_ color: UIColor) -> Self { cancelHighlightedColor(color).doneHighlightedColor(color) } @discardableResult public func buttonsHighlightedColor(_ number: Int) -> Self { buttonsHighlightedColor(number.color) } public func _show(in view: UIView) { view.body { self } layoutIfNeeded() UIView.animate(withDuration: 0.5) { self.alpha = 1 self.containerView.bottom = 0 self.layoutIfNeeded() } if allowImpactFeedback { ImpactFeedback.bzz(.heavy) } } @objc public func _hide() { UIView.animate(withDuration: 0.5, animations: { self.alpha = 0 self.containerView.bottom = self.defaultHeight self.layoutIfNeeded() }) { _ in self.removeFromSuperview() } } @objc fileprivate func changed() { onChange(pickerView.value) } @objc fileprivate func cancel() { onCancel() _hide() if allowImpactFeedback { ImpactFeedback.bzz(.light) } } @objc fileprivate func done() { onDone(pickerView.value) _hide() if allowImpactFeedback { ImpactFeedback.success() } } } // MARK: PickerPopup + UIDatePicker public typealias DatePickerPopup = DynamicPickerView<DatePicker> extension UIDatePicker: DynamicPickerableView { public typealias ValueType = Date public var value: Date { return date } } extension DynamicPickerView where V == DatePicker { @discardableResult public func mode(_ value: UIDatePicker.Mode) -> Self { pickerView.mode(value) return self } @discardableResult public func locale(_ value: Locale) -> Self { pickerView.locale(value) return self } @discardableResult public func calendar(_ value: Calendar) -> Self { pickerView.calendar(value) return self } @discardableResult public func timeZone(_ value: TimeZone) -> Self { pickerView.timeZone(value) return self } @discardableResult public func date(_ value: Date) -> Self { pickerView.date(value) return self } @discardableResult public func minimumDate(_ value: Date) -> Self { pickerView.minimumDate(value) return self } @discardableResult public func maximumDate(_ value: Date) -> Self { pickerView.maximumDate(value) return self } @discardableResult public func countDownDuration(_ value: TimeInterval) -> Self { pickerView.countDownDuration(value) return self } @discardableResult public func minuteInterval(_ value: Int) -> Self { pickerView.minuteInterval(value) return self } public func show(in view: UIView) { onChange(pickerView.date) if let minimumDate = pickerView.minimumDate { pickerView.minimumDate = minimumDate if minimumDate > pickerView.date { var endOfDay = pickerView.calendar.startOfDay(for: minimumDate) endOfDay.addTimeInterval(86399) onChange(endOfDay) } } if let maximumDate = pickerView.maximumDate { pickerView.maximumDate = maximumDate if maximumDate < pickerView.date { pickerView.setDate(pickerView.maximumDate!, animated: false) var endOfDay = pickerView.calendar.startOfDay(for: maximumDate) endOfDay.addTimeInterval(86399) onChange(endOfDay) } } pickerView.onChange(onChange) _show(in: view) } } //// MARK: PickerPopup + WeekdayPickerView // //public typealias WeightPickerPopup = DynamicPickerView<WeightPickerView> // //extension WeightPickerView: DynamicPickerableView { // public typealias ValueType = Day // public var value: Day { return day } //} // //extension DynamicPickerView where V == WeightPickerView { // public func show(in view: UIView, // day: WeekdayPickerView.Day?, // onChange: @escaping (WeekdayPickerView.Day) -> Void, // onCancel: @escaping PickerCancel, // completion: @escaping (WeekdayPickerView.Day) -> Void) { // self.onDone = completion // self.onChange = onChange // self.onCancel = onCancel // if let day = day { // picker.setDay(day, animated: false) // } else { // onChange(picker.day) // picker.setDay(picker.day, animated: false) // } // picker.onChange = onChange // show(in: view) // } //} // //public class WeightPickerView: PickerView, UIPickerViewDataSource, UIPickerViewDelegate { // public enum Day: Int, Codable { // case sun, mon, tue, wed, thu, fri, sat // // public static var all: [Day] = [.sun, .mon, .tue, .wed, .thu, .fri, .sat] // // public var name: String { // switch self { // case .sun: return "Sunday" // case .mon: return "Monday" // case .tue: return "Tuesday" // case .wed: return "Wednesday" // case .thu: return "Thursday" // case .fri: return "Friday" // case .sat: return "Saturday" // } // } // } // // public var day: Day // // public init () { // day = Day(rawValue: Calendar(identifier: .gregorian).component(.weekday, from: Date())) ?? .mon // super.init(frame: .zero) // self.dataSource = self // self.delegate = self // } // // required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } // // public var onChange: (Day) -> Void = { _ in } // // public func setDay(_ day: Day, animated: Bool) { // self.day = day // selectRow(day.rawValue, inComponent: 0, animated: animated) // } // // // MARK: DataSource // // public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { // return 7 // } // // public func numberOfComponents(in pickerView: UIPickerView) -> Int { // return 1 // } // // // MARK: Delegate // // func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { // return Day.all[row].name // } // // func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // day = Day.all[row] // onChange(day) // } //}
29.496802
118
0.606115
fc015265e99947bba194fcb95a5dd043fb7636f5
3,881
// // File.swift // // // Created by Daniel Leping on 09/01/2021. // import Foundation #if !COCOAPODS import Avalanche #endif public struct KeyPair { public enum Error: Swift.Error { case badPrivateKey case badSeed(seed: Data) case badChainCodeLength(length: Int) case badStringPartsCount(count: Int) case badStringPrefix(prefix: String) case badBase58(b58: String) case deriveFailed } public let publicKey: Data public let chainCode: Data? private let _sk: Data public init(sk: Data, chainCode: Data?) throws { guard let pub = Algos.Secp256k1.privateToPublic(privateKey: sk, compressed: true) else { throw Error.badPrivateKey } guard chainCode?.count ?? 32 == 32 else { throw Error.badChainCodeLength(length: chainCode!.count) } self._sk = sk self.chainCode = chainCode self.publicKey = pub } } public extension KeyPair { /// import from string init(key: String) throws { let parts = key.split(separator: "-") guard parts.count == 2 else { throw Error.badStringPartsCount(count: parts.count) } guard parts[0] == "PrivateKey" else { throw Error.badStringPrefix(prefix: String(parts[0])) } guard let pk = Algos.Base58.from(cb58: String(parts[1])) else { throw Error.badBase58(b58: String(parts[1])) } try self.init(sk: pk, chainCode: nil) } init(seed: Data) throws { guard let gen = Algos.Secp256k1.privateFromSeed(seed: seed) else { throw Error.badSeed(seed: seed) } try self.init(sk: gen.pk, chainCode: gen.cc) } func derive(index: UInt32, hard: Bool) throws -> KeyPair { guard let cc = chainCode else { throw Error.badChainCodeLength(length: 0) } guard let der = Algos.Secp256k1.derivePrivate(pk: _sk, cc: cc, index: index, hard: hard) else { throw Error.deriveFailed } return try KeyPair(sk: der.pk, chainCode: der.cc) } func address(hrp: String, chainId: String) -> Address { try! Address(pubKey: publicKey, hrp: hrp, chainId: chainId) } var ethAddress: EthAddress { try! EthAddress(pubKey: publicKey) } func signAvalanche(serialized tx: Data) -> Signature? { guard let data = Algos.Avalanche.sign(data: tx, with: _sk) else { return nil } return Signature(data: data) } func signAvalanche(message data: Data) -> Signature? { let prefixed = Data("\u{1A}Avalanche Signed Message:\n".utf8) + UInt32(data.count).bigEndianBytes + data guard let data = Algos.Avalanche.sign(data: prefixed, with: _sk) else { return nil } return Signature(data: data) } func signEthereum(message data: Data) -> Signature? { let prefixed = Data("\u{19}Ethereum Signed Message:\n".utf8) + Data(String(data.count, radix: 10).utf8) + data guard let data = Algos.Ethereum.sign(data: prefixed, with: _sk) else { return nil } return Signature(data: data) } func signEthereum(serialized tx: Data) -> Signature? { guard let data = Algos.Ethereum.sign(data: tx, with: _sk) else { return nil } return Signature(data: data) } var privateString: String { "PrivateKey-" + Algos.Base58.cb58(data: _sk) } var privateData: Data { _sk } var publicString: String { Algos.Base58.cb58(data: publicKey) } static func generate() -> KeyPair? { try? Algos.Secp256k1.generateKey().flatMap { try KeyPair(sk: $0.pk, chainCode: $0.cc) } } }
29.625954
118
0.586704
4bb6f1388963cf61f82049d1d32b14700c5e25b8
2,948
// // KRELocationManager.swift // KoraSDK // // Created by Srinivas Vasadi on 20/03/19. // Copyright © 2019 Srinivas Vasadi. All rights reserved. // import UIKit import CoreLocation open class KRELocationManager: NSObject, CLLocationManagerDelegate { var lastKnowAccuracy: CGFloat = 0.0 open var lastKnowRegion: KRERegion? // MARK: - public static let shared = KRELocationManager() public var locationManager: CLLocationManager? // MARK: - override init() { super.init() } public func setupLocationManager() { DispatchQueue.main.async { self.locationManager = CLLocationManager() self.locationManager?.delegate = self self.locationManager?.requestAlwaysAuthorization() } } // MARK: - open func updateLastKnowLocation() { guard let locationManager = locationManager else { return } if lastKnowRegion == nil { lastKnowRegion = KRERegion(location: locationManager.location) } else { lastKnowRegion?.updateRegion(with: locationManager.location) } } func updateMonitoredRegions(forCurrentLocation currentLocation: KRERegion?) { updateLastKnowLocation() } // MARK: - CLLocationManagerDelegate public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { // Location Services Status switch status { case .notDetermined, .restricted, .denied: guard let monitoredRegions = locationManager?.monitoredRegions else { return } for region in monitoredRegions { locationManager?.stopMonitoring(for: region) } case .authorizedAlways: updateMonitoredRegions(forCurrentLocation: lastKnowRegion) default: break } } public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { debugPrint("KRELocationManager did failed update location : \(error)") } } // MARK: - KRERegion open class KRERegion: NSObject { public var latitude: Double = 0.0 public var longitude: Double = 0.0 public var radius: Double = 0.0 public var isOutside = false public var accuracy: CLLocationAccuracy = 0 // MARK: - init?(location: CLLocation?) { super.init() latitude = location?.coordinate.latitude ?? 0.0 longitude = location?.coordinate.longitude ?? 0.0 accuracy = location?.horizontalAccuracy ?? 0.0 radius = accuracy } func updateRegion(with location: CLLocation?) { latitude = location?.coordinate.latitude ?? 0.0 longitude = location?.coordinate.longitude ?? 0.0 accuracy = location?.horizontalAccuracy ?? 0.0 radius = accuracy } }
30.081633
117
0.631954
fb9d6a0c8927143abdf3974ba36df75844cc533f
8,265
// // MBWayComponentTests.swift // AdyenTests // // Created by Mohamed Eldoheiri on 7/31/20. // Copyright © 2020 Adyen. All rights reserved. // @testable import Adyen @testable import AdyenComponents import XCTest class MBWayComponentTests: XCTestCase { lazy var method = MBWayPaymentMethod(type: "test_type", name: "test_name") let payment = Payment(amount: Payment.Amount(value: 2, currencyCode: "EUR"), countryCode: "DE") func testLocalizationWithCustomTableName() { let sut = MBWayComponent(paymentMethod: method) sut.payment = payment sut.localizationParameters = LocalizationParameters(tableName: "AdyenUIHost", keySeparator: nil) XCTAssertEqual(sut.phoneItem?.title, ADYLocalizedString("adyen.phoneNumber.title", sut.localizationParameters)) XCTAssertEqual(sut.phoneItem?.placeholder, ADYLocalizedString("adyen.phoneNumber.placeholder", sut.localizationParameters)) XCTAssertEqual(sut.phoneItem?.validationFailureMessage, ADYLocalizedString("adyen.phoneNumber.invalid", sut.localizationParameters)) XCTAssertNotNil(sut.button.title) XCTAssertEqual(sut.button.title, ADYLocalizedString("adyen.continueTo", sut.localizationParameters, method.name)) XCTAssertTrue(sut.button.title!.contains(method.name)) } func testLocalizationWithCustomKeySeparator() { let sut = MBWayComponent(paymentMethod: method) sut.payment = payment sut.localizationParameters = LocalizationParameters(tableName: "AdyenUIHostCustomSeparator", keySeparator: "_") XCTAssertEqual(sut.phoneItem?.title, ADYLocalizedString("adyen_phoneNumber_title", sut.localizationParameters)) XCTAssertEqual(sut.phoneItem?.placeholder, ADYLocalizedString("adyen_phoneNumber_placeholder", sut.localizationParameters)) XCTAssertEqual(sut.phoneItem?.validationFailureMessage, ADYLocalizedString("adyen_phoneNumber_invalid", sut.localizationParameters)) XCTAssertNotNil(sut.button.title) XCTAssertEqual(sut.button.title, ADYLocalizedString("adyen_continueTo", sut.localizationParameters, method.name)) } func testUIConfiguration() { var style = FormComponentStyle() /// Footer style.mainButtonItem.button.title.color = .white style.mainButtonItem.button.title.backgroundColor = .red style.mainButtonItem.button.title.textAlignment = .center style.mainButtonItem.button.title.font = .systemFont(ofSize: 22) style.mainButtonItem.button.backgroundColor = .red style.mainButtonItem.backgroundColor = .brown /// background color style.backgroundColor = .red /// Text field style.textField.text.color = .red style.textField.text.font = .systemFont(ofSize: 13) style.textField.text.textAlignment = .right style.textField.title.backgroundColor = .blue style.textField.title.color = .yellow style.textField.title.font = .systemFont(ofSize: 20) style.textField.title.textAlignment = .center style.textField.backgroundColor = .red let sut = MBWayComponent(paymentMethod: method, style: style) UIApplication.shared.keyWindow?.rootViewController = sut.viewController let expectation = XCTestExpectation(description: "Dummy Expectation") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) { let phoneNumberView: FormPhoneNumberItemView? = sut.viewController.view.findView(with: "AdyenComponents.MBWayComponent.phoneNumberItem") let phoneNumberViewTitleLabel: UILabel? = sut.viewController.view.findView(with: "AdyenComponents.MBWayComponent.phoneNumberItem.titleLabel") let phoneNumberViewTextField: UITextField? = sut.viewController.view.findView(with: "AdyenComponents.MBWayComponent.phoneNumberItem.textField") let payButtonItemViewButton: UIControl? = sut.viewController.view.findView(with: "AdyenComponents.MBWayComponent.payButtonItem.button") let payButtonItemViewButtonTitle: UILabel? = sut.viewController.view.findView(with: "AdyenComponents.MBWayComponent.payButtonItem.button.titleLabel") /// Test phone number field XCTAssertEqual(phoneNumberView?.backgroundColor, .red) XCTAssertEqual(phoneNumberViewTitleLabel?.textColor, sut.viewController.view.tintColor) XCTAssertEqual(phoneNumberViewTitleLabel?.backgroundColor, .blue) XCTAssertEqual(phoneNumberViewTitleLabel?.textAlignment, .center) XCTAssertEqual(phoneNumberViewTitleLabel?.font, .systemFont(ofSize: 20)) XCTAssertEqual(phoneNumberViewTextField?.backgroundColor, .red) XCTAssertEqual(phoneNumberViewTextField?.textAlignment, .right) XCTAssertEqual(phoneNumberViewTextField?.textColor, .red) XCTAssertEqual(phoneNumberViewTextField?.font, .systemFont(ofSize: 13)) /// Test footer XCTAssertEqual(payButtonItemViewButton?.backgroundColor, .red) XCTAssertEqual(payButtonItemViewButtonTitle?.backgroundColor, .red) XCTAssertEqual(payButtonItemViewButtonTitle?.textAlignment, .center) XCTAssertEqual(payButtonItemViewButtonTitle?.textColor, .white) XCTAssertEqual(payButtonItemViewButtonTitle?.font, .systemFont(ofSize: 22)) expectation.fulfill() } wait(for: [expectation], timeout: 5) } func testSubmitForm() { let sut = MBWayComponent(paymentMethod: method) let delegate = PaymentComponentDelegateMock() sut.delegate = delegate sut.payment = payment let delegateExpectation = expectation(description: "PaymentComponentDelegate must be called when submit button is clicked.") delegate.onDidSubmit = { data, component in XCTAssertTrue(component === sut) XCTAssertTrue(data.paymentMethod is MBWayDetails) let data = data.paymentMethod as! MBWayDetails XCTAssertEqual(data.telephoneNumber, "+3511233456789") sut.stopLoading(withSuccess: true, completion: { delegateExpectation.fulfill() }) XCTAssertEqual(sut.viewController.view.isUserInteractionEnabled, true) XCTAssertEqual(sut.button.showsActivityIndicator, false) } UIApplication.shared.keyWindow?.rootViewController = sut.viewController let dummyExpectation = expectation(description: "Dummy Expectation") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) { let submitButton: UIControl? = sut.viewController.view.findView(with: "AdyenComponents.MBWayComponent.payButtonItem.button") let phoneNumberView: FormPhoneNumberItemView! = sut.viewController.view.findView(with: "AdyenComponents.MBWayComponent.phoneNumberItem") self.populate(textItemView: phoneNumberView, with: "1233456789") submitButton?.sendActions(for: .touchUpInside) dummyExpectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } private func populate<T: FormTextItem, U: FormTextItemView<T>>(textItemView: U, with text: String) { let textView = textItemView.textField textView.text = text textView.sendActions(for: .editingChanged) } func testBigTitle() { let sut = MBWayComponent(paymentMethod: method) UIApplication.shared.keyWindow?.rootViewController = sut.viewController let expectation = XCTestExpectation(description: "Dummy Expectation") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) { XCTAssertNil(sut.viewController.view.findView(with: "AdyenComponents.MBWayComponent.Test name")) XCTAssertEqual(sut.viewController.title, self.method.name) expectation.fulfill() } wait(for: [expectation], timeout: 5) } func testRequiresModalPresentation() { let mbWayPaymentMethod = MBWayPaymentMethod(type: "mbway", name: "Test name") let sut = MBWayComponent(paymentMethod: mbWayPaymentMethod) XCTAssertEqual(sut.requiresModalPresentation, true) } }
48.905325
161
0.717725
4615a2cee428d9d364c269967d5f9342b2c9f99d
40,102
//===--- RangeReplaceableCollection.swift ---------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // A Collection protocol with replaceSubrange. // //===----------------------------------------------------------------------===// /// A type that supports replacement of an arbitrary subrange of elements with /// the elements of another collection. /// /// In most cases, it's best to ignore this protocol and use the /// `RangeReplaceableCollection` protocol instead, because it has a more /// complete interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'RandomAccessCollection' instead") public typealias RangeReplaceableIndexable = RangeReplaceableCollection /// A collection that supports replacement of an arbitrary subrange of elements /// with the elements of another collection. /// /// Range-replaceable collections provide operations that insert and remove /// elements. For example, you can add elements to an array of strings by /// calling any of the inserting or appending operations that the /// `RangeReplaceableCollection` protocol defines. /// /// var bugs = ["Aphid", "Damselfly"] /// bugs.append("Earwig") /// bugs.insert(contentsOf: ["Bumblebee", "Cicada"], at: 1) /// print(bugs) /// // Prints "["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]" /// /// Likewise, `RangeReplaceableCollection` types can remove one or more /// elements using a single operation. /// /// bugs.removeLast() /// bugs.removeSubrange(1...2) /// print(bugs) /// // Prints "["Aphid", "Damselfly"]" /// /// bugs.removeAll() /// print(bugs) /// // Prints "[]" /// /// Lastly, use the eponymous `replaceSubrange(_:with:)` method to replace /// a subrange of elements with the contents of another collection. Here, /// three elements in the middle of an array of integers are replaced by the /// five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// Conforming to the RangeReplaceableCollection Protocol /// ===================================================== /// /// To add `RangeReplaceableCollection` conformance to your custom collection, /// add an empty initializer and the `replaceSubrange(_:with:)` method to your /// custom type. `RangeReplaceableCollection` provides default implementations /// of all its other methods using this initializer and method. For example, /// the `removeSubrange(_:)` method is implemented by calling /// `replaceSubrange(_:with:)` with an empty collection for the `newElements` /// parameter. You can override any of the protocol's required methods to /// provide your own custom implementation. public protocol RangeReplaceableCollection : Collection where SubSequence : RangeReplaceableCollection { // FIXME(ABI): Associated type inference requires this. associatedtype SubSequence //===--- Fundamental Requirements ---------------------------------------===// /// Creates a new, empty collection. init() /// Replaces the specified subrange of elements with the given collection. /// /// This method has the effect of removing the specified range of elements /// from the collection and inserting the new elements at the same location. /// The number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameters: /// - subrange: The subrange of the collection to replace. The bounds of /// the range must be valid indices of the collection. /// - newElements: The new elements to add to the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If the call to `replaceSubrange` simply appends the /// contents of `newElements` to the collection, the complexity is O(*n*), /// where *n* is the length of `newElements`. mutating func replaceSubrange<C>( _ subrange: Range<Index>, with newElements: C ) where C : Collection, C.Element == Element /// Prepares the collection to store the specified number of elements, when /// doing so is appropriate for the underlying type. /// /// If you are adding a known number of elements to a collection, use this /// method to avoid multiple reallocations. A type that conforms to /// `RangeReplaceableCollection` can choose how to respond when this method /// is called. Depending on the type, it may make sense to allocate more or /// less storage than requested, or to take no action at all. /// /// - Parameter n: The requested number of elements to store. mutating func reserveCapacity(_ n: Int) //===--- Derivable Requirements -----------------------------------------===// /// Creates a new collection containing the specified number of a single, /// repeated value. /// /// The following example creates an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. init(repeating repeatedValue: Element, count: Int) /// Creates a new instance of a collection containing the elements of a /// sequence. /// /// - Parameter elements: The sequence of elements for the new collection. /// `elements` must be finite. init<S : Sequence>(_ elements: S) where S.Element == Element /// Adds an element to the end of the collection. /// /// If the collection does not have sufficient capacity for another element, /// additional storage is allocated before appending `newElement`. The /// following example adds a new number to an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// - Parameter newElement: The element to append to the collection. /// /// - Complexity: O(1) on average, over many additions to the same /// collection. mutating func append(_ newElement: Element) /// Adds the elements of a sequence or collection to the end of this /// collection. /// /// The collection being appended to allocates any additional necessary /// storage to hold the new elements. /// /// The following example appends the elements of a `Range<Int>` instance to /// an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the collection. /// /// - Complexity: O(*n*), where *n* is the length of the resulting /// collection. // FIXME(ABI)#166 (Evolution): Consider replacing .append(contentsOf) with += // suggestion in SE-91 mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Element /// Inserts a new element into the collection at the specified position. /// /// The new element is inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as /// the `index` parameter, the new element is appended to the /// collection. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElement: The new element to insert into the collection. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index into the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func insert(_ newElement: Element, at i: Index) /// Inserts the elements of a sequence into the collection at the specified /// position. /// /// The new elements are inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as the /// `index` parameter, the new elements are appended to the collection. /// /// Here's an example of inserting a range of integers into an array of the /// same type: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(contentsOf: 100...103, at: 3) /// print(numbers) /// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElements: The new elements to insert into the collection. /// - Parameter i: The position at which to insert the new elements. `index` /// must be a valid index of the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If `i` is equal to the collection's `endIndex` /// property, the complexity is O(*n*), where *n* is the length of /// `newElements`. mutating func insert<S : Collection>(contentsOf newElements: S, at i: Index) where S.Element == Element /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved to close the /// gap. This example removes the middle element from an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.2, 1.5, 1.2, 1.6]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter i: The position of the element to remove. `index` must be /// a valid index of the collection that is not equal to the collection's /// end index. /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @discardableResult mutating func remove(at i: Index) -> Element /// Removes the specified subrange of elements from the collection. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeSubrange(1...3) /// print(bugs) /// // Prints "["Aphid", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter bounds: The subrange of the collection to remove. The bounds /// of the range must be valid indices of the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeSubrange(_ bounds: Range<Index>) /// Customization point for `removeLast()`. Implement this function if you /// want to replace the default implementation. /// /// - Returns: A non-nil value if the operation was performed. mutating func _customRemoveLast() -> Element? /// Customization point for `removeLast(_:)`. Implement this function if you /// want to replace the default implementation. /// /// - Returns: `true` if the operation was performed. mutating func _customRemoveLast(_ n: Int) -> Bool /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst() /// print(bugs) /// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @discardableResult mutating func removeFirst() -> Element /// Removes the specified number of elements from the beginning of the /// collection. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst(3) /// print(bugs) /// // Prints "["Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeFirst(_ n: Int) /// Removes all elements from the collection. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter keepCapacity: Pass `true` to request that the collection /// avoid releasing its storage. Retaining the collection's storage can /// be a useful optimization when you're planning to grow the collection /// again. The default value is `false`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeAll(keepingCapacity keepCapacity: Bool /*= false*/) // FIXME(ABI): Associated type inference requires this. subscript(bounds: Index) -> Element { get } // FIXME(ABI): Associated type inference requires this. subscript(bounds: Range<Index>) -> SubSequence { get } } //===----------------------------------------------------------------------===// // Default implementations for RangeReplaceableCollection //===----------------------------------------------------------------------===// extension RangeReplaceableCollection { /// Creates a new collection containing the specified number of a single, /// repeated value. /// /// Here's an example of creating an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. @_inlineable public init(repeating repeatedValue: Element, count: Int) { self.init() if count != 0 { let elements = Repeated(_repeating: repeatedValue, count: count) append(contentsOf: elements) } } /// Creates a new instance of a collection containing the elements of a /// sequence. /// /// - Parameter elements: The sequence of elements for the new collection. @_inlineable public init<S : Sequence>(_ elements: S) where S.Element == Element { self.init() append(contentsOf: elements) } /// Adds an element to the end of the collection. /// /// If the collection does not have sufficient capacity for another element, /// additional storage is allocated before appending `newElement`. The /// following example adds a new number to an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// - Parameter newElement: The element to append to the collection. /// /// - Complexity: O(1) on average, over many additions to the same /// collection. @_inlineable public mutating func append(_ newElement: Element) { insert(newElement, at: endIndex) } /// Adds the elements of a sequence or collection to the end of this /// collection. /// /// The collection being appended to allocates any additional necessary /// storage to hold the new elements. /// /// The following example appends the elements of a `Range<Int>` instance to /// an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the collection. /// /// - Complexity: O(*n*), where *n* is the length of the resulting /// collection. @_inlineable public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Element { let approximateCapacity = self.count + numericCast(newElements.underestimatedCount) self.reserveCapacity(approximateCapacity) for element in newElements { append(element) } } /// Inserts a new element into the collection at the specified position. /// /// The new element is inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as /// the `index` parameter, the new element is appended to the /// collection. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElement: The new element to insert into the collection. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index into the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public mutating func insert( _ newElement: Element, at i: Index ) { replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// Inserts the elements of a sequence into the collection at the specified /// position. /// /// The new elements are inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as the /// `index` parameter, the new elements are appended to the collection. /// /// Here's an example of inserting a range of integers into an array of the /// same type: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(contentsOf: 100...103, at: 3) /// print(numbers) /// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElements: The new elements to insert into the collection. /// - Parameter i: The position at which to insert the new elements. `index` /// must be a valid index of the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If `i` is equal to the collection's `endIndex` /// property, the complexity is O(*n*), where *n* is the length of /// `newElements`. @_inlineable public mutating func insert<C : Collection>( contentsOf newElements: C, at i: Index ) where C.Element == Element { replaceSubrange(i..<i, with: newElements) } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved to close the /// gap. This example removes the middle element from an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.2, 1.5, 1.2, 1.6]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter position: The position of the element to remove. `position` must be /// a valid index of the collection that is not equal to the collection's /// end index. /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable @discardableResult public mutating func remove(at position: Index) -> Element { _precondition(!isEmpty, "Can't remove from an empty collection") let result: Element = self[position] replaceSubrange(position..<index(after: position), with: EmptyCollection()) return result } /// Removes the elements in the specified subrange from the collection. /// /// All the elements following the specified position are moved to close the /// gap. This example removes two elements from the middle of an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5] /// measurements.removeSubrange(1..<4) /// print(measurements) /// // Prints "[1.2, 1.5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter bounds: The range of the collection to be removed. The /// bounds of the range must be valid indices of the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public mutating func removeSubrange(_ bounds: Range<Index>) { replaceSubrange(bounds, with: EmptyCollection()) } /// Removes the specified number of elements from the beginning of the /// collection. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst(3) /// print(bugs) /// // Prints "["Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public mutating func removeFirst(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it has") let end = index(startIndex, offsetBy: numericCast(n)) removeSubrange(startIndex..<end) } /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst() /// print(bugs) /// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable @discardableResult public mutating func removeFirst() -> Element { _precondition(!isEmpty, "Can't remove first element from an empty collection") let firstElement = first! removeFirst(1) return firstElement } /// Removes all elements from the collection. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter keepCapacity: Pass `true` to request that the collection /// avoid releasing its storage. Retaining the collection's storage can /// be a useful optimization when you're planning to grow the collection /// again. The default value is `false`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { self = Self() } else { replaceSubrange(startIndex..<endIndex, with: EmptyCollection()) } } /// Prepares the collection to store the specified number of elements, when /// doing so is appropriate for the underlying type. /// /// If you will be adding a known number of elements to a collection, use /// this method to avoid multiple reallocations. A type that conforms to /// `RangeReplaceableCollection` can choose how to respond when this method /// is called. Depending on the type, it may make sense to allocate more or /// less storage than requested or to take no action at all. /// /// - Parameter n: The requested number of elements to store. @_inlineable public mutating func reserveCapacity(_ n: Int) {} } extension RangeReplaceableCollection where SubSequence == Self { /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The first element of the collection. /// /// - Complexity: O(1) /// - Precondition: `!self.isEmpty`. @_inlineable @discardableResult public mutating func removeFirst() -> Element { _precondition(!isEmpty, "Can't remove items from an empty collection") let element = first! self = self[index(after: startIndex)..<endIndex] return element } /// Removes the specified number of elements from the beginning of the /// collection. /// /// Attempting to remove more elements than exist in the collection /// triggers a runtime error. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(1) @_inlineable public mutating func removeFirst(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") self = self[index(startIndex, offsetBy: numericCast(n))..<endIndex] } } extension RangeReplaceableCollection { /// Replaces the specified subrange of elements with the given collection. /// /// This method has the effect of removing the specified range of elements /// from the collection and inserting the new elements at the same location. /// The number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameters: /// - subrange: The subrange of the collection to replace. The bounds of /// the range must be valid indices of the collection. /// - newElements: The new elements to add to the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If the call to `replaceSubrange` simply appends the /// contents of `newElements` to the collection, the complexity is O(*n*), /// where *n* is the length of `newElements`. @_inlineable public mutating func replaceSubrange<C: Collection, R: RangeExpression>( _ subrange: R, with newElements: C ) where C.Element == Element, R.Bound == Index { self.replaceSubrange(subrange.relative(to: self), with: newElements) } /// Removes the elements in the specified subrange from the collection. /// /// All the elements following the specified position are moved to close the /// gap. This example removes two elements from the middle of an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5] /// measurements.removeSubrange(1..<4) /// print(measurements) /// // Prints "[1.2, 1.5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter bounds: The range of the collection to be removed. The /// bounds of the range must be valid indices of the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public mutating func removeSubrange<R: RangeExpression>( _ bounds: R ) where R.Bound == Index { removeSubrange(bounds.relative(to: self)) } } extension RangeReplaceableCollection { @_inlineable public mutating func _customRemoveLast() -> Element? { return nil } @_inlineable public mutating func _customRemoveLast(_ n: Int) -> Bool { return false } } extension RangeReplaceableCollection where Self : BidirectionalCollection, SubSequence == Self { @_inlineable public mutating func _customRemoveLast() -> Element? { let element = last! self = self[startIndex..<index(before: endIndex)] return element } @_inlineable public mutating func _customRemoveLast(_ n: Int) -> Bool { self = self[startIndex..<index(endIndex, offsetBy: numericCast(-n))] return true } } extension RangeReplaceableCollection where Self : BidirectionalCollection { /// Removes and returns the last element of the collection. /// /// The collection must not be empty. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The last element of the collection. /// /// - Complexity: O(1) @_inlineable @discardableResult public mutating func removeLast() -> Element { _precondition(!isEmpty, "Can't remove last element from an empty collection") if let result = _customRemoveLast() { return result } return remove(at: index(before: endIndex)) } /// Removes the specified number of elements from the end of the /// collection. /// /// Attempting to remove more elements than exist in the collection /// triggers a runtime error. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the specified number of elements. @_inlineable public mutating func removeLast(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") if _customRemoveLast(n) { return } let end = endIndex removeSubrange(index(end, offsetBy: numericCast(-n))..<end) } } // FIXME: swift-3-indexing-model: file a bug for the compiler? /// Ambiguity breakers. extension RangeReplaceableCollection where Self : BidirectionalCollection, SubSequence == Self { /// Removes and returns the last element of the collection. /// /// The collection must not be empty. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The last element of the collection. /// /// - Complexity: O(1) @_inlineable @discardableResult public mutating func removeLast() -> Element { _precondition(!isEmpty, "Can't remove last element from an empty collection") if let result = _customRemoveLast() { return result } return remove(at: index(before: endIndex)) } /// Removes the specified number of elements from the end of the /// collection. /// /// Attempting to remove more elements than exist in the collection /// triggers a runtime error. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the specified number of elements. @_inlineable public mutating func removeLast(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") if _customRemoveLast(n) { return } let end = endIndex removeSubrange(index(end, offsetBy: numericCast(-n))..<end) } } extension RangeReplaceableCollection { /// Creates a new collection by concatenating the elements of a collection and /// a sequence. /// /// The two arguments must have the same `Element` type. For example, you can /// concatenate the elements of an integer array and a `Range<Int>` instance. /// /// let numbers = [1, 2, 3, 4] /// let moreNumbers = numbers + 5...10 /// print(moreNumbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" /// /// The resulting collection has the type of the argument on the left-hand /// side. In the example above, `moreNumbers` has the same type as `numbers`, /// which is `[Int]`. /// /// - Parameters: /// - lhs: A range-replaceable collection. /// - rhs: A collection or finite sequence. @_inlineable public static func + < Other : Sequence >(lhs: Self, rhs: Other) -> Self where Element == Other.Element { var lhs = lhs // FIXME: what if lhs is a reference type? This will mutate it. lhs.append(contentsOf: rhs) return lhs } /// Creates a new collection by concatenating the elements of a sequence and a /// collection. /// /// The two arguments must have the same `Element` type. For example, you can /// concatenate the elements of a `Range<Int>` instance and an integer array. /// /// let numbers = [7, 8, 9, 10] /// let moreNumbers = 1...6 + numbers /// print(moreNumbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" /// /// The resulting collection has the type of argument on the right-hand side. /// In the example above, `moreNumbers` has the same type as `numbers`, which /// is `[Int]`. /// /// - Parameters: /// - lhs: A collection or finite sequence. /// - rhs: A range-replaceable collection. @_inlineable public static func + < Other : Sequence >(lhs: Other, rhs: Self) -> Self where Element == Other.Element { var result = Self() result.reserveCapacity(rhs.count + numericCast(lhs.underestimatedCount)) result.append(contentsOf: lhs) result.append(contentsOf: rhs) return result } /// Appends the elements of a sequence to a range-replaceable collection. /// /// Use this operator to append the elements of a sequence to the end of /// range-replaceable collection with same `Element` type. This example appends /// the elements of a `Range<Int>` instance to an array of integers. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers += 10...15 /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameters: /// - lhs: The array to append to. /// - rhs: A collection or finite sequence. /// /// - Complexity: O(*n*), where *n* is the length of the resulting array. @_inlineable public static func += < Other : Sequence >(lhs: inout Self, rhs: Other) where Element == Other.Element { lhs.append(contentsOf: rhs) } /// Creates a new collection by concatenating the elements of two collections. /// /// The two arguments must have the same `Element` type. For example, you can /// concatenate the elements of two integer arrays. /// /// let lowerNumbers = [1, 2, 3, 4] /// let higherNumbers: ContiguousArray = [5, 6, 7, 8, 9, 10] /// let allNumbers = lowerNumbers + higherNumbers /// print(allNumbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" /// /// The resulting collection has the type of the argument on the left-hand /// side. In the example above, `moreNumbers` has the same type as `numbers`, /// which is `[Int]`. /// /// - Parameters: /// - lhs: A range-replaceable collection. /// - rhs: Another range-replaceable collection. @_inlineable public static func + < Other : RangeReplaceableCollection >(lhs: Self, rhs: Other) -> Self where Element == Other.Element { var lhs = lhs // FIXME: what if lhs is a reference type? This will mutate it. lhs.append(contentsOf: rhs) return lhs } } extension RangeReplaceableCollection { /// Returns a new collection of the same type containing, in order, the /// elements of the original collection that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. @_inlineable @available(swift, introduced: 4.0) public func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> Self { return try Self(self.lazy.filter(isIncluded)) } }
38.411877
115
0.65109
64fc3e05d8d3ee780cc08a7398620efd22ec74d1
3,222
// // ExternalModuleTypesStubbableTests.swift // MockingbirdTests // // Created by Andrew Chang on 9/15/19. // import Foundation import Mockingbird import MockingbirdModuleTestsHost @testable import MockingbirdTestsHost // MARK: - Stubbable declarations private protocol StubbableLocalPublicExternalProtocol { func getVariable() -> Mockable<PropertyGetterDeclaration, () -> Bool, Bool> func method() -> Mockable<FunctionDeclaration, () -> Void, Void> } extension LocalPublicExternalProtocolMock: StubbableLocalPublicExternalProtocol {} private protocol StubbableSubclassingExternalClassWithInheritedIntializer { func getInternalVariable() -> Mockable<PropertyGetterDeclaration, () -> Bool, Bool> func internalMethod() -> Mockable<FunctionDeclaration, () -> Void, Void> func getOpenVariable() -> Mockable<PropertyGetterDeclaration, () -> Bool, Bool> func openMethod() -> Mockable<FunctionDeclaration, () -> Void, Void> } extension SubclassingExternalClassWithInheritedIntializerMock: StubbableSubclassingExternalClassWithInheritedIntializer {} extension SubclassingExternalSubclassWithInheritedInitializerMock: StubbableSubclassingExternalClassWithInheritedIntializer {} extension SubclassingExternalClassWithDesignatedIntializerMock: StubbableSubclassingExternalClassWithInheritedIntializer {} extension SubclassingExternalSubclassWithDesignatedInitializerMock: StubbableSubclassingExternalClassWithInheritedIntializer {} private protocol StubbableConformingInitializableOpenClassConstrainedProtocol { func getOpenVariable() -> Mockable<PropertyGetterDeclaration, () -> Bool, Bool> func setOpenVariable(_ newValue: @autoclosure () -> Bool) -> Mockable<PropertySetterDeclaration, (Bool) -> Void, Void> } extension ConformingInitializableOpenClassConstrainedProtocolMock: StubbableConformingInitializableOpenClassConstrainedProtocol {} private protocol StubbableConformingUninitializableOpenClassConstrainedProtocol { func getOpenVariable() -> Mockable<PropertyGetterDeclaration, () -> Bool, Bool> func setOpenVariable(_ newValue: @autoclosure () -> Bool) -> Mockable<PropertySetterDeclaration, (Bool) -> Void, Void> } extension ConformingUninitializableOpenClassConstrainedProtocolMock: StubbableConformingUninitializableOpenClassConstrainedProtocol {} private protocol StubbableImplicitlyImportedExternalObjectiveCType { func getVariable() -> Mockable<PropertyGetterDeclaration, () -> Bool, Bool> } extension ImplicitlyImportedExternalObjectiveCTypeMock: StubbableImplicitlyImportedExternalObjectiveCType {} // MARK: - Non-stubbable declarations extension ConformingInitializableOpenClassConstrainedProtocolMock { func getPublicVariable() -> Mockable<PropertyGetterDeclaration, () -> Bool, Bool> { fatalError() } func setPublicVariable(_ newValue: @autoclosure () -> Bool) -> Mockable<PropertySetterDeclaration, (Bool) -> Void, Void> { fatalError() } } extension ConformingUninitializableOpenClassConstrainedProtocolMock { func getPublicVariable() -> Mockable<PropertyGetterDeclaration, () -> Bool, Bool> { fatalError() } func setPublicVariable(_ newValue: @autoclosure () -> Bool) -> Mockable<PropertySetterDeclaration, (Bool) -> Void, Void> { fatalError() } }
44.75
100
0.815642
d7db44d22d54e0187a556913bc72afcb88d7b8b2
11,867
// // OPFParser.swift // r2-streamer-swift // // Created by Alexandre Camilleri on 2/21/17. // // Copyright 2018 Readium Foundation. All rights reserved. // Use of this source code is governed by a BSD-style license which is detailed // in the LICENSE file present in the project repository where this source code is maintained. // import Fuzi import R2Shared // http://www.idpf.org/epub/30/spec/epub30-publications.html#title-type // the six basic values of the "title-type" property specified by EPUB 3: public enum EPUBTitleType: String { case main case subtitle case short case collection case edition case expanded } public enum OPFParserError: Error { /// The Epub have no title. Title is mandatory. case missingPublicationTitle /// Smile resource couldn't be parsed. case invalidSmilResource } /// EpubParser support class, able to parse the OPF package document. /// OPF: Open Packaging Format. final class OPFParser: Loggable { /// Relative path to the OPF in the EPUB container private let basePath: String /// DOM representation of the OPF file. private let document: Fuzi.XMLDocument /// EPUB title which will be used as a fallback if we can't parse one. Title is mandatory in /// RWPM. private let fallbackTitle: String /// iBooks Display Options XML file to use as a fallback for metadata. /// See https://github.com/readium/architecture/blob/master/streamer/parser/metadata.md#epub-2x-9 private let displayOptions: Fuzi.XMLDocument? /// List of metadata declared in the package. private let metas: OPFMetaList /// Encryption information, indexed by resource HREF. private let encryptions: [String: Encryption] init(basePath: String, data: Data, fallbackTitle: String, displayOptionsData: Data? = nil, encryptions: [String: Encryption]) throws { self.basePath = basePath self.fallbackTitle = fallbackTitle self.document = try Fuzi.XMLDocument(data: data) self.document.definePrefix("opf", forNamespace: "http://www.idpf.org/2007/opf") self.displayOptions = (displayOptionsData.map { try? Fuzi.XMLDocument(data: $0) }) ?? nil self.metas = OPFMetaList(document: self.document) self.encryptions = encryptions } convenience init(fetcher: Fetcher, opfHREF: String, fallbackTitle: String, encryptions: [String: Encryption] = [:]) throws { try self.init( basePath: opfHREF, data: try fetcher.readData(at: opfHREF), fallbackTitle: fallbackTitle, displayOptionsData: { let iBooksPath = "/META-INF/com.apple.ibooks.display-options.xml" let koboPath = "/META-INF/com.kobobooks.display-options.xml" return (try? fetcher.readData(at: iBooksPath)) ?? (try? fetcher.readData(at: koboPath)) ?? nil }(), encryptions: encryptions ) } /// Parse the OPF file of the EPUB container and return a `Publication`. /// It also complete the informations stored in the container. func parsePublication() throws -> (version: String, metadata: Metadata, readingOrder: [Link], resources: [Link]) { let links = parseLinks() let (resources, readingOrder) = splitResourcesAndReadingOrderLinks(links) let metadata = EPUBMetadataParser(document: document, fallbackTitle: fallbackTitle, displayOptions: displayOptions, metas: metas) return ( version: parseEPUBVersion(), metadata: try metadata.parse(), readingOrder: readingOrder, resources: resources ) } /// Retrieves the EPUB version from the package.opf XML document. private func parseEPUBVersion() -> String { // Default EPUB Version value, used when no version hes been specified (see OPF_2.0.1_draft 1.3.2). let defaultVersion = "1.2" return document.firstChild(xpath: "/opf:package")?.attr("version") ?? defaultVersion } /// Parses XML elements of the <Manifest> in the package.opf file as a list of `Link`. private func parseLinks() -> [Link] { // Read meta to see if any Link is referenced as the Cover. let coverId = metas["cover"].first?.content let manifestItems = document.xpath("/opf:package/opf:manifest/opf:item") // Spine items indexed by IDRef let spineItemsKVs = document.xpath("/opf:package/opf:spine/opf:itemref") .compactMap { item in item.attr("idref").map { ($0, item) } } let spineItems = Dictionary(spineItemsKVs, uniquingKeysWith: { first, _ in first }) return manifestItems.compactMap { manifestItem in // Must have an ID. guard let id = manifestItem.attr("id") else { log(.warning, "Manifest item MUST have an id, item ignored.") return nil } let isCover = (id == coverId) guard let link = makeLink(manifestItem: manifestItem, spineItem: spineItems[id], isCover: isCover) else { log(.warning, "Can't parse link with ID \(id)") return nil } return link } } /// Parses XML elements of the <spine> in the package.opf file. /// They are only composed of an `idref` referencing one of the previously parsed resource (XML: idref -> id). /// /// - Parameter manifestLinks: The `Link` parsed in the manifest items. /// - Returns: The `Link` in `resources` and in `readingOrder`, taken from the `manifestLinks`. private func splitResourcesAndReadingOrderLinks(_ manifestLinks: [Link]) -> (resources: [Link], readingOrder: [Link]) { var resources = manifestLinks var readingOrder: [Link] = [] let spineItems = document.xpath("/opf:package/opf:spine/opf:itemref") for item in spineItems { // Find the `Link` that `idref` is referencing to from the `manifestLinks`. guard let idref = item.attr("idref"), let index = resources.firstIndex(where: { $0.properties["id"] as? String == idref }), // Only linear items are added to the readingOrder. item.attr("linear")?.lowercased() != "no" else { continue } readingOrder.append(resources[index]) // `resources` should only contain the links that are not already in `readingOrder`. resources.remove(at: index) } return (resources, readingOrder) } private func makeLink(manifestItem: Fuzi.XMLElement, spineItem: Fuzi.XMLElement?, isCover: Bool) -> Link? { guard var href = manifestItem.attr("href")?.removingPercentEncoding else { return nil } href = HREF(href, relativeTo: basePath).string // Merges the string properties found in the manifest and spine items. let stringProperties = "\(manifestItem.attr("properties") ?? "") \(spineItem?.attr("properties") ?? "")" .components(separatedBy: .whitespaces) .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } var rels: [LinkRelation] = [] if stringProperties.contains("nav") { rels.append(.contents) } if isCover || stringProperties.contains("cover-image") { rels.append(.cover) } var properties = parseStringProperties(stringProperties) if let encryption = encryptions[href]?.json, !encryption.isEmpty { properties["encrypted"] = encryption } let type = manifestItem.attr("media-type") var duration: Double? if let id = manifestItem.attr("id") { properties["id"] = id // If the link references a SMIL resource, retrieves and fills its duration. if MediaType.smil.matches(type), let durationMeta = metas["duration", in: .media, refining: id].first { duration = Double(SMILParser.smilTimeToSeconds(durationMeta.content)) } } return Link( href: href, type: type, rels: rels, properties: Properties(properties), duration: duration ) } /// Parse string properties into an `otherProperties` dictionary. private func parseStringProperties(_ properties: [String]) -> [String: Any] { var contains: [String] = [] var layout: EPUBLayout? var orientation: Presentation.Orientation? var overflow: Presentation.Overflow? var page: Presentation.Page? var spread: Presentation.Spread? for property in properties { switch property { // Contains case "scripted": contains.append("js") case "mathml": contains.append("mathml") case "onix-record": contains.append("onix") case "svg": contains.append("svg") case "xmp-record": contains.append("xmp") case "remote-resources": contains.append("remote-resources") // Page case "page-spread-left": page = .left case "page-spread-right": page = .right case "page-spread-center", "rendition:page-spread-center": page = .center // Spread case "rendition:spread-none", "rendition:spread-auto": // If we don't qualify `.none` here it sets it to `nil`. spread = Presentation.Spread.none case "rendition:spread-landscape": spread = .landscape case "rendition:spread-portrait": // `portrait` is deprecated and should fallback to `both`. // See. https://readium.org/architecture/streamer/parser/metadata#epub-3x-11 spread = .both case "rendition:spread-both": spread = .both // Layout case "rendition:layout-reflowable": layout = .reflowable case "rendition:layout-pre-paginated": layout = .fixed // Orientation case "rendition:orientation-auto": orientation = .auto case "rendition:orientation-landscape": orientation = .landscape case "rendition:orientation-portrait": orientation = .portrait // Rendition case "rendition:flow-auto": overflow = .auto case "rendition:flow-paginated": overflow = .paginated case "rendition:flow-scrolled-continuous", "rendition:flow-scrolled-doc": overflow = .scrolled default: continue } } var otherProperties: [String: Any] = [:] if !contains.isEmpty { otherProperties["contains"] = contains } if let layout = layout { otherProperties["layout"] = layout.rawValue } if let orientation = orientation { otherProperties["orientation"] = orientation.rawValue } if let overflow = overflow { otherProperties["overflow"] = overflow.rawValue } if let page = page { otherProperties["page"] = page.rawValue } if let spread = spread { otherProperties["spread"] = spread.rawValue } return otherProperties } }
38.908197
138
0.589871
33b0a34efe7f54a1edd946b13290cf8e729e264c
6,454
// //===----------------------------------------------------------------------===// // // ScreenPlacer+Abstract.swift // // Created by Trevor Beasty on 6/12/19. // // // This source file is part of the Lasso open source project // // https://github.com/ww-tech/lasso // // Copyright © 2019-2020 WW International, Inc. // //===----------------------------------------------------------------------===// // import UIKit // Embodiment of the supported ScreenPlacer structures. Clients can call these utilities to make custom ScreenPlacers. // B/c the init on ScreenPlacer is not publicly exposed, these utilities represent the only paths // through which clients can create custom ScreenPlacers. // MARK: - Instance Placement /// Place some UIViewController relative to some Base artifact. /// /// Choosing the appropriate NextContext is up to the discretion of the implementer. Intuitively, the NextContext /// should reflect some artifact which allows placement of some 'next controller' in a position 'immediately tangent' /// to the originally placed controller. By following this rule, one can place a sequence of screens in a reasonable way. /// /// - Parameters: /// - base: any object into which the controller can be placed /// - place: a closure which executes the placement of the controller relative to the base /// - Returns: the logical 'next' screen context public func makePlacer<Base: AnyObject, NextContext: UIViewController>(base: Base, place: @escaping (Base, UIViewController) -> NextContext) -> ScreenPlacer<NextContext> { return ScreenPlacer<NextContext> { toPlace in return place(base, toPlace) } } // MARK: - Embedding // // ScreenPlacers are composable with respect to embeddings - any placer instance can be embedded. To embed is simply to // to say "you're actually going place this container controller, and I'm going to place controller(s) in that container". // All embeddings are deferred - the container is not placed until all requisite children of that container are placed. // Embedding placers are required (by definition) to return the container as the PlacedContext. This is intuitively // pleasing - the next logical target for placement following placement into a container is some other placement into that container. // In this way, the container is a sort of persistent context with respect to embedding placers. /// Make a ScreenPlacer which places a child controller into a container. /// /// - Parameters: /// - embedder: the container /// - place: a closure which executes the placement of the child into the container /// - onDidPlaceEmbedded: a closure to be executed immediately following placement of the child into the container /// - Returns: a ScreenPlacer which places the child into the container public func makeEmbeddingPlacer<Embedder: UIViewController>(into embedder: Embedder, place: @escaping (Embedder, UIViewController) -> Void, onDidPlaceEmbedded: @escaping () -> Void = { }) -> ScreenPlacer<Embedder> { return ScreenPlacer<Embedder> { toPlace in place(embedder, toPlace) onDidPlaceEmbedded() return embedder } } /// Make many ScreenPlacers which each place a child controller into the embedding container. /// /// Placement of the many children into the container is deferred until all children have been placed. /// Failure to place all children will result in the container never being placed. /// /// - Parameters: /// - embedder: the container /// - count: the number of children which need to be placed into the container /// - place: a closure which executes the placement of the many children into the container /// - onDidPlaceEmbedded: a closure to be executed immediately following placement of the many children into the container /// - Returns: many ScreenPlacers which each place a child into the container public func makeEmbeddingPlacers<Embedder: UIViewController>(into embedder: Embedder, count: Int, place: @escaping (Embedder, [UIViewController]) -> Void, onDidPlaceEmbedded: @escaping () -> Void = { }) -> [ScreenPlacer<Embedder>] { var buffer = [UIViewController?](repeating: nil, count: count) { didSet { let embedded = buffer.compactMap({ $0 }) guard embedded.count == count else { return } place(embedder, embedded) onDidPlaceEmbedded() } } return (0..<count).map({ i in return ScreenPlacer<Embedder> { toPlace in buffer[i] = toPlace return embedder } }) } extension ScreenPlacer { /// Compose a singular embedding into an existing placer. /// /// - Parameters: /// - embedder: the container /// - place: a closure which executes the placement of the child into the container /// - Returns: a ScreenPlacer which places the child into the container public func withEmbedding<Embedder: UIViewController>(into embedder: Embedder, place: @escaping (Embedder, UIViewController) -> Void) -> ScreenPlacer<Embedder> { return makeEmbeddingPlacer(into: embedder, place: place) { self.place(embedder) } } /// Compose a plural embedding into an existing placer. /// /// - Parameters: /// - embedder: the container /// - count: the number of children which need to be placed into the container /// - place: a closure which executes the placement of the many children into the container /// - Returns: many ScreenPlacers which each place a child into the container public func withEmbedding<Embedder: UIViewController>(into embedder: Embedder, count: Int, place: @escaping (Embedder, [UIViewController]) -> Void) -> [ScreenPlacer<Embedder>] { return makeEmbeddingPlacers(into: embedder, count: count, place: place) { self.place(embedder) } } }
47.455882
159
0.629687
1ab4991e9f36816630a2c03bf2cd4727c8c2e677
3,559
// // PeselValidator.swift // FormsValidators // // Created by Konrad on 4/1/20. // Copyright © 2020 Limbo. All rights reserved. // import Foundation // MARK: PeselValidator public class PeselValidator: Validator { override public init(isRequired: Bool = true) { super.init(isRequired: isRequired) self.dependencies = [NotEmptyValidator(isRequired: isRequired)] } override public func validate(_ value: Any?) -> ValidationResult { let value: String = value as? String ?? "" if let result = self.validateDependencies(value) { return result } guard self.shouldValidate(value) else { return ValidationResult() } if let charactersResult = self.validateCharacters(pesel: value) { return charactersResult } if let lengthResult = self.validateLength(pesel: value) { return lengthResult } if let dateResult = self.validateDate(pesel: value) { return dateResult } if let checkSumResult = self.validateCheckSum(pesel: value) { return checkSumResult } return ValidationResult() } private func validateCharacters(pesel: String) -> ValidationResult? { let regex: String = "^[0-9]+$" guard NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: pesel) else { return ValidationResult(error: .peselError) } return nil } private func validateLength(pesel: String) -> ValidationResult? { switch pesel.count { case ..<11: return ValidationResult(error: .peselShortError) case 12...: return ValidationResult(error: .peselLongError) default: return nil } } private func validateDate(pesel: String) -> ValidationResult? { guard let year: Int = Int(pesel[2..<4]), let month: Int = Int(pesel[2..<4]), let day: Int = Int(pesel[4..<6]) else { return ValidationResult(error: .peselError) } var date: (day: Int, month: Int, year: Int) = (0, 0, 0) switch month { case 1...12: date = (day, month, 1_900 + year) case 21...32: date = (day, month - 20, 2_000 + year) case 41...52: date = (day, month - 40, 2_100 + year) case 61...72: date = (day, month - 60, 2_200 + year) case 81...92: date = (day, month - 80, 1_800 + year) default: break } let components = DateComponents( year: date.year, month: date.month, day: date.day) guard let calendarDate: Date = Calendar(identifier: .gregorian).date(from: components), calendarDate.timeIntervalSinceNow < 0 else { return ValidationResult(error: .peselError) } return nil } private func validateCheckSum(pesel: String) -> ValidationResult? { guard let crc: Int = Int(pesel[10]) else { return ValidationResult(error: .peselError) } var controlNumber: Int = 0 let weights: [Int] = [9, 7, 3, 1, 9, 7, 3, 1, 9, 7] for i in 0..<pesel.count - 1 { guard let value: Int = Int(pesel[i]) else { return ValidationResult(error: .peselError) } controlNumber += weights[i] * value } controlNumber = controlNumber % 10 guard crc == controlNumber else { return ValidationResult(error: .peselError) } return nil } }
34.892157
95
0.576004
14b3fe8aaa8a7bb402756cc5f1c920c734420ac6
4,674
// // ViewController.swift // ChatMessage // // Created by Marcos Felipe Souza on 26/08/2018. // Copyright © 2018 Marcos. All rights reserved. // import UIKit class ChatMessageViewController: UITableViewController { fileprivate let cellIdentifier = "cellIdentifier" let messages: [ChatMessageModel] = [ ChatMessageModel(date: Date(stringDate: "28/09/2018"), chat: [ChatModel(message: "Olá , minha primeira mensagem", isComming: true), ChatModel(message: "Está aqui é minha primeira mensagem um pouco maior", isComming: true)]), ChatMessageModel(date: Date(stringDate: "29/09/2018"), chat: [ChatModel(message: "Agora está mensagem eu vou mensagear um outra menssagem para que estore as margens,Agora está mensagem eu vou mensagear um outra menssagem para que estore as margens,Agora está mensagem eu vou mensagear um outra menssagem para que estore as margens,Agora está mensagem eu vou mensagear um outra menssagem para que estore as margens", isComming: false), ChatModel(message: "Okay, Vlw!", isComming: true), ChatModel(message: "Essa eh pra ir a UK!", isComming: false)]), ChatMessageModel(date: Date(stringDate: "30/09/2018"), chat: [ ChatModel(message: "Vai sim !", isComming: true), ChatModel(message: "So ter fé", isComming: true), ChatModel(message: "kkkkk... Vlw!", isComming: false) ]) ] override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() setupTableView() setupConstraints() } func setupNavigationBar() { //Big titles navigationItem.title = "Messages" navigationController?.navigationBar.prefersLargeTitles = true } func setupTableView() { //Register Cell Identifier in TableView tableView.register(ChatMessageCell.self, forCellReuseIdentifier: cellIdentifier) //Remove Separator lines tableView.separatorStyle = .none tableView.backgroundColor = UIColor(white: 0.95, alpha: 1) tableView.allowsSelection = false } func setupConstraints() { tableView.translatesAutoresizingMaskIntoConstraints = false tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages[section].chat.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ChatMessageCell let chatModel = messages[indexPath.section].chat[indexPath.row] cell.chatModel = chatModel return cell } override func numberOfSections(in tableView: UITableView) -> Int { return messages.count } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let dateString = convertDateInString(messages[section].date) let label = DataHeaderLabel() label.text = dateString let containerView = UIView() containerView.addSubview(label) label.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true label.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true return containerView } //Spacing in TOP override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } fileprivate func convertStringInDate(_ stringDt: String) -> Date { let converter = DateFormatter() converter.dateFormat = "dd/MM/yyyy" return converter.date(from: stringDt) ?? Date() } fileprivate func convertDateInString(_ date: Date) -> String { let converter = DateFormatter() converter.dateFormat = "dd/MM/yyyy" return converter.string(from: date) } }
42.490909
446
0.65276
21e6b9ebfd9adedd3a1190502d564be1f04ac739
1,347
// // TestConfig.example.swift // // // Created by Jan Ruhlaender on 24.04.20. // import Foundation /// TODO: Rename this file to TestConfig class TestConfigExample { // MARK: - Required information to create an access token for the APNs Service /// the TEAM-ID Must be set and is used as issuer of the notification. static let teamID = "YOUR_TEN_LETTER_TEAM_ID" // Your Key-ID. See: Apple Developer Account / Certificates, Identifiers & Profiles / Keys static let keyID = "YOUR_10_LETTER_KEY_ID" // Your Key-File. Must be created and downloaded. See: Apple Developer Account / Certificates, Identifiers & Profiles / Keys // IMPORTANT: This file path must not be located in a protected directory like Downloads static let p8FilePath = "LOCAL_PATH/AuthKey_<KEY-ID>.p8" // MARK: - required information to create a notification // This identifier must be created by the app. See: https://stackoverflow.com/questions/25925481/how-to-get-a-unique-device-id-in-swift static let deviceID = "YOUR_DEVICE_ID" // Application Bundle Identifier from your App. See: Project / Target / General / Bundle Identifier static let appBundleID = "YOUR_APP_BUNDLE_ID" // Payload of the notification static let payload = "{\"aps\":{\"alert\":\"Test\"},\"yourCustomKey\":\"1\"}" }
37.416667
139
0.703044
de0f509256ffebe986e1dc43c1f2e995a0fd0e3a
2,784
// // Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved. // The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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 WebAuthenticationUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? weak var windowScene: UIWindowScene? weak var signInViewController: UIViewController? func signIn() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let signInController = storyboard.instantiateViewController(withIdentifier: "SignIn") signInViewController = signInController window?.rootViewController = signInController } func showProfile() { let storyboard = UIStoryboard(name: "Profile", bundle: nil) let profileViewController = storyboard.instantiateInitialViewController() window?.rootViewController = profileViewController } func setRootViewController() { if Credential.default == nil { self.signIn() } else { self.showProfile() } } func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let scene = (scene as? UIWindowScene) else { return } windowScene = scene NotificationCenter.default.addObserver(forName: .defaultCredentialChanged, object: nil, queue: .main) { notification in self.setRootViewController() } setRootViewController() } func sceneDidDisconnect(_ scene: UIScene) { } func sceneDidBecomeActive(_ scene: UIScene) { guard signInViewController == nil, Credential.default == nil else { return } DispatchQueue.main.async { self.signIn() } } func sceneWillResignActive(_ scene: UIScene) { } func sceneWillEnterForeground(_ scene: UIScene) { } func sceneDidEnterBackground(_ scene: UIScene) { } func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { print(URLContexts) do { try WebAuthentication.shared?.resume(with: URLContexts) } catch { print(error) } } }
31.280899
127
0.658764
7abfeeeaa05ee59418f9820a7699873935b949cd
723
// // ViewController.swift // TrophyKit Example tvOS // // Created by Yubo Qin on 7/1/21. // Copyright © 2021 CocoaPods. All rights reserved. // import UIKit import TrophyKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func showTrophy() { let trophy = Trophy(configuration: TrophyConfiguration(size: .medium)) trophy.show(from: self, title: "Achievement Unlocked", subtitle: "You have added a new skill!", iconSymbol: "gamecontroller.fill", trophyIconSymbol: "rosette") } }
23.322581
78
0.608575
013e37b9f2ffad122b59de096f9ad3ea61cdcd20
598
// // BlockContactsRequestModel.swift // Chat // // Created by Mahyar Zhiani on 10/1/1397 AP. // Copyright © 1397 Mahyar Zhiani. All rights reserved. // import Foundation open class BlockContactsRequestModel { public let contactId: Int? public let threadId: Int? public let typeCode: String? public let userId: Int? public init(contactId: Int?, threadId: Int?, typeCode: String?, userId: Int?) { self.contactId = contactId self.threadId = threadId self.typeCode = typeCode self.userId = userId } }
22.148148
83
0.625418
09f1a2936f30e1bb87680cb73767b77e2dfe6833
622
// // Constraint+SnapKit.swift // BrainKit // // Created by Ondřej Hanák on 22. 02. 2021. // Copyright © 2021 Userbrain. All rights reserved. // import SnapKit extension Constraint { public static func set(activated activatedConstraints: [Constraint] = [], deactivated deactivatedConstraints: [Constraint] = []) { deactivatedConstraints.forEach { $0.deactivate() } activatedConstraints.forEach { $0.activate() } } public static func set(activated activatedConstraint: Constraint?, deactivated deactivatedConstraint: Constraint?) { deactivatedConstraint?.deactivate() activatedConstraint?.activate() } }
28.272727
131
0.747588
e55f325043d4a44f0209217e69a6a46a3bc1aa03
4,084
// // ConfidenceMapRecorder.swift // ScannerApp-Swift // // Created by Zheren Xiao on 2020-10-27. // Copyright © 2020 jx16. All rights reserved. // import Accelerate.vImage import Compression import CoreMedia import CoreVideo import Foundation class ConfidenceMapRecorder: Recorder { typealias T = CVPixelBuffer private let confidenceMapQueue = DispatchQueue(label: "confidence map queue") private var fileHandle: FileHandle? = nil private var fileUrl: URL? = nil private var compressedFileUrl: URL? = nil private var count: Int32 = 0 func prepareForRecording(dirPath: String, filename: String, fileExtension: String = "confidence") { confidenceMapQueue.async { self.count = 0 let filePath = (dirPath as NSString).appendingPathComponent((filename as NSString).appendingPathExtension(fileExtension)!) let compressedFilePath = (filePath as NSString).appendingPathExtension("zlib")! self.fileUrl = URL(fileURLWithPath: filePath) self.compressedFileUrl = URL(fileURLWithPath: compressedFilePath) FileManager.default.createFile(atPath: self.fileUrl!.path, contents: nil, attributes: nil) self.fileHandle = FileHandle(forUpdatingAtPath: self.fileUrl!.path) if self.fileHandle == nil { print("Unable to create file handle.") return } } } func update(_ buffer: CVPixelBuffer, timestamp: CMTime? = nil) { confidenceMapQueue.async { print("Saving confidence map \(self.count) ...") CVPixelBufferLockBaseAddress(buffer, .readOnly) let baseAddress: UnsafeMutableRawPointer = CVPixelBufferGetBaseAddress(buffer)! let size = CVPixelBufferGetDataSize(buffer) let data = Data(bytesNoCopy: baseAddress, count: size, deallocator: .none) self.fileHandle?.write(data) CVPixelBufferUnlockBaseAddress(buffer, .readOnly) self.count += 1 } } func finishRecording() { confidenceMapQueue.async { if self.fileHandle != nil { self.fileHandle!.closeFile() self.fileHandle = nil } print("\(self.count) confidence maps saved.") self.compressFile() self.removeUncompressedFile() } } // below are duplicate with code in DepthRecorder, consider refactor // this method is based on apple's sample app Compression-Streaming-Sample private func compressFile() { let algorithm = COMPRESSION_ZLIB let operation = COMPRESSION_STREAM_ENCODE // let compressedFilePath = (fileUrl!.path as NSString).appendingPathExtension("zlib")! // let compressedFileUrl = URL(fileURLWithPath: compressedFilePath) FileManager.default.createFile(atPath: compressedFileUrl!.path, contents: nil, attributes: nil) if let sourceFileHandle = try? FileHandle(forReadingFrom: fileUrl!), let destinationFileHandle = try? FileHandle(forWritingTo: compressedFileUrl!) { Compressor.streamingCompression(operation: operation, sourceFileHandle: sourceFileHandle, destinationFileHandle: destinationFileHandle, algorithm: algorithm) { print($0) } } } private func removeUncompressedFile() { do { try FileManager.default.removeItem(at: fileUrl!) print("Uncompressed depth file \(fileUrl!.lastPathComponent) removed.") } catch { print("Unable to remove uncompressed depth file.") } } }
34.610169
134
0.585455
fcf9b62ab51901a7cb1c4f51107758ff41bb1710
11,442
// RUN: rm -rf %t // RUN: %swift-syntax-test -input-source-filename %s -parse-gen > %t // RUN: diff -u %s %t // RUN: %swift-syntax-test -input-source-filename %s -parse-gen -print-node-kind > %t.withkinds // RUN: diff -u %S/Outputs/round_trip_parse_gen.swift.withkinds %t.withkinds // RUN: %swift-syntax-test -input-source-filename %s -eof > %t // RUN: diff -u %s %t // RUN: %swift-syntax-test -serialize-raw-tree -input-source-filename %s > %t.dump // RUN: %swift-syntax-test -deserialize-raw-tree -input-source-filename %t.dump -output-filename %t // RUN: diff -u %s %t import ABC import A.B.C @objc import A.B @objc import typealias A.B import struct A.B #warning("test warning") #error("test error") #if Blah class C { func bar(_ a: Int) {} func bar1(_ a: Float) -> Float { return -0.6 + 0.1 - 0.3 } func bar2(a: Int, b: Int, c:Int) -> Int { return 1 } func bar3(a: Int) -> Int { return 1 } func bar4(_ a: Int) -> Int { return 1 } func foo() { var a = /*comment*/"ab\(x)c"/*comment*/ var b = /*comment*/+2/*comment*/ bar(1) bar(+10) bar(-10) bar1(-1.1) bar1(1.1) var f = /*comments*/+0.1/*comments*/ foo() _ = "🙂🤗🤩🤔🤨" } func foo1() { _ = bar2(a:1, b:2, c:2) _ = bar2(a:1 + 1, b:2 * 2 + 2, c:2 + 2) _ = bar2(a : bar2(a: 1, b: 2, c: 3), b: 2, c: 3) _ = bar3(a : bar3(a: bar3(a: 1))) _ = bar4(bar4(bar4(1))) _ = [:] _ = [] _ = [1, 2, 3, 4] _ = [1:1, 2:2, 3:3, 4:4] _ = [bar3(a:1), bar3(a:1), bar3(a:1), bar3(a:1)] _ = ["a": bar3(a:1), "b": bar3(a:1), "c": bar3(a:1), "d": bar3(a:1)] foo(nil, nil, nil) _ = type(of: a).self _ = a.`self` _ = A -> B.C<Int> _ = [(A) throws -> B]() } func boolAnd() -> Bool { return true && false } func boolOr() -> Bool { return true || false } func foo2() { _ = true ? 1 : 0 _ = (true ? 1 : 0) ? (true ? 1 : 0) : (true ? 1 : 0) _ = (1, 2) _ = (first: 1, second: 2) _ = (1) _ = (first: 1) if !true { return } } func foo3() { _ = [Any]() _ = (@convention(c) (Int) -> Void).self _ = a.a.a _ = a.b _ = 1.a (1 + 1).a.b.foo _ = a as Bool || a as! Bool || a as? Bool _ = a is Bool _ = self _ = Self } func superExpr() { _ = super.foo super.bar() super[12] = 1 super.init() } func implicitMember() { _ = .foo _ = .foo(x: 12) _ = .foo() { 12 } _ = .foo[12] _ = .foo.bar } init() {} @objc private init(a: Int) init!(a: Int) {} init?(a: Int) {} public init(a: Int) throws {} init(a: Int..., b: Double...) {} @objc deinit {} private deinit {} internal subscript(x: Int) -> Int { get {} set {} } subscript() -> Int { return 1 } subscript(x: Int..., y y: String...) -> Int { return 1 } var x: Int { address { fatalError() } unsafeMutableAddress { fatalError() } } } protocol PP { associatedtype A associatedtype B: Sequence associatedtype C = Int associatedtype D: Sequence = [Int] associatedtype E: Sequence = [[Int]] where A.Element : Sequence private associatedtype F @objc associatedtype G } #endif #if blah typealias A = Any #elseif blahblah typealias B = (Array<Array<Any>>.Element, x: Int) #else typealias C = [Int] #endif typealias D = [Int: String] typealias E = Int?.Protocol typealias F = [Int]!.Type typealias G = (a x: Int, _ y: Int ... = 1) throw -> () -> () typealias H = () rethrows -> () typealias I = (A & B<C>) -> C & D typealias J = inout @autoclosure () -> Int typealias K = (@invalidAttr Int, inout Int, __shared Int, __owned Int) -> () @objc private typealias T<a,b> = Int @objc private typealias T<a,b> class Foo { let bar: Int } class Bar: Foo { var foo: Int = 42 } class C<A, B> where A: Foo, B == Bar {} @available(*, unavailable) private class C {} struct foo { struct foo { struct foo { func foo() { } } } struct foo {} } struct foo { @available(*, unavailable) struct foo {} public class foo { @available(*, unavailable) @objc(fooObjc) private static func foo() {} @objc(fooObjcBar:baz:) private static func foo(bar: String, baz: Int) } } struct S<A, B, C, @objc D> where A:B, B==C, A : C, B.C == D.A, A.B: C.D {} private struct S<A, B>: Base where A: B { private struct S: A, B {} } protocol P: class {} func foo(_ _: Int, a b: Int = 3 + 2, _ c: Int = 2, d _: Int = true ? 2: 3, @objc e: X = true, f: inout Int, g: Int..., h: Bool...) throws -> [Int: String] {} func foo(_ a: Int) throws -> Int {} func foo( a: Int) rethrows -> Int {} struct C { @objc @available(*, unavailable) private static override func foo<a, b, c>(a b: Int, c: Int) throws -> [Int] where a==p1, b:p2 { ddd } func rootView() -> Label {} static func ==() -> bool {} static func !=<a, b, c>() -> bool {} } @objc private protocol foo : bar where A==B {} protocol foo { func foo() } private protocol foo{} @objc public protocol foo where A:B {} #if blah func tryfoo() { try foo() try! foo() try? foo() try! foo().bar().foo().bar() } #else func closure() { _ = {[weak a, unowned(safe) self, b = 3, unowned(unsafe) c = foo().bar] in } _ = {[] in } _ = { [] a, b, _ -> Int in return 2 } _ = { [] (a: Int, b: Int, _: Int) -> Int in return 2 } _ = { [] a, b, _ throws -> Int in return 2 } _ = { [] (a: Int, _ b: Int) throws -> Int in return 2 } _ = { a, b in } _ = { (a, b) in } _ = {} _ = { s1, s2 in s1 > s2 } _ = { $0 > $1 } } #endif func postfix() { foo() foo() {} foo {} foo { } arg2: {} foo {} foo.bar() foo.bar() {} foo.bar() {} arg2: {} in: {} foo.bar {} foo[] foo[1] foo[] {} foo[1] {} foo[1] {} arg2: {} foo[1][2,x:3] foo?++.bar!(baz).self foo().0 foo<Int>.bar foo<Int>() foo.bar<Int>() foo(x:y:)() foo(x:)<Int> { } _ = .foo(x:y:) _ = x.foo(x:y:) _ = foo(&d) _ = <#Placeholder#> + <#T##(Int) -> Int#> } #if blah #else #endif class C { var a: Int { @objc mutating set(value) {} mutating get { return 3 } @objc didSet {} willSet(newValue){ } } var a : Int { return 3 } } protocol P { var a: Int { get set } var a: Int {} } private final class D { @objc static private var a: Int = 3 { return 3 }, b: Int, c = 4, d : Int { get {} get {}}, (a, b): (Int, Int) let (a, b) = (1,2), _ = 4 {} func patternTests() { for let (x, _) in foo {} for var x: Int in foo {} } } do { switch foo { case let a: break case let a as Int: break case let (a, b): break case (let a, var b): break case is Int: break case let .bar(x): break case MyEnum.foo: break case let a as Int: break case let a?: break } } func statementTests() { do { } catch (var x, let y) { } catch where false { } catch let e where e.foo == bar { } catch .a(let a), .b(let b) where b == "" { } catch { } repeat { } while true LABEL: repeat { } while false while true { } LABEL: while true { } LABEL: do {} LABEL: switch foo { case 1: fallthrough case 2: break LABEL case 3: break } for a in b { defer { () } if c { throw MyError() continue } else { continue LABEL } } if foo, let a = foo, let b: Int = foo, var c = foo, case (let v, _) = foo, case (let v, _): (Int, Int) = foo { } else if foo { } else { } guard let a = b else {} guard let self = self else {} for var i in foo where i.foo {} for case is Int in foo {} switch Foo { case n1: break case n2, n3l: break #if FOO case let (x, y) where !x, n3l where false: break #elseif BAR case let y: break #else case .foo(let x): break #endif default: break } switch foo { case 1, 2, 3: break default: break } switch foo { case 1, 2, 3: break @unknown default: break } switch foo { case 1, 2, 3: break @unknown case _: break } switch foo { case 1, 2, 3: break // This is rejected in Sema, but should be preserved by Syntax. @unknown case (42, -42) where 1 == 2: break @garbage case 0: break @garbage(foobar) case -1: break } } // MARK: - ExtensionDecl extension ext { var s: Int { return 42 } } @available(*, unavailable) fileprivate extension ext {} extension ext : extProtocol {} extension ext where A == Int, B: Numeric {} extension ext.a.b {} func foo() { var a = "abc \(foo()) def \(a + b + "a \(3)") gh \(bar, default: 1)" var a = """ abc \( foo() + bar() ) de \(3 + 3 + "abc \(foo()) def") fg \(bar, default: 1) """ } func keypath() { _ = \a.?.b _ = \a.b.c _ = \a.b[1] _ = \.a.b _ = \Array<Int>.[] _ = #keyPath(a.b.c) } func objcSelector() { _ = [ #selector(getter: Foo.bar), #selector(setter: Foo.Bar.baz), #selector(Foo.method(x:y:)), #selector(foo[42].bar(x)), #selector({ [x] in return nil }) ] } func objectLiterals() { #fileLiteral(a) #colorLiteral(a, b) #imageLiteral(a, b, c) #column #file #function #dsohandle } enum E1 : String { case foo = 1 case bar = "test", baz(x: Int, String) = 12 indirect case qux(E1) indirect private enum E2<T>: String where T: SomeProtocol { case foo, bar, baz } } precedencegroup FooPrecedence { higherThan: DefaultPrecedence, UnknownPrecedence assignment: false associativity: none } precedencegroup BarPrecedence {} precedencegroup BazPrecedence { associativity: left assignment: true associativity: right lowerThan: DefaultPrecedence } infix operator<++>:FooPrecedence prefix operator..<< postfix operator <- func higherOrderFunc() { let x = [1,2,3] x.reduce(0, +) } if #available(iOS 11, macOS 10.11.2, *) {} @_specialize(where T == Int) @_specialize(exported: true, where T == String) public func specializedGenericFunc<T>(_ t: T) -> T { return t } protocol Q { func g() var x: String { get } func f(x:Int, y:Int) -> Int #if FOO_BAR var conditionalVar: String #endif } struct S : Q, Equatable { @_implements(Q, f(x:y:)) func h(x:Int, y:Int) -> Int { return 6 } @_implements(Equatable, ==(_:_:)) public static func isEqual(_ lhs: S, _ rhs: S) -> Bool { return false } @_implements(P, x) var y: String @_implements(P, g()) func h() { _ = \.self } @available(*, deprecated: 1.2, message: "ABC") fileprivate(set) var x: String } struct ReadModify { var st0 = ("a", "b") var rm0: (String, String) { _read { yield (("a", "b")) } _modify { yield &st0 } } var rm1: (String, String) { _read { yield (st0) } } } @custom @_alignment(16) public struct float3 { public var x, y, z: Float } #sourceLocation(file: "otherFile.swift", line: 5) func foo() {} #sourceLocation() "abc \( } ) def" #assert(true) #assert(false) #assert(true, "hello world") public func anyFoo() -> some Foo {} public func qoo() -> some O & O2 {} func zlop() -> some C & AnyObject & P {} @custom(a, b,c) func foo() {} @custom_attr @custom(A: a, B: b, C:c) func foo() {} "abc" "abc \(foo)" #"abc"# #"abc \#(foo)"# ##"abc"## ##"abc \##(foo)"## foo() #if COND1 .bar?()! #elseif COND2 #if true .call() #elseif true #if true .other #endif #else .before() #if true .after() #endif #endif .member #else .baz() {} #endif
18.425121
105
0.5423
0a4c11f660a6c0fb92a52515dce22e3fe67e5776
108,636
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 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 SwiftPrivate import SwiftPrivateThreadExtras import SwiftPrivateLibcExtras #if canImport(Darwin) #if _runtime(_ObjC) import Foundation #endif import Darwin #elseif canImport(Glibc) import Glibc #elseif os(Windows) import CRT import WinSDK #endif #if _runtime(_ObjC) import ObjectiveC #endif extension String { /// Returns the lines in `self`. public var _lines : [String] { return _split(separator: "\n") } /// Splits `self` at occurrences of `separator`. public func _split(separator: Unicode.Scalar) -> [String] { let scalarSlices = unicodeScalars.split { $0 == separator } return scalarSlices.map { String(String.UnicodeScalarView($0)) } } } public struct SourceLoc { public let file: String public let line: UInt public let comment: String? public init(_ file: String, _ line: UInt, comment: String? = nil) { self.file = file self.line = line self.comment = comment } public func withCurrentLoc( _ file: String = #file, line: UInt = #line ) -> SourceLocStack { return SourceLocStack(self).with(SourceLoc(file, line)) } } public struct SourceLocStack { let locs: [SourceLoc] public init() { locs = [] } public init(_ loc: SourceLoc) { locs = [loc] } init(_locs: [SourceLoc]) { locs = _locs } var isEmpty: Bool { return locs.isEmpty } public func with(_ loc: SourceLoc) -> SourceLocStack { var locs = self.locs locs.append(loc) return SourceLocStack(_locs: locs) } public func pushIf( _ showFrame: Bool, file: String, line: UInt ) -> SourceLocStack { return showFrame ? self.with(SourceLoc(file, line)) : self } public func withCurrentLoc( file: String = #file, line: UInt = #line ) -> SourceLocStack { return with(SourceLoc(file, line)) } public func print() { let top = locs.first! Swift.print("check failed at \(top.file), line \(top.line)") _printStackTrace(SourceLocStack(_locs: Array(locs.dropFirst()))) } } fileprivate struct AtomicBool { private var _value: _stdlib_AtomicInt init(_ b: Bool) { self._value = _stdlib_AtomicInt(b ? 1 : 0) } func store(_ b: Bool) { _value.store(b ? 1 : 0) } func load() -> Bool { return _value.load() != 0 } @discardableResult func orAndFetch(_ b: Bool) -> Bool { return _value.orAndFetch(b ? 1 : 0) != 0 } func fetchAndClear() -> Bool { return _value.fetchAndAnd(0) != 0 } } func _printStackTrace(_ stackTrace: SourceLocStack?) { guard let s = stackTrace, !s.locs.isEmpty else { return } print("stacktrace:") for (i, loc) in s.locs.reversed().enumerated() { let comment = (loc.comment != nil) ? " ; \(loc.comment!)" : "" print(" #\(i): \(loc.file):\(loc.line)\(comment)") } } fileprivate var _anyExpectFailed = AtomicBool(false) fileprivate var _seenExpectCrash = AtomicBool(false) /// Run `body` and expect a failure to happen. /// /// The check passes iff `body` triggers one or more failures. public func expectFailure( _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line, invoking body: () -> Void) { let startAnyExpectFailed = _anyExpectFailed.fetchAndClear() body() let endAnyExpectFailed = _anyExpectFailed.fetchAndClear() expectTrue( endAnyExpectFailed, "running `body` should produce an expected failure", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line) ) _anyExpectFailed.orAndFetch(startAnyExpectFailed) } /// An opaque function that ignores its argument and returns nothing. public func noop<T>(_ value: T) {} /// An opaque function that simply returns its argument. public func identity<T>(_ value: T) -> T { return value } public func identity(_ element: OpaqueValue<Int>) -> OpaqueValue<Int> { return element } public func identityEq(_ element: MinimalEquatableValue) -> MinimalEquatableValue { return element } public func identityComp(_ element: MinimalComparableValue) -> MinimalComparableValue { return element } public func expectEqual<T : Equatable>(_ expected: T, _ actual: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { expectEqualTest(expected, actual, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1} } public func expectEqual<T : Equatable, U : Equatable>( _ expected: (T, U), _ actual: (T, U), _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { expectEqualTest(expected.0, actual.0, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1} expectEqualTest(expected.1, actual.1, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1} } public func expectEqual<T : Equatable, U : Equatable, V : Equatable>( _ expected: (T, U, V), _ actual: (T, U, V), _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { expectEqualTest(expected.0, actual.0, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1} expectEqualTest(expected.1, actual.1, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1} expectEqualTest(expected.2, actual.2, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1} } public func expectEqual<T : Equatable, U : Equatable, V : Equatable, W : Equatable>( _ expected: (T, U, V, W), _ actual: (T, U, V, W), _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { expectEqualTest(expected.0, actual.0, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1} expectEqualTest(expected.1, actual.1, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1} expectEqualTest(expected.2, actual.2, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1} expectEqualTest(expected.3, actual.3, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1} } public func expectEqual(_ expected: String, _ actual: Substring, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if !(expected == actual) { expectationFailure( "expected: \(String(reflecting: expected)) (of type \(String(reflecting: type(of: expected))))\n" + "actual: \(String(reflecting: actual)) (of type \(String(reflecting: type(of: actual))))", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line) ) } } public func expectEqual(_ expected: Substring, _ actual: String, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if !(expected == actual) { expectationFailure( "expected: \(String(reflecting: expected)) (of type \(String(reflecting: type(of: expected))))\n" + "actual: \(String(reflecting: actual)) (of type \(String(reflecting: type(of: actual))))", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line) ) } } public func expectEqual(_ expected: String, _ actual: String, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if !(expected == actual) { expectationFailure( "expected: \(String(reflecting: expected)) (of type \(String(reflecting: type(of: expected))))\n" + "actual: \(String(reflecting: actual)) (of type \(String(reflecting: type(of: actual))))", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line) ) } } public func expectEqualReference(_ expected: AnyObject?, _ actual: AnyObject?, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { expectEqualTest(expected, actual, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 === $1} } public func expectationFailure( _ reason: String, trace message: String, stackTrace: SourceLocStack) { _anyExpectFailed.store(true) stackTrace.print() print(reason, terminator: reason == "" ? "" : "\n") print(message, terminator: message == "" ? "" : "\n") } // Renamed to avoid collision with expectEqual(_, _, TRACE). // See <rdar://26058520> Generic type constraints incorrectly applied to // functions with the same name public func expectEqualTest<T>( _ expected: T, _ actual: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line, sameValue equal: (T, T) -> Bool ) { if !equal(expected, actual) { expectationFailure( "expected: \(String(reflecting: expected)) (of type \(String(reflecting: type(of: expected))))\n" + "actual: \(String(reflecting: actual)) (of type \(String(reflecting: type(of: actual))))", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line) ) } } public func expectNotEqual<T : Equatable>(_ expected: T, _ actual: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if expected == actual { expectationFailure( "unexpected value: \"\(actual)\" (of type \(String(reflecting: type(of: actual))))", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line) ) } } public func expectOptionalEqual<T>( _ expected: T, _ actual: T?, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line, sameValue equal: (T, T) -> Bool ) { if (actual == nil) || !equal(expected, actual!) { expectationFailure( "expected: \"\(expected)\" (of type \(String(reflecting: type(of: expected))))\n" + "actual: \"\(actual.debugDescription)\" (of type \(String(reflecting: type(of: actual))))", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectEqual( _ expected: Any.Type, _ actual: Any.Type, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { expectEqualTest(expected, actual, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) { $0 == $1 } } public func expectLT<T : Comparable>(_ lhs: T, _ rhs: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if !(lhs < rhs) { expectationFailure("\(lhs) < \(rhs)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } else if !(rhs > lhs) { expectationFailure("\(lhs) < \(rhs) (flipped)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectLE<T : Comparable>(_ lhs: T, _ rhs: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if !(lhs <= rhs) { expectationFailure("\(lhs) <= \(rhs)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } else if !(rhs >= lhs) { expectationFailure("\(lhs) <= \(rhs) (flipped)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectGT<T : Comparable>(_ lhs: T, _ rhs: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if !(lhs > rhs) { expectationFailure("\(lhs) > \(rhs)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } else if !(rhs < lhs) { expectationFailure("\(lhs) > \(rhs) (flipped)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectGE<T : Comparable>(_ lhs: T, _ rhs: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if !(lhs >= rhs) { expectationFailure("\(lhs) >= \(rhs)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } else if !(rhs <= lhs) { expectationFailure("\(lhs) >= \(rhs) (flipped)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } extension Range { internal func _contains(_ other: Range<Bound>) -> Bool { if other.lowerBound < lowerBound { return false } if upperBound < other.upperBound { return false } return true } } extension Range { internal func _contains(_ other: ClosedRange<Bound>) -> Bool { if other.lowerBound < lowerBound { return false } if upperBound <= other.upperBound { return false } return true } } public func expectTrapping<Bound>( _ point: Bound, in range: Range<Bound>, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { if !range.contains(point) { expectationFailure("\(point) in \(range)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) _trappingExpectationFailedCallback() } } public func expectTrapping<Bound>( _ subRange: Range<Bound>, in range: Range<Bound>, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { if !range._contains(subRange) { expectationFailure("\(subRange) in \(range)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) _trappingExpectationFailedCallback() } } public func expectTrapping<Bound>( _ point: Bound, in range: ClosedRange<Bound>, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { if !range.contains(point) { expectationFailure("\(point) in \(range)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) _trappingExpectationFailedCallback() } } public func expectTrapping<Bound>( _ subRange: ClosedRange<Bound>, in range: Range<Bound>, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { if !range._contains(subRange) { expectationFailure("\(subRange) in \(range)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) _trappingExpectationFailedCallback() } } extension ClosedRange { internal func _contains(_ other: ClosedRange<Bound>) -> Bool { if other.lowerBound < lowerBound { return false } if upperBound < other.upperBound { return false } return true } } public func expectTrapping<Bound>( _ subRange: ClosedRange<Bound>, in range: ClosedRange<Bound>, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { if !range._contains(subRange) { expectationFailure("\(subRange) in \(range)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) _trappingExpectationFailedCallback() } } public func expectType<T>(_: T.Type, _ x: inout T) {} public func expectEqualType<T>(_: T.Type, _: T.Type) {} public func expectSequenceType<X : Sequence>(_ x: X) -> X { return x } public func expectCollectionType<X : Collection>( _ x: X.Type ) {} public func expectMutableCollectionType<X : MutableCollection>( _ x: X.Type ) {} /// A slice is a `Collection` that when sliced returns an instance of /// itself. public func expectSliceType<X : Collection>( _ sliceType: X.Type ) where X.SubSequence == X {} /// A mutable slice is a `MutableCollection` that when sliced returns an /// instance of itself. public func expectMutableSliceType<X : MutableCollection>( _ mutableSliceType: X.Type ) where X.SubSequence == X {} /// Check that all associated types of a `Sequence` are what we expect them /// to be. public func expectSequenceAssociatedTypes<X : Sequence>( sequenceType: X.Type, iteratorType: X.Iterator.Type ) {} /// Check that all associated types of a `Collection` are what we expect them /// to be. public func expectCollectionAssociatedTypes<X : Collection>( collectionType: X.Type, iteratorType: X.Iterator.Type, subSequenceType: X.SubSequence.Type, indexType: X.Index.Type, indicesType: X.Indices.Type ) {} /// Check that all associated types of a `BidirectionalCollection` are what we /// expect them to be. public func expectBidirectionalCollectionAssociatedTypes<X : BidirectionalCollection>( collectionType: X.Type, iteratorType: X.Iterator.Type, subSequenceType: X.SubSequence.Type, indexType: X.Index.Type, indicesType: X.Indices.Type ) {} /// Check that all associated types of a `RandomAccessCollection` are what we /// expect them to be. public func expectRandomAccessCollectionAssociatedTypes<X : RandomAccessCollection>( collectionType: X.Type, iteratorType: X.Iterator.Type, subSequenceType: X.SubSequence.Type, indexType: X.Index.Type, indicesType: X.Indices.Type ) {} public struct AssertionResult : CustomStringConvertible { init(isPass: Bool) { self._isPass = isPass } public func withDescription(_ description: String) -> AssertionResult { var result = self result.description += description return result } let _isPass: Bool public var description: String = "" } public func assertionSuccess() -> AssertionResult { return AssertionResult(isPass: true) } public func assertionFailure() -> AssertionResult { return AssertionResult(isPass: false) } public func expectUnreachable( _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { expectationFailure("this code should not be executed", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } public func expectUnreachableCatch(_ error: Error, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { expectationFailure( "error should not be thrown: \"\(error)\"", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } public func expectTrue(_ actual: AssertionResult, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if !actual._isPass { expectationFailure( "expected: passed assertion\n\(actual.description)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectFalse(_ actual: AssertionResult, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if actual._isPass { expectationFailure( "expected: failed assertion\n\(actual.description)", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectTrue(_ actual: Bool, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if !actual { expectationFailure("expected: true", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectFalse(_ actual: Bool, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if actual { expectationFailure("expected: false", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectThrows<ErrorType: Error & Equatable>( _ expectedError: ErrorType? = nil, _ test: () throws -> Void, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { do { try test() } catch let error as ErrorType { if let expectedError = expectedError { expectEqual(expectedError, error) } } catch { expectationFailure("unexpected error thrown: \"\(error)\"", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectDoesNotThrow(_ test: () throws -> Void, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { do { try test() } catch { expectationFailure("unexpected error thrown: \"\(error)\"", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectNil<T>(_ value: T?, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { if value != nil { expectationFailure( "expected optional to be nil\nactual: \"\(value!)\"", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } @discardableResult public func expectNotNil<T>(_ value: T?, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) -> T? { if value == nil { expectationFailure("expected optional to be non-nil", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } return value } public func expectCrashLater(withMessage message: String = "") { print("\(_stdlibUnittestStreamPrefix);expectCrash;\(_anyExpectFailed.load())") var stderr = _Stderr() print("\(_stdlibUnittestStreamPrefix);expectCrash;\(message)", to: &stderr) _seenExpectCrash.store(true) } public func expectCrash(withMessage message: String = "", executing: () -> Void) -> Never { expectCrashLater(withMessage: message) executing() expectUnreachable() fatalError() } func _defaultTestSuiteFailedCallback() { abort() } var _testSuiteFailedCallback: () -> Void = _defaultTestSuiteFailedCallback public func _setTestSuiteFailedCallback(_ callback: @escaping () -> Void) { _testSuiteFailedCallback = callback } func _defaultTrappingExpectationFailedCallback() { abort() } var _trappingExpectationFailedCallback: () -> Void = _defaultTrappingExpectationFailedCallback public func _setTrappingExpectationFailedCallback(callback: @escaping () -> Void) { _trappingExpectationFailedCallback = callback } extension ProcessTerminationStatus { var isSwiftTrap: Bool { switch self { case .signal(let signal): #if os(Windows) return CInt(signal) == SIGILL #elseif os(WASI) // No signals support on WASI yet, see https://github.com/WebAssembly/WASI/issues/166. return false #else return CInt(signal) == SIGILL || CInt(signal) == SIGTRAP #endif default: // This default case is needed for standard library builds where // resilience is enabled. // FIXME: Add the .exit case when there is a way to suppress when not. // case .exit: return false return false } } } func _stdlib_getline() -> String? { var result: [UInt8] = [] while true { let c = getchar() if c == EOF { if result.isEmpty { return nil } return String(decoding: result, as: UTF8.self) } if c == CInt(Unicode.Scalar("\n").value) { return String(decoding: result, as: UTF8.self) } result.append(UInt8(c)) } } func _printDebuggingAdvice(_ fullTestName: String) { print("To debug, run:") var invocation = [CommandLine.arguments[0]] #if os(Windows) var buffer: UnsafeMutablePointer<CChar>? var length: Int = 0 if _dupenv_s(&buffer, &length, "SWIFT_INTERPRETER") != 0, let buffer = buffer { invocation.insert(String(cString: buffer), at: 0) free(buffer) } #else let interpreter = getenv("SWIFT_INTERPRETER") if interpreter != nil { if let interpreterCmd = String(validatingUTF8: interpreter!) { invocation.insert(interpreterCmd, at: 0) } } #endif print("$ \(invocation.joined(separator: " ")) " + "--stdlib-unittest-in-process --stdlib-unittest-filter \"\(fullTestName)\"") } var _allTestSuites: [TestSuite] = [] var _testSuiteNameToIndex: [String : Int] = [:] let _stdlibUnittestStreamPrefix = "__STDLIB_UNITTEST__" let _crashedPrefix = "CRASHED:" @_silgen_name("installTrapInterceptor") func _installTrapInterceptor() #if _runtime(_ObjC) @objc protocol _StdlibUnittestNSException { @objc optional var name: AnyObject { get } } #endif // Avoid serializing references to objc_setUncaughtExceptionHandler in SIL. @inline(never) func _childProcess() { _installTrapInterceptor() #if _runtime(_ObjC) objc_setUncaughtExceptionHandler { let exception = ($0 as Optional)! as AnyObject var stderr = _Stderr() let maybeNSException = unsafeBitCast(exception, to: _StdlibUnittestNSException.self) if let name = maybeNSException.name { print("*** [StdlibUnittest] Terminating due to uncaught exception " + "\(name): \(exception)", to: &stderr) } else { print("*** [StdlibUnittest] Terminating due to uncaught exception: " + "\(exception)", to: &stderr) } } #endif while let line = _stdlib_getline() { let parts = line._split(separator: ";") if parts[0] == _stdlibUnittestStreamPrefix { precondition(parts[1] == "shutdown") return } let testSuiteName = parts[0] let testName = parts[1] var testParameter: Int? if parts.count > 2 { testParameter = Int(parts[2])! } else { testParameter = nil } let testSuite = _allTestSuites[_testSuiteNameToIndex[testSuiteName]!] _anyExpectFailed.store(false) testSuite._runTest(name: testName, parameter: testParameter) print("\(_stdlibUnittestStreamPrefix);end;\(_anyExpectFailed.load())") var stderr = _Stderr() print("\(_stdlibUnittestStreamPrefix);end", to: &stderr) if testSuite._shouldShutDownChildProcess(forTestNamed: testName) { return } } } #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY @inline(never) func _childProcessAsync() async { _installTrapInterceptor() #if _runtime(_ObjC) objc_setUncaughtExceptionHandler { let exception = ($0 as Optional)! as AnyObject var stderr = _Stderr() let maybeNSException = unsafeBitCast(exception, to: _StdlibUnittestNSException.self) if let name = maybeNSException.name { print("*** [StdlibUnittest] Terminating due to uncaught exception " + "\(name): \(exception)", to: &stderr) } else { print("*** [StdlibUnittest] Terminating due to uncaught exception: " + "\(exception)", to: &stderr) } } #endif while let line = _stdlib_getline() { let parts = line._split(separator: ";") if parts[0] == _stdlibUnittestStreamPrefix { precondition(parts[1] == "shutdown") return } let testSuiteName = parts[0] let testName = parts[1] var testParameter: Int? if parts.count > 2 { testParameter = Int(parts[2])! } else { testParameter = nil } let testSuite = _allTestSuites[_testSuiteNameToIndex[testSuiteName]!] _anyExpectFailed.store(false) await testSuite._runTestAsync(name: testName, parameter: testParameter) print("\(_stdlibUnittestStreamPrefix);end;\(_anyExpectFailed.load())") var stderr = _Stderr() print("\(_stdlibUnittestStreamPrefix);end", to: &stderr) if testSuite._shouldShutDownChildProcess(forTestNamed: testName) { return } } } #endif class _ParentProcess { #if os(Windows) internal var _process: HANDLE = INVALID_HANDLE_VALUE internal var _childStdin: _FDOutputStream = _FDOutputStream(handle: INVALID_HANDLE_VALUE) internal var _childStdout: _FDInputStream = _FDInputStream(handle: INVALID_HANDLE_VALUE) internal var _childStderr: _FDInputStream = _FDInputStream(handle: INVALID_HANDLE_VALUE) #else internal var _pid: pid_t? internal var _childStdin: _FDOutputStream = _FDOutputStream(fd: -1) internal var _childStdout: _FDInputStream = _FDInputStream(fd: -1) internal var _childStderr: _FDInputStream = _FDInputStream(fd: -1) #endif internal var _runTestsInProcess: Bool internal var _filter: String? internal var _args: [String] init(runTestsInProcess: Bool, args: [String], filter: String?) { self._runTestsInProcess = runTestsInProcess self._filter = filter self._args = args } func _spawnChild() { let params = ["--stdlib-unittest-run-child"] + _args #if os(Windows) let (hProcess, hStdIn, hStdOut, hStdErr) = spawnChild(params) self._process = hProcess self._childStdin = _FDOutputStream(handle: hStdIn) self._childStdout = _FDInputStream(handle: hStdOut) self._childStderr = _FDInputStream(handle: hStdErr) #else let (pid, childStdinFD, childStdoutFD, childStderrFD) = spawnChild(params) _pid = pid _childStdin = _FDOutputStream(fd: childStdinFD) _childStdout = _FDInputStream(fd: childStdoutFD) _childStderr = _FDInputStream(fd: childStderrFD) #endif } func _waitForChild() -> ProcessTerminationStatus { #if os(Windows) let status = waitProcess(_process) _process = INVALID_HANDLE_VALUE _childStdin.close() _childStdout.close() _childStderr.close() #else let status = posixWaitpid(_pid!) _pid = nil _childStdin.close() _childStdout.close() _childStderr.close() _childStdin = _FDOutputStream(fd: -1) _childStdout = _FDInputStream(fd: -1) _childStderr = _FDInputStream(fd: -1) #endif return status } internal func _readFromChild( onStdoutLine: @escaping (String) -> (done: Bool, Void), onStderrLine: @escaping (String) -> (done: Bool, Void) ) { #if os(Windows) let (_, stdoutThread) = _stdlib_thread_create_block({ while !self._childStdout.isEOF { self._childStdout.read() while var line = self._childStdout.getline() { if let cr = line.firstIndex(of: "\r") { line.remove(at: cr) } var done: Bool (done: done, ()) = onStdoutLine(line) if done { return } } } }, ()) let (_, stderrThread) = _stdlib_thread_create_block({ while !self._childStderr.isEOF { self._childStderr.read() while var line = self._childStderr.getline() { if let cr = line.firstIndex(of: "\r") { line.remove(at: cr) } var done: Bool (done: done, ()) = onStderrLine(line) if done { return } } } }, ()) let (_, _) = _stdlib_thread_join(stdoutThread!, Void.self) let (_, _) = _stdlib_thread_join(stderrThread!, Void.self) #else var readfds = _stdlib_fd_set() var writefds = _stdlib_fd_set() var errorfds = _stdlib_fd_set() var done = false while !((_childStdout.isEOF && _childStderr.isEOF) || done) { readfds.zero() errorfds.zero() if !_childStdout.isEOF { readfds.set(_childStdout.fd) errorfds.set(_childStdout.fd) } if !_childStderr.isEOF { readfds.set(_childStderr.fd) errorfds.set(_childStderr.fd) } var ret: CInt repeat { ret = _stdlib_select(&readfds, &writefds, &errorfds, nil) } while ret == -1 && errno == EINTR if ret <= 0 { fatalError("select() returned an error") } if readfds.isset(_childStdout.fd) || errorfds.isset(_childStdout.fd) { _childStdout.read() while let line = _childStdout.getline() { (done: done, ()) = onStdoutLine(line) } continue } if readfds.isset(_childStderr.fd) || errorfds.isset(_childStderr.fd) { _childStderr.read() while let line = _childStderr.getline() { (done: done, ()) = onStderrLine(line) } continue } } #endif } /// Returns the values of the corresponding variables in the child process. internal func _runTestInChild( _ testSuite: TestSuite, _ testName: String, parameter: Int? ) -> (anyExpectFailed: Bool, seenExpectCrash: Bool, status: ProcessTerminationStatus?, crashStdout: [Substring], crashStderr: [Substring]) { #if os(Windows) if _process == INVALID_HANDLE_VALUE { _spawnChild() } #else if _pid == nil { _spawnChild() } #endif print("\(testSuite.name);\(testName)", terminator: "", to: &_childStdin) if let parameter = parameter { print(";", terminator: "", to: &_childStdin) print(parameter, terminator: "", to: &_childStdin) } print("", to: &_childStdin) let currentTest = testSuite._testByName(testName) if let stdinText = currentTest.stdinText { print(stdinText, terminator: "", to: &_childStdin) } if currentTest.stdinEndsWithEOF { _childStdin.close() } var stdoutSeenCrashDelimiter = false var stderrSeenCrashDelimiter = false var expectingPreCrashMessage = "" var stdoutEnd = false var stderrEnd = false var capturedCrashStdout: [Substring] = [] var capturedCrashStderr: [Substring] = [] var anyExpectFailedInChild = false func processLine(_ line: String, isStdout: Bool) -> (done: Bool, Void) { var line = line[...] if let index = findSubstring(line, _stdlibUnittestStreamPrefix) { let controlMessage = line[index..<line.endIndex].split(separator: ";", omittingEmptySubsequences: false) switch controlMessage[1] { case "expectCrash": fallthrough case "expectCrash\r": if isStdout { stdoutSeenCrashDelimiter = true anyExpectFailedInChild = controlMessage[2] == "true" } else { stderrSeenCrashDelimiter = true expectingPreCrashMessage = String(controlMessage[2]) } case "end": fallthrough case "end\r": if isStdout { stdoutEnd = true anyExpectFailedInChild = controlMessage[2] == "true" } else { stderrEnd = true } default: fatalError("unexpected message: \(controlMessage[1])") } line = line[line.startIndex..<index] if line.isEmpty { #if os(Windows) return (done: isStdout ? stdoutEnd : stderrEnd, ()) #else return (done: stdoutEnd && stderrEnd, ()) #endif } } if !expectingPreCrashMessage.isEmpty && findSubstring(line, expectingPreCrashMessage) != nil { line = "OK: saw expected pre-crash message in \"\(line)\""[...] expectingPreCrashMessage = "" } if isStdout { if stdoutSeenCrashDelimiter { capturedCrashStdout.append(line) } } else { if stderrSeenCrashDelimiter { capturedCrashStderr.append(line) if findSubstring(line, _crashedPrefix) != nil { if !expectingPreCrashMessage.isEmpty { line = """ FAIL: saw expected "\(line.lowercased())", but without \ message "\(expectingPreCrashMessage)" before it """[...] anyExpectFailedInChild = true } else { line = "OK: saw expected \"\(line.lowercased())\""[...] } } } } if isStdout { print("stdout>>> \(line)") } else { print("stderr>>> \(line)") } #if os(Windows) return (done: isStdout ? stdoutEnd : stderrEnd, ()) #else return (done: stdoutEnd && stderrEnd, ()) #endif } _readFromChild( onStdoutLine: { processLine($0, isStdout: true) }, onStderrLine: { processLine($0, isStdout: false) }) // Check if the child has sent us "end" markers for the current test. if stdoutEnd && stderrEnd { var status: ProcessTerminationStatus? if testSuite._shouldShutDownChildProcess(forTestNamed: testName) { status = _waitForChild() switch status! { case .exit(0): status = nil default: () } } return ( anyExpectFailedInChild, stdoutSeenCrashDelimiter || stderrSeenCrashDelimiter, status, capturedCrashStdout, capturedCrashStderr) } // We reached EOF on stdout and stderr and we did not see "end" markers, so // it looks like child crashed (of course it could have closed the file // descriptors, but we assume it did not, since it prevent further // communication with the parent). let status = _waitForChild() return ( anyExpectFailedInChild, stdoutSeenCrashDelimiter || stderrSeenCrashDelimiter, status, capturedCrashStdout, capturedCrashStderr) } internal func _shutdownChild() -> (failed: Bool, Void) { #if os(Windows) if _process == INVALID_HANDLE_VALUE { // The child process is not running. Report that it didn't fail during // shutdown. return (failed: false, ()) } #else if _pid == nil { // The child process is not running. Report that it didn't fail during // shutdown. return (failed: false, ()) } #endif // If the child process expects an EOF, its stdin fd has already been closed and // it will shut itself down automatically. if !_childStdin.isClosed { print("\(_stdlibUnittestStreamPrefix);shutdown", to: &_childStdin) } var childCrashed = false func processLine(_ line: String, isStdout: Bool) -> (done: Bool, Void) { if isStdout { print("stdout>>> \(line)") } else { if findSubstring(line, _crashedPrefix) != nil { childCrashed = true } print("stderr>>> \(line)") } return (done: false, ()) } _readFromChild( onStdoutLine: { processLine($0, isStdout: true) }, onStderrLine: { processLine($0, isStdout: false) }) let status = _waitForChild() switch status { case .exit(0): return (failed: childCrashed, ()) default: print("Abnormal child process termination: \(status).") return (failed: true, ()) } } internal enum _TestStatus { case skip([TestRunPredicate]) case pass case fail case uxPass case xFail } internal func runOneTest( fullTestName: String, testSuite: TestSuite, test t: TestSuite._Test, testParameter: Int? ) -> _TestStatus { let activeSkips = t.getActiveSkipPredicates() if !activeSkips.isEmpty { return .skip(activeSkips) } let activeXFails = t.getActiveXFailPredicates() let expectXFail = !activeXFails.isEmpty let activeXFailsText = expectXFail ? " (XFAIL: \(activeXFails))" : "" print("[ RUN ] \(fullTestName)\(activeXFailsText)") var expectCrash = false var childTerminationStatus: ProcessTerminationStatus? var crashStdout: [Substring] = [] var crashStderr: [Substring] = [] if _runTestsInProcess { if t.stdinText != nil { print("The test \(fullTestName) requires stdin input and can't be run in-process, marking as failed") _anyExpectFailed.store(true) } else if t.requiresOwnProcess { print("The test \(fullTestName) requires running in a child process and can't be run in-process, marking as failed.") _anyExpectFailed.store(true) } else { _anyExpectFailed.store(false) testSuite._runTest(name: t.name, parameter: testParameter) } } else { var anyExpectFailed = false (anyExpectFailed, expectCrash, childTerminationStatus, crashStdout, crashStderr) = _runTestInChild(testSuite, t.name, parameter: testParameter) _anyExpectFailed.store(anyExpectFailed) } // Determine if the test passed, not taking XFAILs into account. var testPassed = false switch (childTerminationStatus, expectCrash) { case (.none, false): testPassed = !_anyExpectFailed.load() case (.none, true): testPassed = false print("expecting a crash, but the test did not crash") case (.some, false): testPassed = false print("the test crashed unexpectedly") case (.some, true): testPassed = !_anyExpectFailed.load() } if testPassed && t.crashOutputMatches.count > 0 { // If we still think that the test passed, check if the crash // output matches our expectations. let crashOutput = crashStdout + crashStderr for expectedSubstring in t.crashOutputMatches { var found = false for s in crashOutput { if findSubstring(s, expectedSubstring) != nil { found = true break } } if !found { print("did not find expected string after crash: \(expectedSubstring.debugDescription)") testPassed = false } } } // Apply XFAILs. switch (testPassed, expectXFail) { case (true, false): return .pass case (true, true): return .uxPass case (false, false): return .fail case (false, true): return .xFail } } #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY internal func runOneTestAsync( fullTestName: String, testSuite: TestSuite, test t: TestSuite._Test, testParameter: Int? ) async -> _TestStatus { let activeSkips = t.getActiveSkipPredicates() if !activeSkips.isEmpty { return .skip(activeSkips) } let activeXFails = t.getActiveXFailPredicates() let expectXFail = !activeXFails.isEmpty let activeXFailsText = expectXFail ? " (XFAIL: \(activeXFails))" : "" print("[ RUN ] \(fullTestName)\(activeXFailsText)") var expectCrash = false var childTerminationStatus: ProcessTerminationStatus? var crashStdout: [Substring] = [] var crashStderr: [Substring] = [] if _runTestsInProcess { if t.stdinText != nil { print("The test \(fullTestName) requires stdin input and can't be run in-process, marking as failed") _anyExpectFailed.store(true) } else if t.requiresOwnProcess { print("The test \(fullTestName) requires running in a child process and can't be run in-process, marking as failed.") _anyExpectFailed.store(true) } else { _anyExpectFailed.store(false) await testSuite._runTestAsync(name: t.name, parameter: testParameter) } } else { var anyExpectFailed = false (anyExpectFailed, expectCrash, childTerminationStatus, crashStdout, crashStderr) = _runTestInChild(testSuite, t.name, parameter: testParameter) _anyExpectFailed.store(anyExpectFailed) } // Determine if the test passed, not taking XFAILs into account. var testPassed = false switch (childTerminationStatus, expectCrash) { case (.none, false): testPassed = !_anyExpectFailed.load() case (.none, true): testPassed = false print("expecting a crash, but the test did not crash") case (.some, false): testPassed = false print("the test crashed unexpectedly") case (.some, true): testPassed = !_anyExpectFailed.load() } if testPassed && t.crashOutputMatches.count > 0 { // If we still think that the test passed, check if the crash // output matches our expectations. let crashOutput = crashStdout + crashStderr for expectedSubstring in t.crashOutputMatches { var found = false for s in crashOutput { if findSubstring(s, expectedSubstring) != nil { found = true break } } if !found { print("did not find expected string after crash: \(expectedSubstring.debugDescription)") testPassed = false } } } // Apply XFAILs. switch (testPassed, expectXFail) { case (true, false): return .pass case (true, true): return .uxPass case (false, false): return .fail case (false, true): return .xFail } } #endif func run() { if let filter = _filter { print("StdlibUnittest: using filter: \(filter)") } for testSuite in _allTestSuites { var uxpassedTests: [String] = [] var failedTests: [String] = [] var skippedTests: [String] = [] for t in testSuite._tests { for testParameter in t.parameterValues { var testName = t.name if let testParameter = testParameter { testName += "/" testName += String(testParameter) } let fullTestName = "\(testSuite.name).\(testName)" if let filter = _filter, findSubstring(fullTestName, filter) == nil { continue } switch runOneTest( fullTestName: fullTestName, testSuite: testSuite, test: t, testParameter: testParameter ) { case .skip(let activeSkips): skippedTests.append(testName) print("[ SKIP ] \(fullTestName) (skip: \(activeSkips))") case .pass: print("[ OK ] \(fullTestName)") case .uxPass: uxpassedTests.append(testName) print("[ UXPASS ] \(fullTestName)") case .fail: failedTests.append(testName) print("[ FAIL ] \(fullTestName)") case .xFail: print("[ XFAIL ] \(fullTestName)") } } } if !uxpassedTests.isEmpty || !failedTests.isEmpty { print("\(testSuite.name): Some tests failed, aborting") print("UXPASS: \(uxpassedTests)") print("FAIL: \(failedTests)") print("SKIP: \(skippedTests)") if !uxpassedTests.isEmpty { _printDebuggingAdvice(uxpassedTests[0]) } if !failedTests.isEmpty { _printDebuggingAdvice(failedTests[0]) } _testSuiteFailedCallback() } else { print("\(testSuite.name): All tests passed") } } let (failed: failedOnShutdown, ()) = _shutdownChild() if failedOnShutdown { print("The child process failed during shutdown, aborting.") _testSuiteFailedCallback() } } #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY func runAsync() async { if let filter = _filter { print("StdlibUnittest: using filter: \(filter)") } for testSuite in _allTestSuites { var uxpassedTests: [String] = [] var failedTests: [String] = [] var skippedTests: [String] = [] for t in testSuite._tests { for testParameter in t.parameterValues { var testName = t.name if let testParameter = testParameter { testName += "/" testName += String(testParameter) } let fullTestName = "\(testSuite.name).\(testName)" if let filter = _filter, findSubstring(fullTestName, filter) == nil { continue } switch await runOneTestAsync( fullTestName: fullTestName, testSuite: testSuite, test: t, testParameter: testParameter ) { case .skip(let activeSkips): skippedTests.append(testName) print("[ SKIP ] \(fullTestName) (skip: \(activeSkips))") case .pass: print("[ OK ] \(fullTestName)") case .uxPass: uxpassedTests.append(testName) print("[ UXPASS ] \(fullTestName)") case .fail: failedTests.append(testName) print("[ FAIL ] \(fullTestName)") case .xFail: print("[ XFAIL ] \(fullTestName)") } } } if !uxpassedTests.isEmpty || !failedTests.isEmpty { print("\(testSuite.name): Some tests failed, aborting") print("UXPASS: \(uxpassedTests)") print("FAIL: \(failedTests)") print("SKIP: \(skippedTests)") if !uxpassedTests.isEmpty { _printDebuggingAdvice(uxpassedTests[0]) } if !failedTests.isEmpty { _printDebuggingAdvice(failedTests[0]) } _testSuiteFailedCallback() } else { print("\(testSuite.name): All tests passed") } } let (failed: failedOnShutdown, ()) = _shutdownChild() if failedOnShutdown { print("The child process failed during shutdown, aborting.") _testSuiteFailedCallback() } } #endif } // Track repeated calls to runAllTests() and/or runNoTests(). // Complain if a file runs no tests without calling runNoTests(). struct PersistentState { static var runAllTestsWasCalled: Bool = false static var runNoTestsWasCalled: Bool = false static var ranSomething: Bool = false static var complaintInstalled = false static var hashingKeyOverridden = false static func complainIfNothingRuns() { if !complaintInstalled { complaintInstalled = true atexit { if !PersistentState.ranSomething { print("Ran no tests and runNoTests() was not called. Aborting. ") print("Did you forget to call runAllTests()?") _testSuiteFailedCallback() } } } } } // Call runNoTests() if you want to deliberately run no tests. public func runNoTests() { if PersistentState.runAllTestsWasCalled { print("runNoTests() called after runAllTests(). Aborting.") _testSuiteFailedCallback() return } if PersistentState.runNoTestsWasCalled { print("runNoTests() called twice. Aborting.") _testSuiteFailedCallback() return } PersistentState.runNoTestsWasCalled = true PersistentState.ranSomething = true } public func runAllTests() { if PersistentState.runNoTestsWasCalled { print("runAllTests() called after runNoTests(). Aborting.") _testSuiteFailedCallback() return } if PersistentState.runAllTestsWasCalled { print("runAllTests() called twice. Aborting.") _testSuiteFailedCallback() return } PersistentState.runAllTestsWasCalled = true PersistentState.ranSomething = true #if _runtime(_ObjC) autoreleasepool { _stdlib_initializeReturnAutoreleased() } #endif let _isChildProcess: Bool = CommandLine.arguments.contains("--stdlib-unittest-run-child") if _isChildProcess { _childProcess() } else { var runTestsInProcess: Bool = false var filter: String? var args = [String]() var i = 0 i += 1 // Skip the name of the executable. while i < CommandLine.arguments.count { let arg = CommandLine.arguments[i] if arg == "--stdlib-unittest-in-process" { runTestsInProcess = true i += 1 continue } if arg == "--stdlib-unittest-filter" { filter = CommandLine.arguments[i + 1] i += 2 continue } if arg == "--help" { let message = "optional arguments:\n" + "--stdlib-unittest-in-process\n" + " run tests in-process without intercepting crashes.\n" + " Useful for running under a debugger.\n" + "--stdlib-unittest-filter FILTER-STRING\n" + " only run tests whose names contain FILTER-STRING as\n" + " a substring." print(message) return } // Pass through unparsed arguments to the child process. args.append(CommandLine.arguments[i]) i += 1 } let parent = _ParentProcess( runTestsInProcess: runTestsInProcess, args: args, filter: filter) parent.run() } } #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY public func runAllTestsAsync() async { if PersistentState.runNoTestsWasCalled { print("runAllTests() called after runNoTests(). Aborting.") _testSuiteFailedCallback() return } if PersistentState.runAllTestsWasCalled { print("runAllTests() called twice. Aborting.") _testSuiteFailedCallback() return } PersistentState.runAllTestsWasCalled = true PersistentState.ranSomething = true #if _runtime(_ObjC) autoreleasepool { _stdlib_initializeReturnAutoreleased() } #endif let _isChildProcess: Bool = CommandLine.arguments.contains("--stdlib-unittest-run-child") if _isChildProcess { await _childProcessAsync() } else { var runTestsInProcess: Bool = false var filter: String? var args = [String]() var i = 0 i += 1 // Skip the name of the executable. while i < CommandLine.arguments.count { let arg = CommandLine.arguments[i] if arg == "--stdlib-unittest-in-process" { runTestsInProcess = true i += 1 continue } if arg == "--stdlib-unittest-filter" { filter = CommandLine.arguments[i + 1] i += 2 continue } if arg == "--help" { let message = "optional arguments:\n" + "--stdlib-unittest-in-process\n" + " run tests in-process without intercepting crashes.\n" + " Useful for running under a debugger.\n" + "--stdlib-unittest-filter FILTER-STRING\n" + " only run tests whose names contain FILTER-STRING as\n" + " a substring." print(message) return } // Pass through unparsed arguments to the child process. args.append(CommandLine.arguments[i]) i += 1 } let parent = _ParentProcess( runTestsInProcess: runTestsInProcess, args: args, filter: filter) await parent.runAsync() } } #endif #if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER @_silgen_name("_swift_leaks_startTrackingObjects") func startTrackingObjects(_: UnsafePointer<CChar>) @_silgen_name("_swift_leaks_stopTrackingObjects") func stopTrackingObjects(_: UnsafePointer<CChar>) -> Int #endif public final class TestSuite { public init(_ name: String) { self.name = name precondition( _testNameToIndex[name] == nil, "test suite with the same name already exists") _allTestSuites.append(self) _testSuiteNameToIndex[name] = _allTestSuites.count - 1 PersistentState.complainIfNothingRuns() } // This method is prohibited from inlining because inlining the test harness // into the test is not interesting from the runtime performance perspective. // And it does not really make the test cases more effectively at testing the // optimizer from a correctness prospective. On the contrary, it sometimes // severely affects the compile time of the test code. @inline(never) public func test( _ name: String, file: String = #file, line: UInt = #line, _ testFunction: @escaping () -> Void ) { _TestBuilder(testSuite: self, name: name, loc: SourceLoc(file, line)) .code(testFunction) } #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY // This method is prohibited from inlining because inlining the test harness // into the test is not interesting from the runtime performance perspective. // And it does not really make the test cases more effectively at testing the // optimizer from a correctness prospective. On the contrary, it sometimes // severely affects the compile time of the test code. @inline(never) public func test( _ name: String, file: String = #file, line: UInt = #line, _ testFunction: @escaping () async -> Void ) { _TestBuilder(testSuite: self, name: name, loc: SourceLoc(file, line)) .code(testFunction) } #endif // This method is prohibited from inlining because inlining the test harness // into the test is not interesting from the runtime performance perspective. // And it does not really make the test cases more effectively at testing the // optimizer from a correctness prospective. On the contrary, it sometimes // severely affects the compile time of the test code. @inline(never) public func test( _ name: String, file: String = #file, line: UInt = #line ) -> _TestBuilder { return _TestBuilder(testSuite: self, name: name, loc: SourceLoc(file, line)) } public func setUp(_ code: @escaping () -> Void) { precondition(_testSetUpCode == nil, "set-up code already set") _testSetUpCode = code } public func tearDown(_ code: @escaping () -> Void) { precondition(_testTearDownCode == nil, "tear-down code already set") _testTearDownCode = code } func _runTest(name testName: String, parameter: Int?) { PersistentState.ranSomething = true for r in _allResettables { r.reset() } LifetimeTracked.instances = 0 if let f = _testSetUpCode { f() } let test = _testByName(testName) #if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER startTrackingObjects(name) #endif switch test.code { case .single(let code): precondition( parameter == nil, "can't pass parameters to non-parameterized tests") code() case .parameterized(code: let code, _): code(parameter!) #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY case .singleAsync(_): fatalError("Cannot call async code, use `runAllTestsAsync`") case .parameterizedAsync(code: _, _): fatalError("Cannot call async code, use `runAllTestsAsync`") #endif } #if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER _ = stopTrackingObjects(name) #endif if let f = _testTearDownCode { f() } expectEqual( 0, LifetimeTracked.instances, "Found leaked LifetimeTracked instances.", file: test.testLoc.file, line: test.testLoc.line) } #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY func _runTestAsync(name testName: String, parameter: Int?) async { PersistentState.ranSomething = true for r in _allResettables { r.reset() } LifetimeTracked.instances = 0 if let f = _testSetUpCode { f() } let test = _testByName(testName) #if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER startTrackingObjects(name) #endif switch test.code { case .single(let code): precondition( parameter == nil, "can't pass parameters to non-parameterized tests") code() case .parameterized(code: let code, _): code(parameter!) #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY case .singleAsync(let code): precondition( parameter == nil, "can't pass parameters to non-parameterized tests") await code() case .parameterizedAsync(code: let code, _): await code(parameter!) #endif } #if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER _ = stopTrackingObjects(name) #endif if let f = _testTearDownCode { f() } expectEqual( 0, LifetimeTracked.instances, "Found leaked LifetimeTracked instances.", file: test.testLoc.file, line: test.testLoc.line) } #endif func _testByName(_ testName: String) -> _Test { return _tests[_testNameToIndex[testName]!] } /// Determines if we should shut down the current test process, i.e. if this /// test or the next test requires executing in its own process. func _shouldShutDownChildProcess(forTestNamed testName: String) -> Bool { let index = _testNameToIndex[testName]! if index == _tests.count - 1 { return false } let currentTest = _tests[index] let nextTest = _tests[index + 1] if !currentTest.canReuseChildProcessAfterTest { return true } return currentTest.requiresOwnProcess || nextTest.requiresOwnProcess } internal enum _TestCode { case single(code: () -> Void) case parameterized(code: (Int) -> Void, count: Int) #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY case singleAsync(code: () async -> Void) case parameterizedAsync(code: (Int) async -> Void, count: Int) #endif } internal struct _Test { let name: String let testLoc: SourceLoc let xfail: [TestRunPredicate] let skip: [TestRunPredicate] let stdinText: String? let stdinEndsWithEOF: Bool let crashOutputMatches: [String] let code: _TestCode let requiresOwnProcess: Bool /// Whether the test harness should stop reusing the child process after /// running this test. var canReuseChildProcessAfterTest: Bool { return stdinText == nil } func getActiveXFailPredicates() -> [TestRunPredicate] { return xfail.filter { $0.evaluate() } } func getActiveSkipPredicates() -> [TestRunPredicate] { return skip.filter { $0.evaluate() } } var parameterValues: [Int?] { switch code { case .single: return [nil] case .parameterized(code: _, count: let count): return Array(0..<count) #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY case .singleAsync: return [nil] case .parameterizedAsync(code: _, count: let count): return Array(0..<count) #endif } } } public struct _TestBuilder { let _testSuite: TestSuite var _name: String var _data: _Data = _Data() internal final class _Data { var _xfail: [TestRunPredicate] = [] var _skip: [TestRunPredicate] = [] var _stdinText: String? var _stdinEndsWithEOF: Bool = false var _crashOutputMatches: [String] = [] var _testLoc: SourceLoc? var _requiresOwnProcess: Bool = false } init(testSuite: TestSuite, name: String, loc: SourceLoc) { _testSuite = testSuite _name = name _data._testLoc = loc } public func xfail(_ predicate: TestRunPredicate) -> _TestBuilder { _data._xfail.append(predicate) return self } public func skip(_ predicate: TestRunPredicate) -> _TestBuilder { _data._skip.append(predicate) return self } public func stdin(_ stdinText: String, eof: Bool = false) -> _TestBuilder { _data._stdinText = stdinText _data._stdinEndsWithEOF = eof return self } public func crashOutputMatches(_ string: String) -> _TestBuilder { _data._crashOutputMatches.append(string) return self } public func requireOwnProcess() -> _TestBuilder { _data._requiresOwnProcess = true return self } internal func _build(_ testCode: _TestCode) { _testSuite._tests.append( _Test( name: _name, testLoc: _data._testLoc!, xfail: _data._xfail, skip: _data._skip, stdinText: _data._stdinText, stdinEndsWithEOF: _data._stdinEndsWithEOF, crashOutputMatches: _data._crashOutputMatches, code: testCode, requiresOwnProcess: _data._requiresOwnProcess)) _testSuite._testNameToIndex[_name] = _testSuite._tests.count - 1 } public func code(_ testFunction: @escaping () -> Void) { _build(.single(code: testFunction)) } #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY public func code(_ testFunction: @escaping () async -> Void) { _build(.singleAsync(code: testFunction)) } #endif public func forEach<Data>( in parameterSets: [Data], testFunction: @escaping (Data) -> Void ) { _build(.parameterized( code: { (i: Int) in testFunction(parameterSets[i]) }, count: parameterSets.count)) } #if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY public func forEach<Data>( in parameterSets: [Data], testFunction: @escaping (Data) async -> Void ) { _build(.parameterizedAsync( code: { (i: Int) in await testFunction(parameterSets[i]) }, count: parameterSets.count)) } #endif } var name: String var _tests: [_Test] = [] /// Code that is run before every test. var _testSetUpCode: (() -> Void)? /// Code that is run after every test. var _testTearDownCode: (() -> Void)? /// Maps test name to index in `_tests`. var _testNameToIndex: [String : Int] = [:] } #if canImport(Darwin) #if _runtime(_ObjC) func _getSystemVersionPlistProperty(_ propertyName: String) -> String? { return NSDictionary(contentsOfFile: "/System/Library/CoreServices/SystemVersion.plist")?[propertyName] as? String } #else func _getSystemVersionPlistProperty(_ propertyName: String) -> String? { var count = 0 sysctlbyname("kern.osproductversion", nil, &count, nil, 0) var s = [CChar](repeating: 0, count: count) sysctlbyname("kern.osproductversion", &s, &count, nil, 0) return String(cString: &s) } #endif #endif public enum OSVersion : CustomStringConvertible { case osx(major: Int, minor: Int, bugFix: Int) case iOS(major: Int, minor: Int, bugFix: Int) case tvOS(major: Int, minor: Int, bugFix: Int) case watchOS(major: Int, minor: Int, bugFix: Int) case iOSSimulator case tvOSSimulator case watchOSSimulator case linux case musl case freeBSD case openBSD case android case ps4 case windowsCygnus case windows case haiku case wasi public var description: String { switch self { case .osx(let major, let minor, let bugFix): return "OS X \(major).\(minor).\(bugFix)" case .iOS(let major, let minor, let bugFix): return "iOS \(major).\(minor).\(bugFix)" case .tvOS(let major, let minor, let bugFix): return "TVOS \(major).\(minor).\(bugFix)" case .watchOS(let major, let minor, let bugFix): return "watchOS \(major).\(minor).\(bugFix)" case .iOSSimulator: return "iOSSimulator" case .tvOSSimulator: return "TVOSSimulator" case .watchOSSimulator: return "watchOSSimulator" case .linux: return "Linux" case .musl: return "Musl" case .freeBSD: return "FreeBSD" case .openBSD: return "OpenBSD" case .ps4: return "PS4" case .android: return "Android" case .windowsCygnus: return "Cygwin" case .windows: return "Windows" case .haiku: return "Haiku" case .wasi: return "WASI" } } } func _parseDottedVersion(_ s: String) -> [Int] { return Array(s._split(separator: ".").lazy.map { Int($0)! }) } public func _parseDottedVersionTriple(_ s: String) -> (Int, Int, Int) { let array = _parseDottedVersion(s) if array.count >= 4 { fatalError("unexpected version") } return ( array.count >= 1 ? array[0] : 0, array.count >= 2 ? array[1] : 0, array.count >= 3 ? array[2] : 0) } func _getOSVersion() -> OSVersion { #if os(iOS) && targetEnvironment(simulator) // On simulator, the plist file that we try to read turns out to be host's // plist file, which indicates OS X. // // FIXME: how to get the simulator version *without* UIKit? return .iOSSimulator #elseif os(tvOS) && targetEnvironment(simulator) return .tvOSSimulator #elseif os(watchOS) && targetEnvironment(simulator) return .watchOSSimulator #elseif os(Linux) return .linux #elseif os(Musl) return .musl #elseif os(FreeBSD) return .freeBSD #elseif os(OpenBSD) return .openBSD #elseif os(PS4) return .ps4 #elseif os(Android) return .android #elseif os(Cygwin) return .windowsCygnus #elseif os(Windows) return .windows #elseif os(Haiku) return .haiku #elseif os(WASI) return .wasi #else let productVersion = _getSystemVersionPlistProperty("ProductVersion")! let (major, minor, bugFix) = _parseDottedVersionTriple(productVersion) #if os(macOS) return .osx(major: major, minor: minor, bugFix: bugFix) #elseif os(iOS) return .iOS(major: major, minor: minor, bugFix: bugFix) #elseif os(tvOS) return .tvOS(major: major, minor: minor, bugFix: bugFix) #elseif os(watchOS) return .watchOS(major: major, minor: minor, bugFix: bugFix) #else fatalError("could not determine OS version") #endif #endif } var _runningOSVersion: OSVersion = _getOSVersion() var _overrideOSVersion: OSVersion? /// Override the OS version for testing. public func _setOverrideOSVersion(_ v: OSVersion) { _overrideOSVersion = v } func _getRunningOSVersion() -> OSVersion { // Allow overriding the OS version for testing. return _overrideOSVersion ?? _runningOSVersion } public enum TestRunPredicate : CustomStringConvertible { case custom(() -> Bool, reason: String) case always(/*reason:*/ String) case never case osxAny(/*reason:*/ String) case osxMajor(Int, reason: String) case osxMinor(Int, Int, reason: String) case osxMinorRange(Int, ClosedRange<Int>, reason: String) case osxBugFix(Int, Int, Int, reason: String) case osxBugFixRange(Int, Int, ClosedRange<Int>, reason: String) case iOSAny(/*reason:*/ String) case iOSMajor(Int, reason: String) case iOSMajorRange(ClosedRange<Int>, reason: String) case iOSMinor(Int, Int, reason: String) case iOSMinorRange(Int, ClosedRange<Int>, reason: String) case iOSBugFix(Int, Int, Int, reason: String) case iOSBugFixRange(Int, Int, ClosedRange<Int>, reason: String) case iOSSimulatorAny(/*reason:*/ String) case tvOSAny(/*reason:*/ String) case tvOSMajor(Int, reason: String) case tvOSMajorRange(ClosedRange<Int>, reason: String) case tvOSMinor(Int, Int, reason: String) case tvOSMinorRange(Int, ClosedRange<Int>, reason: String) case tvOSBugFix(Int, Int, Int, reason: String) case tvOSBugFixRange(Int, Int, ClosedRange<Int>, reason: String) case tvOSSimulatorAny(/*reason:*/ String) case watchOSAny(/*reason:*/ String) case watchOSMajor(Int, reason: String) case watchOSMajorRange(ClosedRange<Int>, reason: String) case watchOSMinor(Int, Int, reason: String) case watchOSMinorRange(Int, ClosedRange<Int>, reason: String) case watchOSBugFix(Int, Int, Int, reason: String) case watchOSBugFixRange(Int, Int, ClosedRange<Int>, reason: String) case watchOSSimulatorAny(/*reason:*/ String) case linuxAny(reason: String) case freeBSDAny(reason: String) case ps4Any(reason: String) case androidAny(reason: String) case windowsAny(reason: String) case windowsCygnusAny(reason: String) case haikuAny(reason: String) case objCRuntime(/*reason:*/ String) case nativeRuntime(/*reason:*/ String) public var description: String { switch self { case .custom(_, let reason): return "Custom(reason: \(reason))" case .always(let reason): return "Always(reason: \(reason))" case .never: return "" case .osxAny(let reason): return "osx(*, reason: \(reason))" case .osxMajor(let major, let reason): return "osx(\(major).*, reason: \(reason))" case .osxMinor(let major, let minor, let reason): return "osx(\(major).\(minor), reason: \(reason))" case .osxMinorRange(let major, let minorRange, let reason): return "osx(\(major).[\(minorRange)], reason: \(reason))" case .osxBugFix(let major, let minor, let bugFix, let reason): return "osx(\(major).\(minor).\(bugFix), reason: \(reason))" case .osxBugFixRange(let major, let minor, let bugFixRange, let reason): return "osx(\(major).\(minor).[\(bugFixRange)], reason: \(reason))" case .iOSAny(let reason): return "iOS(*, reason: \(reason))" case .iOSMajor(let major, let reason): return "iOS(\(major).*, reason: \(reason))" case .iOSMajorRange(let range, let reason): return "iOS([\(range)], reason: \(reason))" case .iOSMinor(let major, let minor, let reason): return "iOS(\(major).\(minor), reason: \(reason))" case .iOSMinorRange(let major, let minorRange, let reason): return "iOS(\(major).[\(minorRange)], reason: \(reason))" case .iOSBugFix(let major, let minor, let bugFix, let reason): return "iOS(\(major).\(minor).\(bugFix), reason: \(reason))" case .iOSBugFixRange(let major, let minor, let bugFixRange, let reason): return "iOS(\(major).\(minor).[\(bugFixRange)], reason: \(reason))" case .iOSSimulatorAny(let reason): return "iOSSimulatorAny(*, reason: \(reason))" case .tvOSAny(let reason): return "tvOS(*, reason: \(reason))" case .tvOSMajor(let major, let reason): return "tvOS(\(major).*, reason: \(reason))" case .tvOSMajorRange(let range, let reason): return "tvOS([\(range)], reason: \(reason))" case .tvOSMinor(let major, let minor, let reason): return "tvOS(\(major).\(minor), reason: \(reason))" case .tvOSMinorRange(let major, let minorRange, let reason): return "tvOS(\(major).[\(minorRange)], reason: \(reason))" case .tvOSBugFix(let major, let minor, let bugFix, let reason): return "tvOS(\(major).\(minor).\(bugFix), reason: \(reason))" case .tvOSBugFixRange(let major, let minor, let bugFixRange, let reason): return "tvOS(\(major).\(minor).[\(bugFixRange)], reason: \(reason))" case .tvOSSimulatorAny(let reason): return "tvOSSimulatorAny(*, reason: \(reason))" case .watchOSAny(let reason): return "watchOS(*, reason: \(reason))" case .watchOSMajor(let major, let reason): return "watchOS(\(major).*, reason: \(reason))" case .watchOSMajorRange(let range, let reason): return "watchOS([\(range)], reason: \(reason))" case .watchOSMinor(let major, let minor, let reason): return "watchOS(\(major).\(minor), reason: \(reason))" case .watchOSMinorRange(let major, let minorRange, let reason): return "watchOS(\(major).[\(minorRange)], reason: \(reason))" case .watchOSBugFix(let major, let minor, let bugFix, let reason): return "watchOS(\(major).\(minor).\(bugFix), reason: \(reason))" case .watchOSBugFixRange(let major, let minor, let bugFixRange, let reason): return "watchOS(\(major).\(minor).[\(bugFixRange)], reason: \(reason))" case .watchOSSimulatorAny(let reason): return "watchOSSimulatorAny(*, reason: \(reason))" case .linuxAny(reason: let reason): return "linuxAny(*, reason: \(reason))" case .androidAny(reason: let reason): return "androidAny(*, reason: \(reason))" case .freeBSDAny(reason: let reason): return "freeBSDAny(*, reason: \(reason))" case .ps4Any(reason: let reason): return "ps4Any(*, reason: \(reason))" case .windowsAny(reason: let reason): return "windowsAny(*, reason: \(reason))" case .windowsCygnusAny(reason: let reason): return "windowsCygnusAny(*, reason: \(reason))" case .haikuAny(reason: let reason): return "haikuAny(*, reason: \(reason))" case .objCRuntime(let reason): return "Objective-C runtime, reason: \(reason))" case .nativeRuntime(let reason): return "Native runtime (no ObjC), reason: \(reason))" } } public func evaluate() -> Bool { switch self { case .custom(let predicate, _): return predicate() case .always: return true case .never: return false case .osxAny: switch _getRunningOSVersion() { case .osx: return true default: return false } case .osxMajor(let major, _): switch _getRunningOSVersion() { case .osx(major, _, _): return true default: return false } case .osxMinor(let major, let minor, _): switch _getRunningOSVersion() { case .osx(major, minor, _): return true default: return false } case .osxMinorRange(let major, let minorRange, _): switch _getRunningOSVersion() { case .osx(major, let runningMinor, _): return minorRange.contains(runningMinor) default: return false } case .osxBugFix(let major, let minor, let bugFix, _): switch _getRunningOSVersion() { case .osx(major, minor, bugFix): return true default: return false } case .osxBugFixRange(let major, let minor, let bugFixRange, _): switch _getRunningOSVersion() { case .osx(major, minor, let runningBugFix): return bugFixRange.contains(runningBugFix) default: return false } case .iOSAny: switch _getRunningOSVersion() { case .iOS: return true default: return false } case .iOSMajor(let major, _): switch _getRunningOSVersion() { case .iOS(major, _, _): return true default: return false } case .iOSMajorRange(let range, _): switch _getRunningOSVersion() { case .iOS(let major, _, _): return range.contains(major) default: return false } case .iOSMinor(let major, let minor, _): switch _getRunningOSVersion() { case .iOS(major, minor, _): return true default: return false } case .iOSMinorRange(let major, let minorRange, _): switch _getRunningOSVersion() { case .iOS(major, let runningMinor, _): return minorRange.contains(runningMinor) default: return false } case .iOSBugFix(let major, let minor, let bugFix, _): switch _getRunningOSVersion() { case .iOS(major, minor, bugFix): return true default: return false } case .iOSBugFixRange(let major, let minor, let bugFixRange, _): switch _getRunningOSVersion() { case .iOS(major, minor, let runningBugFix): return bugFixRange.contains(runningBugFix) default: return false } case .iOSSimulatorAny: switch _getRunningOSVersion() { case .iOSSimulator: return true default: return false } case .tvOSAny: switch _getRunningOSVersion() { case .tvOS: return true default: return false } case .tvOSMajor(let major, _): switch _getRunningOSVersion() { case .tvOS(major, _, _): return true default: return false } case .tvOSMajorRange(let range, _): switch _getRunningOSVersion() { case .tvOS(let major, _, _): return range.contains(major) default: return false } case .tvOSMinor(let major, let minor, _): switch _getRunningOSVersion() { case .tvOS(major, minor, _): return true default: return false } case .tvOSMinorRange(let major, let minorRange, _): switch _getRunningOSVersion() { case .tvOS(major, let runningMinor, _): return minorRange.contains(runningMinor) default: return false } case .tvOSBugFix(let major, let minor, let bugFix, _): switch _getRunningOSVersion() { case .tvOS(major, minor, bugFix): return true default: return false } case .tvOSBugFixRange(let major, let minor, let bugFixRange, _): switch _getRunningOSVersion() { case .tvOS(major, minor, let runningBugFix): return bugFixRange.contains(runningBugFix) default: return false } case .tvOSSimulatorAny: switch _getRunningOSVersion() { case .tvOSSimulator: return true default: return false } case .watchOSAny: switch _getRunningOSVersion() { case .watchOS: return true default: return false } case .watchOSMajor(let major, _): switch _getRunningOSVersion() { case .watchOS(major, _, _): return true default: return false } case .watchOSMajorRange(let range, _): switch _getRunningOSVersion() { case .watchOS(let major, _, _): return range.contains(major) default: return false } case .watchOSMinor(let major, let minor, _): switch _getRunningOSVersion() { case .watchOS(major, minor, _): return true default: return false } case .watchOSMinorRange(let major, let minorRange, _): switch _getRunningOSVersion() { case .watchOS(major, let runningMinor, _): return minorRange.contains(runningMinor) default: return false } case .watchOSBugFix(let major, let minor, let bugFix, _): switch _getRunningOSVersion() { case .watchOS(major, minor, bugFix): return true default: return false } case .watchOSBugFixRange(let major, let minor, let bugFixRange, _): switch _getRunningOSVersion() { case .watchOS(major, minor, let runningBugFix): return bugFixRange.contains(runningBugFix) default: return false } case .watchOSSimulatorAny: switch _getRunningOSVersion() { case .watchOSSimulator: return true default: return false } case .linuxAny: switch _getRunningOSVersion() { case .linux: return true default: return false } case .androidAny: switch _getRunningOSVersion() { case .android: return true default: return false } case .freeBSDAny: switch _getRunningOSVersion() { case .freeBSD: return true default: return false } case .ps4Any: switch _getRunningOSVersion() { case .ps4: return true default: return false } case .windowsAny: switch _getRunningOSVersion() { case .windowsCygnus: return true case .windows: return true default: return false } case .windowsCygnusAny: switch _getRunningOSVersion() { case .windowsCygnus: return true default: return false } case .haikuAny: switch _getRunningOSVersion() { case .haiku: return true default: return false } case .objCRuntime: #if _runtime(_ObjC) return true #else return false #endif case .nativeRuntime: #if _runtime(_ObjC) return false #else return true #endif } } } // // Semantic tests for protocol conformance // /// Test that the elements of `instances` satisfy the semantic /// requirements of `Equatable`, using `oracle` to generate equality /// expectations from pairs of positions in `instances`. /// /// - Note: `oracle` is also checked for conformance to the /// laws. public func checkEquatable<Instances : Collection>( _ instances: Instances, oracle: (Instances.Index, Instances.Index) -> Bool, allowBrokenTransitivity: Bool = false, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) where Instances.Element : Equatable { let indices = Array(instances.indices) _checkEquatableImpl( Array(instances), oracle: { oracle(indices[$0], indices[$1]) }, allowBrokenTransitivity: allowBrokenTransitivity, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } internal func _checkEquatableImpl<Instance : Equatable>( _ instances: [Instance], oracle: (Int, Int) -> Bool, allowBrokenTransitivity: Bool = false, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { // For each index (which corresponds to an instance being tested) track the // set of equal instances. var transitivityScoreboard: [Box<Set<Int>>] = instances.indices.map { _ in Box(Set()) } // TODO: swift-3-indexing-model: add tests for this function. for i in instances.indices { let x = instances[i] expectTrue(oracle(i, i), "bad oracle: broken reflexivity at index \(i)") for j in instances.indices { let y = instances[j] let predictedXY = oracle(i, j) expectEqual( predictedXY, oracle(j, i), "bad oracle: broken symmetry between indices \(i), \(j)", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) let isEqualXY = x == y expectEqual( predictedXY, isEqualXY, """ \((predictedXY ? "expected equal, found not equal" : "expected not equal, found equal")) lhs (at index \(i)): \(String(reflecting: x)) rhs (at index \(j)): \(String(reflecting: y)) """, stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) // Not-equal is an inverse of equal. expectNotEqual( isEqualXY, x != y, """ lhs (at index \(i)): \(String(reflecting: x)) rhs (at index \(j)): \(String(reflecting: y)) """, stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) if !allowBrokenTransitivity { // Check transitivity of the predicate represented by the oracle. // If we are adding the instance `j` into an equivalence set, check that // it is equal to every other instance in the set. if predictedXY && i < j && transitivityScoreboard[i].value.insert(j).inserted { if transitivityScoreboard[i].value.count == 1 { transitivityScoreboard[i].value.insert(i) } for k in transitivityScoreboard[i].value { expectTrue( oracle(j, k), "bad oracle: broken transitivity at indices \(i), \(j), \(k)", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) // No need to check equality between actual values, we will check // them with the checks above. } precondition(transitivityScoreboard[j].value.isEmpty) transitivityScoreboard[j] = transitivityScoreboard[i] } } } } } public func checkEquatable<T : Equatable>( _ expectedEqual: Bool, _ lhs: T, _ rhs: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { checkEquatable( [lhs, rhs], oracle: { expectedEqual || $0 == $1 }, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) } /// Produce an integer hash value for `value` by feeding it to a dedicated /// `Hasher`. This is always done by calling the `hash(into:)` method. /// If a non-nil `seed` is given, it is used to perturb the hasher state; /// this is useful for resolving accidental hash collisions. internal func hash<H: Hashable>(_ value: H, seed: Int? = nil) -> Int { var hasher = Hasher() if let seed = seed { hasher.combine(seed) } hasher.combine(value) return hasher.finalize() } /// Test that the elements of `groups` consist of instances that satisfy the /// semantic requirements of `Hashable`, with each group defining a distinct /// equivalence class under `==`. public func checkHashableGroups<Groups: Collection>( _ groups: Groups, _ message: @autoclosure () -> String = "", allowIncompleteHashing: Bool = false, stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) where Groups.Element: Collection, Groups.Element.Element: Hashable { let instances = groups.flatMap { $0 } // groupIndices[i] is the index of the element in groups that contains // instances[i]. let groupIndices = zip(0..., groups).flatMap { i, group in group.map { _ in i } } func equalityOracle(_ lhs: Int, _ rhs: Int) -> Bool { return groupIndices[lhs] == groupIndices[rhs] } checkHashable( instances, equalityOracle: equalityOracle, hashEqualityOracle: equalityOracle, allowBrokenTransitivity: false, allowIncompleteHashing: allowIncompleteHashing, stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) } /// Test that the elements of `instances` satisfy the semantic requirements of /// `Hashable`, using `equalityOracle` to generate equality and hashing /// expectations from pairs of positions in `instances`. public func checkHashable<Instances: Collection>( _ instances: Instances, equalityOracle: (Instances.Index, Instances.Index) -> Bool, allowBrokenTransitivity: Bool = false, allowIncompleteHashing: Bool = false, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) where Instances.Element: Hashable { checkHashable( instances, equalityOracle: equalityOracle, hashEqualityOracle: equalityOracle, allowBrokenTransitivity: allowBrokenTransitivity, allowIncompleteHashing: allowIncompleteHashing, stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) } /// Test that the elements of `instances` satisfy the semantic /// requirements of `Hashable`, using `equalityOracle` to generate /// equality expectations from pairs of positions in `instances`, /// and `hashEqualityOracle` to do the same for hashing. public func checkHashable<Instances: Collection>( _ instances: Instances, equalityOracle: (Instances.Index, Instances.Index) -> Bool, hashEqualityOracle: (Instances.Index, Instances.Index) -> Bool, allowBrokenTransitivity: Bool = false, allowIncompleteHashing: Bool = false, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) where Instances.Element: Hashable { checkEquatable( instances, oracle: equalityOracle, allowBrokenTransitivity: allowBrokenTransitivity, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) for i in instances.indices { let x = instances[i] for j in instances.indices { let y = instances[j] let predicted = hashEqualityOracle(i, j) expectEqual( predicted, hashEqualityOracle(j, i), "bad hash oracle: broken symmetry between indices \(i), \(j)", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) if x == y { expectTrue( predicted, """ bad hash oracle: equality must imply hash equality lhs (at index \(i)): \(x) rhs (at index \(j)): \(y) """, stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } if predicted { expectEqual( hash(x), hash(y), """ hash(into:) expected to match, found to differ lhs (at index \(i)): \(x) rhs (at index \(j)): \(y) """, stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) expectEqual( x.hashValue, y.hashValue, """ hashValue expected to match, found to differ lhs (at index \(i)): \(x) rhs (at index \(j)): \(y) """, stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) expectEqual( x._rawHashValue(seed: 0), y._rawHashValue(seed: 0), """ _rawHashValue(seed:) expected to match, found to differ lhs (at index \(i)): \(x) rhs (at index \(j)): \(y) """, stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } else if !allowIncompleteHashing { // Try a few different seeds; at least one of them should discriminate // between the hashes. It is extremely unlikely this check will fail // all ten attempts, unless the type's hash encoding is not unique, // or unless the hash equality oracle is wrong. expectTrue( (0..<10).contains { hash(x, seed: $0) != hash(y, seed: $0) }, """ hash(into:) expected to differ, found to match lhs (at index \(i)): \(x) rhs (at index \(j)): \(y) """, stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) expectTrue( (0..<10).contains { i in x._rawHashValue(seed: i) != y._rawHashValue(seed: i) }, """ _rawHashValue(seed:) expected to differ, found to match lhs (at index \(i)): \(x) rhs (at index \(j)): \(y) """, stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } } } public func checkHashable<T : Hashable>( expectedEqual: Bool, _ lhs: T, _ rhs: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { checkHashable( [lhs, rhs], equalityOracle: { expectedEqual || $0 == $1 }, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } public enum ExpectedComparisonResult { case lt, eq, gt public func isLT() -> Bool { return self == .lt } public func isEQ() -> Bool { return self == .eq } public func isGT() -> Bool { return self == .gt } public func isLE() -> Bool { return isLT() || isEQ() } public func isGE() -> Bool { return isGT() || isEQ() } public func isNE() -> Bool { return !isEQ() } public func flip() -> ExpectedComparisonResult { switch self { case .lt: return .gt case .eq: return .eq case .gt: return .lt } } } extension ExpectedComparisonResult : CustomStringConvertible { public var description: String { switch self { case .lt: return "<" case .eq: return "==" case .gt: return ">" } } } /// Test that the elements of `instances` satisfy the semantic /// requirements of `Comparable`, using `oracle` to generate comparison /// expectations from pairs of positions in `instances`. /// /// - Note: `oracle` is also checked for conformance to the /// laws. public func checkComparable<Instances : Collection>( _ instances: Instances, oracle: (Instances.Index, Instances.Index) -> ExpectedComparisonResult, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) where Instances.Element : Comparable { // Also checks that equality is consistent with comparison and that // the oracle obeys the equality laws checkEquatable(instances, oracle: { oracle($0, $1).isEQ() }, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) for i in instances.indices { let x = instances[i] expectFalse( x < x, "found 'x < x'\n" + "at index \(i): \(String(reflecting: x))", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) expectFalse( x > x, "found 'x > x'\n" + "at index \(i): \(String(reflecting: x))", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) expectTrue(x <= x, "found 'x <= x' to be false\n" + "at index \(i): \(String(reflecting: x))", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) expectTrue(x >= x, "found 'x >= x' to be false\n" + "at index \(i): \(String(reflecting: x))", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) for j in instances.indices where i != j { let y = instances[j] let expected = oracle(i, j) expectEqual( expected.flip(), oracle(j, i), "bad oracle: missing antisymmetry: " + "(\(String(reflecting: i)), \(String(reflecting: j)))", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) expectEqual(expected.isLT(), x < y, "x < y\n" + "lhs (at index \(i)): \(String(reflecting: x))\n" + "rhs (at index \(j)): \(String(reflecting: y))", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) expectEqual(expected.isLE(), x <= y, "x <= y\n" + "lhs (at index \(i)): \(String(reflecting: x))\n" + "rhs (at index \(j)): \(String(reflecting: y))", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) expectEqual(expected.isGE(), x >= y, "x >= y\n" + "lhs (at index \(i)): \(String(reflecting: x))\n" + "rhs (at index \(j)): \(String(reflecting: y))", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) expectEqual(expected.isGT(), x > y, "x > y\n" + "lhs (at index \(i)): \(String(reflecting: x))\n" + "rhs (at index \(j)): \(String(reflecting: y))", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) for k in instances.indices { let expected2 = oracle(j, k) if expected == expected2 { expectEqual( expected, oracle(i, k), "bad oracle: missing transitivity " + "(\(String(reflecting: i)), \(String(reflecting: j)), " + "\(String(reflecting: k)))", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } } } } public func checkComparable<T : Comparable>( _ expected: ExpectedComparisonResult, _ lhs: T, _ rhs: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { checkComparable( [lhs, rhs], oracle: { [[ .eq, expected], [ expected.flip(), .eq]][$0][$1] }, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } /// Test that the elements of `instances` satisfy the semantic /// requirements of `Strideable`, using `advanceOracle` and /// 'distanceOracle' to generate expectations about the results of /// `advanced(by:)` and `distance(to:)` from pairs of positions in /// `instances` and `strides`. /// /// - Note: `oracle` is also checked for conformance to the /// laws. public func checkStrideable<Instances : Collection, Strides : Collection>( _ instances: Instances, strides: Strides, distanceOracle: (Instances.Index, Instances.Index) -> Strides.Element, advanceOracle: (Instances.Index, Strides.Index) -> Instances.Element, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) where Instances.Element : Strideable, Instances.Element.Stride == Strides.Element { checkComparable( instances, oracle: { let d = distanceOracle($1, $0); return d < 0 ? .lt : d == 0 ? .eq : .gt }, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) for i in instances.indices { let x = instances[i] expectEqual(x, x.advanced(by: 0)) for j in strides.indices { let y = strides[j] expectEqual(advanceOracle(i, j), x.advanced(by: y)) } for j in instances.indices { let y = instances[j] expectEqual(distanceOracle(i, j), x.distance(to: y)) } } } public func checkLosslessStringConvertible<Instance>( _ instances: [Instance] ) where Instance : LosslessStringConvertible & Equatable { expectEqualFunctionsForDomain(instances, { $0 }, { Instance(String($0))! }) } public func nthIndex<C: Collection>(_ x: C, _ n: Int) -> C.Index { return x.index(x.startIndex, offsetBy: n) } public func nth<C: Collection>(_ x: C, _ n: Int) -> C.Element { return x[nthIndex(x, n)] } public func expectEqualSequence< Expected: Sequence, Actual: Sequence >( _ expected: Expected, _ actual: Actual, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) where Expected.Element == Actual.Element, Expected.Element : Equatable { expectEqualSequence(expected, actual, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) { $0 == $1 } } public func expectEqualSequence< Expected : Sequence, Actual : Sequence, T : Equatable, U : Equatable >( _ expected: Expected, _ actual: Actual, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) where Expected.Element == Actual.Element, Expected.Element == (T, U) { expectEqualSequence( expected, actual, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) { (lhs: (T, U), rhs: (T, U)) -> Bool in lhs.0 == rhs.0 && lhs.1 == rhs.1 } } public func expectEqualSequence< Expected: Sequence, Actual: Sequence >( _ expected: Expected, _ actual: Actual, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line, sameValue: (Expected.Element, Expected.Element) -> Bool ) where Expected.Element == Actual.Element { if !expected.elementsEqual(actual, by: sameValue) { expectationFailure("expected elements: \"\(expected)\"\n" + "actual: \"\(actual)\" (of type \(String(reflecting: type(of: actual))))", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectEqualsUnordered< Expected : Sequence, Actual : Sequence >( _ expected: Expected, _ actual: Actual, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line, compare: @escaping (Expected.Element, Expected.Element) -> ExpectedComparisonResult ) where Expected.Element == Actual.Element { let x: [Expected.Element] = expected.sorted { compare($0, $1).isLT() } let y: [Actual.Element] = actual.sorted { compare($0, $1).isLT() } expectEqualSequence( x, y, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), sameValue: { compare($0, $1).isEQ() }) } public func expectEqualsUnordered< Expected : Sequence, Actual : Sequence >( _ expected: Expected, _ actual: Actual, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) where Expected.Element == Actual.Element, Expected.Element : Comparable { expectEqualsUnordered(expected, actual, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) { $0 < $1 ? .lt : $0 == $1 ? .eq : .gt } } public func expectEqualsUnordered<T : Comparable>( _ expected: [T], _ actual: [T], _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { let x = expected.sorted() let y = actual.sorted() expectEqualSequence(x, y, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } public func expectEqualsUnordered<T : Strideable>( _ expected: Range<T>, _ actual: [T], _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) where T.Stride: SignedInteger { if expected.count != actual.count { expectationFailure("expected elements: \"\(expected)\"\n" + "actual: \"\(actual)\" (of type \(String(reflecting: type(of: actual))))", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } for e in actual { if !expected.contains(e) { expectationFailure("expected elements: \"\(expected)\"\n" + "actual: \"\(actual)\" (of type \(String(reflecting: type(of: actual))))", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } } /// A nominal type that is equivalent to a tuple of two elements. /// /// We need a nominal type because we can't add protocol conformances to /// tuples. struct Pair<T : Comparable> : Comparable { init(_ first: T, _ second: T) { self.first = first self.second = second } var first: T var second: T static func == <T>(lhs: Pair<T>, rhs: Pair<T>) -> Bool { return lhs.first == rhs.first && lhs.second == rhs.second } static func < <T>(lhs: Pair<T>, rhs: Pair<T>) -> Bool { return [lhs.first, lhs.second].lexicographicallyPrecedes( [rhs.first, rhs.second]) } } public func expectEqualsUnordered< Expected : Sequence, Actual : Sequence, T : Comparable >( _ expected: Expected, _ actual: Actual, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) where Actual.Element == (key: T, value: T), Expected.Element == (T, T) { func comparePairLess(_ lhs: (T, T), rhs: (T, T)) -> Bool { return [lhs.0, lhs.1].lexicographicallyPrecedes([rhs.0, rhs.1]) } let x: [(T, T)] = expected.sorted(by: comparePairLess) let y: [(T, T)] = actual.map { ($0.0, $0.1) } .sorted(by: comparePairLess) func comparePairEquals(_ lhs: (T, T), rhs: (key: T, value: T)) -> Bool { return lhs.0 == rhs.0 && lhs.1 == rhs.1 } expectEqualSequence(x, y, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), sameValue: comparePairEquals) } public func expectEqualFunctionsForDomain<ArgumentType, Result : Equatable>( _ arguments: [ArgumentType], _ function1: (ArgumentType) -> Result, _ function2: (ArgumentType) -> Result ) { for a in arguments { let expected = function1(a) let actual = function2(a) expectEqual(expected, actual, "where the argument is: \(a)") } } public func expectEqualMethodsForDomain< SelfType, ArgumentType, Result : Equatable >( _ selfs: [SelfType], _ arguments: [ArgumentType], _ function1: (SelfType) -> (ArgumentType) -> Result, _ function2: (SelfType) -> (ArgumentType) -> Result ) { for s in selfs { for a in arguments { let expected = function1(s)(a) let actual = function2(s)(a) expectEqual( expected, actual, "where the first argument is: \(s)\nand the second argument is: \(a)" ) } } } public func expectEqualUnicodeScalars<S: StringProtocol>( _ expected: [UInt32], _ actual: S, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line) { let actualUnicodeScalars = Array( actual.unicodeScalars.lazy.map { $0.value }) if !expected.elementsEqual(actualUnicodeScalars) { expectationFailure( "expected elements: \"\(asHex(expected))\"\n" + "actual: \"\(asHex(actualUnicodeScalars))\"", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } }
30.809983
125
0.643534
9097207889d4f752259e1d80e68710bee0176639
16,714
/* * Sentinel-Shuttle for Swift * * by Data Infrastructure * Template version * - 0.1.1 : first release * - 0.1.2 : log_id methods * - 0.1.3 : remove _$ssToken * - 0.1.4 : toDictionary() -> [String:Any] * - 0.1.5 : extra partition exception * * Author * - Sentinel Shuttle Generator v3.0 * - [email protected] (Data Infrastructure Team) */ import Foundation public class DiRakeClientTestIOsSentinelShuttle { public enum DiRakeClientTestIOsSentinelShuttleError: Error { case EmptyExtraPartitionFieldError(reason:String) } private static let _$ssTemplateVersion = "0.1.5" private static let _$ssVersion = "19.07.24:3.1.0:7" private static let _$ssSchemaId = "DiRakeClientTestIOs" private static let _$ssDelim = "\t" private static let _$logVersionKey = "log_version" private static let _$extraPartitionFieldKey = "" private static let headerFieldNameList:[String] = ["base_time", "local_time", "recv_time", "os_name", "os_version", "resolution", "screen_width", "screen_height", "language_code", "rake_lib", "rake_lib_version", "ip", "recv_host", "token", "log_version", "device_id", "device_model", "manufacturer", "carrier_name", "network_type", "app_release", "app_build_number", "browser_name", "browser_version", "referrer", "url", "document_title", "page_id", "action_id", "dmpc", "reserved02"] private static let bodyFieldNameList:[String] = ["context_id", "context_desc", "user_id", "ab_test_group"] private static let actionKeyNameList:[String] = ["page_id", "action_id"] // private static var bodyRule = [:] // String,Any? private static let encryptedFieldsList:[String] = ["device_id"] private var fieldsDictionary:[String:Any?] = [:] public init() { for headerFieldName in DiRakeClientTestIOsSentinelShuttle.headerFieldNameList { if headerFieldName == DiRakeClientTestIOsSentinelShuttle._$logVersionKey { self.fieldsDictionary.updateValue(DiRakeClientTestIOsSentinelShuttle._$ssVersion, forKey: DiRakeClientTestIOsSentinelShuttle._$logVersionKey) } else { self.fieldsDictionary.updateValue(nil, forKey: headerFieldName) } } for bodyFieldName in DiRakeClientTestIOsSentinelShuttle.bodyFieldNameList { self.fieldsDictionary.updateValue(nil, forKey: bodyFieldName) } } /* Methods */ public func base_time(_ base_time:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(base_time, forKey: "base_time") return self } public func local_time(_ local_time:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(local_time, forKey: "local_time") return self } public func recv_time(_ recv_time:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(recv_time, forKey: "recv_time") return self } public func os_name(_ os_name:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(os_name, forKey: "os_name") return self } public func os_version(_ os_version:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(os_version, forKey: "os_version") return self } public func resolution(_ resolution:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(resolution, forKey: "resolution") return self } public func screen_width(_ screen_width:Int?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(screen_width, forKey: "screen_width") return self } public func screen_height(_ screen_height:Int?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(screen_height, forKey: "screen_height") return self } public func language_code(_ language_code:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(language_code, forKey: "language_code") return self } public func rake_lib(_ rake_lib:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(rake_lib, forKey: "rake_lib") return self } public func rake_lib_version(_ rake_lib_version:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(rake_lib_version, forKey: "rake_lib_version") return self } public func ip(_ ip:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(ip, forKey: "ip") return self } public func recv_host(_ recv_host:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(recv_host, forKey: "recv_host") return self } public func token(_ token:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(token, forKey: "token") return self } public func device_id(_ device_id:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(device_id, forKey: "device_id") return self } public func device_model(_ device_model:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(device_model, forKey: "device_model") return self } public func manufacturer(_ manufacturer:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(manufacturer, forKey: "manufacturer") return self } public func carrier_name(_ carrier_name:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(carrier_name, forKey: "carrier_name") return self } public func network_type(_ network_type:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(network_type, forKey: "network_type") return self } public func app_release(_ app_release:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(app_release, forKey: "app_release") return self } public func app_build_number(_ app_build_number:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(app_build_number, forKey: "app_build_number") return self } public func browser_name(_ browser_name:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(browser_name, forKey: "browser_name") return self } public func browser_version(_ browser_version:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(browser_version, forKey: "browser_version") return self } public func referrer(_ referrer:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(referrer, forKey: "referrer") return self } public func url(_ url:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(url, forKey: "url") return self } public func document_title(_ document_title:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(document_title, forKey: "document_title") return self } public func page_id(_ page_id:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(page_id, forKey: "page_id") return self } public func action_id(_ action_id:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(action_id, forKey: "action_id") return self } public func dmpc(_ dmpc:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(dmpc, forKey: "dmpc") return self } public func reserved02(_ reserved02:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(reserved02, forKey: "reserved02") return self } public func context_id(_ context_id:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(context_id, forKey: "context_id") return self } public func context_desc(_ context_desc:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(context_desc, forKey: "context_desc") return self } public func user_id(_ user_id:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(user_id, forKey: "user_id") return self } public func ab_test_group(_ ab_test_group:String?) -> DiRakeClientTestIOsSentinelShuttle { self.fieldsDictionary.updateValue(ab_test_group, forKey: "ab_test_group") return self } public func setBodyOfpage1__action1(context_id:String?, context_desc:String?) -> DiRakeClientTestIOsSentinelShuttle { self.clearBody() self.fieldsDictionary.updateValue("page1", forKey: "page_id") self.fieldsDictionary.updateValue("action1", forKey: "action_id") self.fieldsDictionary.updateValue(context_id, forKey: "context_id") self.fieldsDictionary.updateValue(context_desc, forKey: "context_desc") return self } /* 12 public util functions */ public func toString() -> String { return self.toHBString() } public func toHBString() -> String { return self.toHBString(DiRakeClientTestIOsSentinelShuttle._$ssDelim) } public func toHBString(_ delim:String) -> String { do { return try "\(self.headerToString(delim))\(self.bodyToString())" } catch DiRakeClientTestIOsSentinelShuttleError.EmptyExtraPartitionFieldError(let reason) { print("\(self) \(reason)"); return "" } } public func headerToString(_ delim:String) throws -> String { var headerString = "" for fieldName in DiRakeClientTestIOsSentinelShuttle.headerFieldNameList { var valueString = "" if let value = self.fieldsDictionary[fieldName] { if value is String { valueString = self.getEscapedValue(value as! String) } else if value is [AnyHashable:Any] { valueString = self.convertFromDictionaryToString(value as! [AnyHashable : Any]) } else { valueString = String(describing: value) //FIXME is it right? } } else { // extra partition field는 빈값이어서는 안된다. if DiRakeClientTestIOsSentinelShuttle._$extraPartitionFieldKey == fieldName { throw DiRakeClientTestIOsSentinelShuttleError.EmptyExtraPartitionFieldError(reason: "\(self) \(fieldName) should not be empty.") } } headerString = headerString.appending("\(valueString)\(delim)") } return headerString } public func clearBody() { for bodyFieldName in DiRakeClientTestIOsSentinelShuttle.bodyFieldNameList { self.fieldsDictionary.updateValue(nil, forKey: bodyFieldName) } } public func getBody() -> [String:Any] { var body:[String:Any] = [:] for bodyFieldName in DiRakeClientTestIOsSentinelShuttle.bodyFieldNameList { let bodyFieldValue = self.fieldsDictionary[bodyFieldName]! if bodyFieldValue != nil { body.updateValue(bodyFieldValue!, forKey: bodyFieldName) } } return body } public func bodyToString() -> String { do { let jsonData = try JSONSerialization.data(withJSONObject: self.getBody(), options: JSONSerialization.WritingOptions(rawValue: 0)) let jsonString = String.init(data: jsonData, encoding: String.Encoding.utf8)! return self.getEscapedValue(jsonString) } catch let error { print("\(self) bodyToString() failed: \(error)") return "{}" } } public static func getSentinelMeta() -> [String:[String:Any]] { var fieldOrder:[String:Int] = [:] for (index, headerFieldName) in DiRakeClientTestIOsSentinelShuttle.headerFieldNameList.enumerated() { fieldOrder.updateValue(index, forKey: headerFieldName) } fieldOrder.updateValue(DiRakeClientTestIOsSentinelShuttle.headerFieldNameList.count, forKey: "_$body") return [ "sentinel_meta": [ "_$schemaId": DiRakeClientTestIOsSentinelShuttle._$ssSchemaId, "_$fieldOrder": fieldOrder, "_$encryptionFields": DiRakeClientTestIOsSentinelShuttle.encryptedFieldsList, "_$projectId": "" ] ] } public static func toDictionary(_ dict:[String:Any?]) throws -> [String:Any] { var sentinelDictionary:[String:Any] = [:] var bodyDictionary:[String:Any] = [:] if DiRakeClientTestIOsSentinelShuttle._$extraPartitionFieldKey != "" { if !dict.keys.contains(DiRakeClientTestIOsSentinelShuttle._$extraPartitionFieldKey) { throw DiRakeClientTestIOsSentinelShuttleError.EmptyExtraPartitionFieldError(reason: "\(self) \(DiRakeClientTestIOsSentinelShuttle._$extraPartitionFieldKey) should be exist.") } } for fieldName in DiRakeClientTestIOsSentinelShuttle.headerFieldNameList { if let value = dict[fieldName] { sentinelDictionary.updateValue(value!, forKey: fieldName) } else { sentinelDictionary.updateValue("", forKey: fieldName) } } sentinelDictionary.updateValue(DiRakeClientTestIOsSentinelShuttle._$ssVersion, forKey: DiRakeClientTestIOsSentinelShuttle._$logVersionKey) for fieldName in DiRakeClientTestIOsSentinelShuttle.bodyFieldNameList { if let value = dict[fieldName] { bodyDictionary.updateValue(value!, forKey: fieldName) } } sentinelDictionary.updateValue(bodyDictionary, forKey: "_$body") sentinelDictionary.updateValue(self.getSentinelMeta()["sentinel_meta"]!, forKey: "sentinel_meta") return sentinelDictionary } public func toDictionary() throws -> [String:Any] { var properties:[String:Any] = [:] // header for headerFieldName in DiRakeClientTestIOsSentinelShuttle.headerFieldNameList { var valueString = "" if let value = self.fieldsDictionary[headerFieldName]! { if value is String { valueString = self.getEscapedValue(value as! String) } else { valueString = String(describing: value) } } else { if DiRakeClientTestIOsSentinelShuttle._$extraPartitionFieldKey == headerFieldName { throw DiRakeClientTestIOsSentinelShuttleError.EmptyExtraPartitionFieldError(reason: "\(self) \(headerFieldName) should not be empty.") } } properties.updateValue(valueString, forKey: headerFieldName) } // body properties.updateValue(self.getBody(), forKey: "_$body") // sentinel_meta properties.updateValue(DiRakeClientTestIOsSentinelShuttle.getSentinelMeta()["sentinel_meta"]!, forKey: "sentinel_meta") return properties } public func toJSONString() -> String { do { let jsonData = try JSONSerialization.data(withJSONObject: self.toDictionary(), options: JSONSerialization.WritingOptions.prettyPrinted) return String.init(data: jsonData, encoding: String.Encoding.utf8)! } catch let error { print("\(self) toJSONString() failed: \(error)") return "{}" } } public func getEscapedValue(_ value:String) -> String { return value.replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: "\\t").replacingOccurrences(of: "\r", with: "\\r") } func convertFromDictionaryToString(_ dict:[AnyHashable:Any]) -> String { do { let jsonData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions(rawValue: 0)) return String.init(data: jsonData, encoding: String.Encoding.utf8)! } catch let error { print("\(self) convertFromDictionaryToString() failed: \(error)") return "{}" } } }
39.234742
488
0.67243
ff8faa2b3451469891c25400951b323ecbe0f852
330
import Vapor extension Droplet { func setupRoutes() throws { // Register the routes from the custom controllers // With the current droplet ProjectController(drop: self).configureRoutes() UserController(drop: self).configureRoutes() JWTController(drop: self).configureRoutes() } }
27.5
58
0.675758
290e694dcfc7ff6c5b2be09fce51f1b67568253a
138
struct CarFactory: Factory { typealias ModelType = Car static func build(value: [String: Any] = [:]) -> Car { return Car() } }
17.25
56
0.615942
ef3e79dc38bb9ac70d22e289a84a7c2ad4ab1ac7
2,144
// // MenuController.swift // SpeakSelectionDemo // // Created by Adam Niepokój on 13/06/2021. // import UIKit /// An abstraction describing menu controller. protocol MenuController: AnyObject { /// A flag determining if menu is visible. var isMenuVisible: Bool { get } /// Menu items. var menuItems: [UIMenuItem]? { get set } /// Sets the area in a view above or below which the editing menu is positioned. /// /// - Parameters: /// - menuVisible: true if the menu should be shown, false if it should be hidden. /// - animated: true if the showing or hiding of the menu should be animated, otherwise false. func setTargetRect(_ targetRect: CGRect, in targetView: UIView) /// Shows or hides the editing menu, optionally animating the action. /// - Parameters: /// - targetRect: a rectangle that defines the area that is to be the target of the menu commands. /// - targetView: the view in which targetRect appears. func setMenuVisible(_ menuVisible: Bool, animated: Bool) } extension UIMenuController: MenuController {} // MARK: - Implementation details extension MenuController { /// Shows menu controller for selectable view. /// /// - Parameters: /// - selectableView: a selectable view. /// - animated: a animation flag. func show( in selectableView: SelectableView, animated: Bool ) { guard !isMenuVisible else { return } selectableView.selectionOverlay.isHidden = false menuItems = selectableView.menuActions setTargetRect(selectableView.viewRect, in: selectableView) setMenuVisible(true, animated: animated) } /// Hides menu controller for selectable view. /// /// - Parameters: /// - selectableView: a selectable view. /// - animated: a animation flag. func hide( in selectableView: SelectableView, animated: Bool ) { guard isMenuVisible else { return } selectableView.selectionOverlay.isHidden = true menuItems = nil setMenuVisible(false, animated: animated) } }
30.628571
106
0.655317
62bd56ea41e3305a93905996e5796c67e82f67c0
438
// // NSAttributedString+Extensions.swift // MaterialTextView // // Created by Mikhail Motyzhenkov on 13/03/2019. // Copyright © 2019 QIWI. All rights reserved. // import Foundation import UIKit extension NSParagraphStyle { static var materialTextViewDefault: NSParagraphStyle { let para = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle para.minimumLineHeight = 16 para.lineSpacing = 4 return para } }
21.9
79
0.76484
fc79f6c393c25cfdf20e119918746db71758c751
751
// // BaseVC.swift // p2p wallet // // Created by Chung Tran on 10/23/20. // import Foundation import RxSwift class BaseVC: BEViewController { let disposeBag = DisposeBag() var scrollViewAvoidingTabBar: UIScrollView? {nil} deinit { debugPrint("\(String(describing: self)) deinited") } override func setUp() { super.setUp() view.backgroundColor = .background adjustContentInsetToFitTabBar() } func adjustContentInsetToFitTabBar() { scrollViewAvoidingTabBar?.contentInset = scrollViewAvoidingTabBar?.contentInset.modifying(dBottom: 20) ?? .zero } func forceResizeModal() { view.layoutIfNeeded() preferredContentSize.height += 1 } }
22.088235
119
0.6498
676ad826e24c13ad848e2c436dd883953a522732
786
// // CreatePasscodePresenter.swift // AptoSDK // // Created by Takeichi Kanzaki on 21/11/2019. // import Foundation import AptoSDK class CreatePasscodePresenter: CreatePasscodePresenterProtocol { var router: CreatePasscodeModuleProtocol? var interactor: CreatePasscodeInteractorProtocol? var viewModel = CreatePasscodeViewModel() var analyticsManager: AnalyticsServiceProtocol? func viewLoaded() { analyticsManager?.track(event: .createPasscodeStart) } func closeTapped() { router?.close() } func pinEntered(_ code: String) { interactor?.save(code: code) { [weak self] result in switch result { case .failure(let error): self?.viewModel.error.send(error) case .success: self?.router?.finish() } } } }
21.833333
64
0.699746
0e643c530b1b27ba3c8c7ddfc60a7bd797f55525
105
// // File.swift // CooeeReactNativeExample // // Created by wp 02 on 20/04/21. // import Foundation
11.666667
33
0.657143
89644e82bce7f4ae1ffb4a6e54cbcf2f82ede5a1
1,887
// // ViewController.swift // Project 01 - StopWatchMeow // // Created by MichaelChen on 2017/1/20. // Copyright © 2017年 MichaelChen. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var startButton: UIButton! @IBOutlet weak var pauseButton: UIButton! var counter = 0.0 var timer = Timer() var isPlaying = false override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. timeLabel.text = String(counter) pauseButton.isEnabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func StartTimer(_ sender: Any) { if (isPlaying) { return } startButton.isEnabled = false pauseButton.isEnabled = true timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.updataTimer), userInfo: nil, repeats: true) isPlaying = true } @IBAction func PauseTimer(_ sender: Any) { startButton.isEnabled = true pauseButton.isEnabled = true timer.invalidate() isPlaying = false } @IBAction func Reset(_ sender: Any) { startButton.isEnabled = true pauseButton.isEnabled = true timer.invalidate() isPlaying = false counter = 0.0 timeLabel.text = String(counter) } func updataTimer() { counter += 0.1 timeLabel.text = String(format: "%.1f", counter) } }
25.16
148
0.614202